Merge pull request #617 from IronApollo/vault-fix

Fix vault, remove 1.14 and DummyFawe
Dieser Commit ist enthalten in:
NotMyFault 2020-09-16 18:06:57 +02:00 committet von GitHub
Commit 4f6c904615
Es konnte kein GPG-Schlüssel zu dieser Signatur gefunden werden
GPG-Schlüssel-ID: 4AEE18F83AFDEB23
22 geänderte Dateien mit 32 neuen und 26016 gelöschten Zeilen

Datei anzeigen

@ -16,7 +16,7 @@ FAWE is a fork of WorldEdit that has huge speed and memory improvements and cons
* [JavaDocs](https://ci.athion.net/job/FastAsyncWorldEdit-1.16/javadoc/) * [JavaDocs](https://ci.athion.net/job/FastAsyncWorldEdit-1.16/javadoc/)
## Downloads ## Downloads
### 1.14+ ### 1.15+
* [Download](https://intellectualsites.github.io/download/fawe.html) * [Download](https://intellectualsites.github.io/download/fawe.html)
* [Jenkins](https://ci.athion.net/job/FastAsyncWorldEdit-1.16/) * [Jenkins](https://ci.athion.net/job/FastAsyncWorldEdit-1.16/)

Datei anzeigen

@ -12,7 +12,7 @@ repositories {
maven { url = uri("https://repo.codemc.org/repository/maven-public") } maven { url = uri("https://repo.codemc.org/repository/maven-public") }
maven { url = uri("https://papermc.io/repo/repository/maven-public/") } maven { url = uri("https://papermc.io/repo/repository/maven-public/") }
maven { url = uri("https://maven.enginehub.org/repo/") } maven { url = uri("https://maven.enginehub.org/repo/") }
maven { url = uri("http://ci.emc.gs/nexus/content/groups/aikar/") } maven { url = uri("https://ci.emc.gs/nexus/content/groups/aikar/") }
maven { url = uri("https://ci.athion.net/plugin/repository/tools/") } maven { url = uri("https://ci.athion.net/plugin/repository/tools/") }
maven { maven {
this.name = "JitPack" this.name = "JitPack"
@ -39,7 +39,6 @@ dependencies {
"api"(project(":worldedit-core")) "api"(project(":worldedit-core"))
"api"(project(":worldedit-libs:bukkit")) "api"(project(":worldedit-libs:bukkit"))
"compile"(":worldedit-adapters:") "compile"(":worldedit-adapters:")
"compile"("org.spigotmcv1_14_r1:spigotmcv1_14_r1:1_14_r1")
"compile"("org.spigotmcv1_15_r1:spigotmcv1_15_r1:1_15_r1") "compile"("org.spigotmcv1_15_r1:spigotmcv1_15_r1:1_15_r1")
"compile"("org.spigotmcv1_16_r1:spigotmcv1_16_r1:1_16_r1") "compile"("org.spigotmcv1_16_r1:spigotmcv1_16_r1:1_16_r1")
"implementation"("it.unimi.dsi:fastutil:${Versions.FAST_UTIL}") "implementation"("it.unimi.dsi:fastutil:${Versions.FAST_UTIL}")
@ -61,6 +60,8 @@ dependencies {
exclude("com.sk89q.worldedit.worldedit-libs", "bukkit") exclude("com.sk89q.worldedit.worldedit-libs", "bukkit")
exclude("com.sk89q.worldedit.worldedit-libs", "core") exclude("com.sk89q.worldedit.worldedit-libs", "core")
} }
"compile"("org.bstats:bstats-bukkit:1.7")
// Third party
"implementation"("com.github.InventivetalentDev:MapManager:1.7.+") { isTransitive = false } "implementation"("com.github.InventivetalentDev:MapManager:1.7.+") { isTransitive = false }
"implementation"("com.github.TechFortress:GriefPrevention:16.+") { isTransitive = false } "implementation"("com.github.TechFortress:GriefPrevention:16.+") { isTransitive = false }
"implementation"("com.massivecraft:mcore:7.0.1") { isTransitive = false } "implementation"("com.massivecraft:mcore:7.0.1") { isTransitive = false }
@ -107,6 +108,9 @@ tasks.named<ShadowJar>("shadowJar") {
relocate("it.unimi.dsi.fastutil", "com.sk89q.worldedit.bukkit.fastutil") { relocate("it.unimi.dsi.fastutil", "com.sk89q.worldedit.bukkit.fastutil") {
include(dependency("it.unimi.dsi:fastutil")) include(dependency("it.unimi.dsi:fastutil"))
} }
relocate("org.bstats", "com.boydti.metrics") {
include(dependency("org.bstats:bstats-bukkit:1.7"))
}
} }
} }

Datei anzeigen

@ -53,7 +53,6 @@ public class FaweBukkit implements IFawe, Listener {
private static final Logger log = LoggerFactory.getLogger(FaweBukkit.class); private static final Logger log = LoggerFactory.getLogger(FaweBukkit.class);
private final Plugin plugin; private final Plugin plugin;
private VaultUtil vault;
private ItemUtil itemUtil; private ItemUtil itemUtil;
private boolean listeningImages; private boolean listeningImages;
@ -61,10 +60,6 @@ public class FaweBukkit implements IFawe, Listener {
private CFIPacketListener packetListener; private CFIPacketListener packetListener;
private final boolean chunksStretched; private final boolean chunksStretched;
public VaultUtil getVault() {
return this.vault;
}
public FaweBukkit(Plugin plugin) { public FaweBukkit(Plugin plugin) {
this.plugin = plugin; this.plugin = plugin;
try { try {
@ -87,9 +82,6 @@ public class FaweBukkit implements IFawe, Listener {
chunksStretched = chunksStretched =
Integer.parseInt(Bukkit.getBukkitVersion().split("-")[0].split("\\.")[1]) >= 16; Integer.parseInt(Bukkit.getBukkitVersion().split("-")[0].split("\\.")[1]) >= 16;
//Vault is Spigot/Paper only so this needs to be done in the Bukkit module
TaskManager.IMP.later(this::setupVault, 0);
//PlotSquared support is limited to Spigot/Paper as of 02/20/2020 //PlotSquared support is limited to Spigot/Paper as of 02/20/2020
TaskManager.IMP.later(this::setupPlotSquared, 0); TaskManager.IMP.later(this::setupPlotSquared, 0);
@ -177,13 +169,6 @@ public class FaweBukkit implements IFawe, Listener {
return tmp; return tmp;
} }
private void setupVault() {
try {
this.vault = new VaultUtil();
} catch (final Throwable ignored) {
}
}
@Override public String getDebugInfo() { @Override public String getDebugInfo() {
StringBuilder msg = new StringBuilder(); StringBuilder msg = new StringBuilder();
msg.append("Server Version: ").append(Bukkit.getVersion()).append("\n"); msg.append("Server Version: ").append(Bukkit.getVersion()).append("\n");

Datei anzeigen

@ -1,157 +0,0 @@
package com.boydti.fawe.bukkit.adapter.mc1_14;
import com.sk89q.util.ReflectionUtil;
import com.sk89q.worldedit.world.registry.BlockMaterial;
import net.minecraft.server.v1_14_R1.Block;
import net.minecraft.server.v1_14_R1.BlockAccessAir;
import net.minecraft.server.v1_14_R1.BlockPosition;
import net.minecraft.server.v1_14_R1.EnumPistonReaction;
import net.minecraft.server.v1_14_R1.IBlockData;
import net.minecraft.server.v1_14_R1.ITileEntity;
import net.minecraft.server.v1_14_R1.Material;
import org.bukkit.craftbukkit.v1_14_R1.block.data.CraftBlockData;
public class BlockMaterial_1_14 implements BlockMaterial {
private final Block block;
private final IBlockData defaultState;
private final Material material;
private final boolean isTranslucent;
private final CraftBlockData craftBlockData;
private final org.bukkit.Material craftMaterial;
private final int opacity;
public BlockMaterial_1_14(Block block) {
this(block, block.getBlockData());
}
public BlockMaterial_1_14(Block block, IBlockData defaultState) {
this.block = block;
this.defaultState = defaultState;
this.material = defaultState.getMaterial();
this.craftBlockData = CraftBlockData.fromData(defaultState);
this.craftMaterial = craftBlockData.getMaterial();
this.isTranslucent = !(boolean) ReflectionUtil.getField(Block.class, block, "v");
opacity = defaultState.b(BlockAccessAir.INSTANCE, BlockPosition.ZERO);
}
public Block getBlock() {
return block;
}
public IBlockData getState() {
return defaultState;
}
public CraftBlockData getCraftBlockData() {
return craftBlockData;
}
public Material getMaterial() {
return material;
}
@Override
public boolean isAir() {
return defaultState.isAir();
}
@Override
public boolean isFullCube() {
return craftMaterial.isOccluding();
}
@Override
public boolean isOpaque() {
return material.f();
}
@Override
public boolean isPowerSource() {
return defaultState.isPowerSource();
}
@Override
public boolean isLiquid() {
return material.isLiquid();
}
@Override
public boolean isSolid() {
return material.isBuildable();
}
@Override
public float getHardness() {
return block.strength;
}
@Override
public float getResistance() {
return block.getDurability();
}
@Override
public float getSlipperiness() {
return block.m();
}
@Override
public int getLightValue() {
return defaultState.h();
}
@Override
public int getLightOpacity() {
return opacity;
}
@Override
public boolean isFragileWhenPushed() {
return material.getPushReaction() == EnumPistonReaction.DESTROY;
}
@Override
public boolean isUnpushable() {
return material.getPushReaction() == EnumPistonReaction.BLOCK;
}
@Override
public boolean isTicksRandomly() {
return block.isTicking(defaultState);
}
@Override
public boolean isMovementBlocker() {
return material.isSolid();
}
@Override
public boolean isBurnable() {
return material.isBurnable();
}
@Override
public boolean isToolRequired() {
return !material.isAlwaysDestroyable();
}
@Override
public boolean isReplacedDuringPlacement() {
return material.isReplaceable();
}
@Override
public boolean isTranslucent() {
return isTranslucent;
}
@Override
public boolean hasContainer() {
return block instanceof ITileEntity;
}
@Override
public int getMapColor() {
return material.i().rgb;
}
}

Datei anzeigen

@ -1,299 +0,0 @@
package com.boydti.fawe.bukkit.adapter.mc1_14;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.bukkit.adapter.NMSAdapter;
import com.boydti.fawe.bukkit.adapter.DelegateLock;
import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.collection.BitArray;
import com.boydti.fawe.util.MathMan;
import com.boydti.fawe.util.ReflectionUtils;
import com.boydti.fawe.util.TaskManager;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import io.papermc.lib.PaperLib;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import net.jpountz.util.UnsafeUtils;
import net.minecraft.server.v1_14_R1.Block;
import net.minecraft.server.v1_14_R1.Chunk;
import net.minecraft.server.v1_14_R1.ChunkCoordIntPair;
import net.minecraft.server.v1_14_R1.ChunkSection;
import net.minecraft.server.v1_14_R1.DataBits;
import net.minecraft.server.v1_14_R1.DataPalette;
import net.minecraft.server.v1_14_R1.DataPaletteBlock;
import net.minecraft.server.v1_14_R1.DataPaletteLinear;
import net.minecraft.server.v1_14_R1.GameProfileSerializer;
import net.minecraft.server.v1_14_R1.IBlockData;
import net.minecraft.server.v1_14_R1.PacketPlayOutLightUpdate;
import net.minecraft.server.v1_14_R1.PlayerChunk;
import net.minecraft.server.v1_14_R1.PlayerChunkMap;
import net.minecraft.server.v1_14_R1.World;
import org.bukkit.craftbukkit.v1_14_R1.CraftChunk;
import org.bukkit.craftbukkit.v1_14_R1.CraftWorld;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
public final class BukkitAdapter_1_14 extends NMSAdapter {
/*
NMS fields
*/
public final static Field fieldBits;
public final static Field fieldPalette;
public final static Field fieldSize;
public final static Field fieldFluidCount;
public final static Field fieldTickingBlockCount;
public final static Field fieldNonEmptyBlockCount;
private final static Field fieldDirtyCount;
private final static Field fieldDirtyBits;
private final static MethodHandle methodGetVisibleChunk;
private static final int CHUNKSECTION_BASE;
private static final int CHUNKSECTION_SHIFT;
private static final Field fieldLock;
static {
try {
fieldSize = DataPaletteBlock.class.getDeclaredField("i");
fieldSize.setAccessible(true);
fieldBits = DataPaletteBlock.class.getDeclaredField("a");
fieldBits.setAccessible(true);
fieldPalette = DataPaletteBlock.class.getDeclaredField("h");
fieldPalette.setAccessible(true);
fieldFluidCount = ChunkSection.class.getDeclaredField("e");
fieldFluidCount.setAccessible(true);
fieldTickingBlockCount = ChunkSection.class.getDeclaredField("tickingBlockCount");
fieldTickingBlockCount.setAccessible(true);
fieldNonEmptyBlockCount = ChunkSection.class.getDeclaredField("nonEmptyBlockCount");
fieldNonEmptyBlockCount.setAccessible(true);
fieldDirtyCount = PlayerChunk.class.getDeclaredField("dirtyCount");
fieldDirtyCount.setAccessible(true);
fieldDirtyBits = PlayerChunk.class.getDeclaredField("r");
fieldDirtyBits.setAccessible(true);
Method declaredGetVisibleChunk = PlayerChunkMap.class.getDeclaredMethod("getVisibleChunk", long.class);
declaredGetVisibleChunk.setAccessible(true);
methodGetVisibleChunk = MethodHandles.lookup().unreflect(declaredGetVisibleChunk);
{
Field tmp = DataPaletteBlock.class.getDeclaredField("j");
ReflectionUtils.setAccessibleNonFinal(tmp);
fieldLock = tmp;
fieldLock.setAccessible(true);
}
Unsafe unsafe = UnsafeUtils.getUNSAFE();
CHUNKSECTION_BASE = unsafe.arrayBaseOffset(ChunkSection[].class);
int scale = unsafe.arrayIndexScale(ChunkSection[].class);
if ((scale & (scale - 1)) != 0)
throw new Error("data type scale not a power of two");
CHUNKSECTION_SHIFT = 31 - Integer.numberOfLeadingZeros(scale);
} catch (RuntimeException e) {
throw e;
} catch (Throwable rethrow) {
rethrow.printStackTrace();
throw new RuntimeException(rethrow);
}
}
protected static boolean setSectionAtomic(ChunkSection[] sections, ChunkSection expected, ChunkSection value, int layer) {
long offset = ((long) layer << CHUNKSECTION_SHIFT) + CHUNKSECTION_BASE;
if (layer >= 0 && layer < sections.length) {
return UnsafeUtils.getUNSAFE().compareAndSwapObject(sections, offset, expected, value);
}
return false;
}
protected static DelegateLock applyLock(ChunkSection section) {
try {
synchronized (section) {
DataPaletteBlock<IBlockData> blocks = section.getBlocks();
ReentrantLock currentLock = (ReentrantLock) fieldLock.get(blocks);
if (currentLock instanceof DelegateLock) {
return (DelegateLock) currentLock;
}
DelegateLock newLock = new DelegateLock(currentLock);
fieldLock.set(blocks, newLock);
return newLock;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static Chunk ensureLoaded(World nmsWorld, int X, int Z) {
Chunk nmsChunk = nmsWorld.getChunkIfLoaded(X, Z);
if (nmsChunk != null) {
return nmsChunk;
}
if (Fawe.isMainThread()) {
return nmsWorld.getChunkAt(X, Z);
}
if (PaperLib.isPaper()) {
CraftWorld craftWorld = nmsWorld.getWorld();
CompletableFuture<org.bukkit.Chunk> future = craftWorld.getChunkAtAsync(X, Z, true);
try {
CraftChunk chunk = (CraftChunk) future.get();
return chunk.getHandle();
} catch (Throwable e) {
e.printStackTrace();
}
}
// TODO optimize
return TaskManager.IMP.sync(() -> nmsWorld.getChunkAt(X, Z));
}
public static PlayerChunk getPlayerChunk(net.minecraft.server.v1_14_R1.WorldServer nmsWorld, final int cx, final int cz) {
PlayerChunkMap chunkMap = nmsWorld.getChunkProvider().playerChunkMap;
try {
return (PlayerChunk)methodGetVisibleChunk.invoke(chunkMap, ChunkCoordIntPair.pair(cx, cz));
} catch (Throwable thr) {
throw new RuntimeException(thr);
}
}
public static void sendChunk(net.minecraft.server.v1_14_R1.WorldServer nmsWorld, int X, int Z, int mask, boolean lighting) {
PlayerChunk playerChunk = getPlayerChunk(nmsWorld, X, Z);
if (playerChunk == null) {
return;
}
if (playerChunk.hasBeenLoaded()) {
TaskManager.IMP.sync(() -> {
try {
int dirtyBits = fieldDirtyBits.getInt(playerChunk);
if (dirtyBits == 0) {
nmsWorld.getChunkProvider().playerChunkMap.a(playerChunk);
}
if (mask == 0) {
dirtyBits = 65535;
} else {
dirtyBits |= mask;
}
fieldDirtyBits.set(playerChunk, dirtyBits);
fieldDirtyCount.set(playerChunk, 64);
if (lighting) {
ChunkCoordIntPair chunkCoordIntPair = new ChunkCoordIntPair(X, Z);
PacketPlayOutLightUpdate packet = new PacketPlayOutLightUpdate(chunkCoordIntPair, nmsWorld.getChunkProvider().getLightEngine());
playerChunk.players.a(chunkCoordIntPair, false).forEach(p -> {
p.playerConnection.sendPacket(packet);
});
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
});
return;
}
return;
}
/*
NMS conversion
*/
public static ChunkSection newChunkSection(final int layer, final char[] blocks, boolean fastmode) {
return newChunkSection(layer, null, blocks, fastmode);
}
public static ChunkSection newChunkSection(final int layer, final Function<Integer, char[]> get, char[] set, boolean fastmode) {
if (set == null) {
return newChunkSection(layer);
}
final int[] blockToPalette = FaweCache.IMP.BLOCK_TO_PALETTE.get();
final int[] paletteToBlock = FaweCache.IMP.PALETTE_TO_BLOCK.get();
final long[] blockStates = FaweCache.IMP.BLOCK_STATES.get();
final int[] blocksCopy = FaweCache.IMP.SECTION_BLOCKS.get();
try {
int[] num_palette_buffer = new int[1];
Map<BlockVector3, Integer> ticking_blocks = new HashMap<>();
int air;
if (get == null) {
air = createPalette(blockToPalette, paletteToBlock, blocksCopy, num_palette_buffer, set, ticking_blocks, fastmode);
} else {
air = createPalette(layer, blockToPalette, paletteToBlock, blocksCopy, num_palette_buffer, get, set, ticking_blocks, fastmode);
}
int num_palette = num_palette_buffer[0];
// BlockStates
int bitsPerEntry = MathMan.log2nlz(num_palette - 1);
if (Settings.IMP.PROTOCOL_SUPPORT_FIX || num_palette != 1) {
bitsPerEntry = Math.max(bitsPerEntry, 4); // Protocol support breaks <4 bits per entry
} else {
bitsPerEntry = Math.max(bitsPerEntry, 1); // For some reason minecraft needs 4096 bits to store 0 entries
}
final int blockBitArrayEnd = (bitsPerEntry * 4096) >> 6;
if (num_palette == 1) {
for (int i = 0; i < blockBitArrayEnd; i++) blockStates[i] = 0;
} else {
final BitArray bitArray = new BitArray(bitsPerEntry, 4096, blockStates);
bitArray.fromRaw(blocksCopy);
}
ChunkSection section = newChunkSection(layer);
// set palette & data bits
final DataPaletteBlock<IBlockData> dataPaletteBlocks = section.getBlocks();
// private DataPalette<T> h;
// protected DataBits a;
final long[] bits = Arrays.copyOfRange(blockStates, 0, blockBitArrayEnd);
final DataBits nmsBits = new DataBits(bitsPerEntry, 4096, bits);
final DataPalette<IBlockData> palette;
// palette = new DataPaletteHash<>(Block.REGISTRY_ID, bitsPerEntry, dataPaletteBlocks, GameProfileSerializer::d, GameProfileSerializer::a);
palette = new DataPaletteLinear<>(Block.REGISTRY_ID, bitsPerEntry, dataPaletteBlocks, GameProfileSerializer::d);
// set palette
for (int i = 0; i < num_palette; i++) {
final int ordinal = paletteToBlock[i];
blockToPalette[ordinal] = Integer.MAX_VALUE;
final BlockState state = BlockTypesCache.states[ordinal];
final IBlockData ibd = ((BlockMaterial_1_14) state.getMaterial()).getState();
palette.a(ibd);
}
try {
fieldBits.set(dataPaletteBlocks, nmsBits);
fieldPalette.set(dataPaletteBlocks, palette);
fieldSize.set(dataPaletteBlocks, bitsPerEntry);
setCount(ticking_blocks.size(), 4096 - air, section);
ticking_blocks.forEach((pos, ordinal) -> {
section.setType(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ(),
Block.getByCombinedId(ordinal));
});
} catch (final IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
return section;
} catch (final Throwable e){
Arrays.fill(blockToPalette, Integer.MAX_VALUE);
throw e;
}
}
private static ChunkSection newChunkSection(int layer) {
return new ChunkSection(layer << 4);
}
public static void setCount(final int tickingBlockCount, final int nonEmptyBlockCount, final ChunkSection section) throws NoSuchFieldException, IllegalAccessException {
fieldFluidCount.setShort(section, (short) 0); // TODO FIXME
fieldTickingBlockCount.setShort(section, (short) tickingBlockCount);
fieldNonEmptyBlockCount.setShort(section, (short) nonEmptyBlockCount);
}
}

Datei anzeigen

@ -1,832 +0,0 @@
package com.boydti.fawe.bukkit.adapter.mc1_14;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.beta.IChunkSet;
import com.boydti.fawe.beta.implementation.blocks.CharBlocks;
import com.boydti.fawe.beta.implementation.blocks.CharGetBlocks;
import com.boydti.fawe.beta.implementation.lighting.HeightMapType;
import com.boydti.fawe.beta.implementation.queue.QueueHandler;
import com.boydti.fawe.bukkit.adapter.DelegateLock;
import com.boydti.fawe.bukkit.adapter.mc1_14.nbt.LazyCompoundTag_1_14;
import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.collection.AdaptedMap;
import com.boydti.fawe.object.collection.BitArray;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.LongTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.impl.FAWE_Spigot_v1_14_R4;
import com.sk89q.worldedit.internal.Constants;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockTypes;
import net.minecraft.server.v1_14_R1.BiomeBase;
import net.minecraft.server.v1_14_R1.BlockPosition;
import net.minecraft.server.v1_14_R1.Chunk;
import net.minecraft.server.v1_14_R1.ChunkSection;
import net.minecraft.server.v1_14_R1.DataBits;
import net.minecraft.server.v1_14_R1.DataPalette;
import net.minecraft.server.v1_14_R1.DataPaletteBlock;
import net.minecraft.server.v1_14_R1.DataPaletteHash;
import net.minecraft.server.v1_14_R1.DataPaletteLinear;
import net.minecraft.server.v1_14_R1.Entity;
import net.minecraft.server.v1_14_R1.EntityTypes;
import net.minecraft.server.v1_14_R1.EnumSkyBlock;
import net.minecraft.server.v1_14_R1.HeightMap;
import net.minecraft.server.v1_14_R1.IBlockData;
import net.minecraft.server.v1_14_R1.LightEngine;
import net.minecraft.server.v1_14_R1.NBTTagCompound;
import net.minecraft.server.v1_14_R1.NBTTagInt;
import net.minecraft.server.v1_14_R1.NibbleArray;
import net.minecraft.server.v1_14_R1.SectionPosition;
import net.minecraft.server.v1_14_R1.TileEntity;
import net.minecraft.server.v1_14_R1.WorldServer;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.craftbukkit.v1_14_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_14_R1.block.CraftBlock;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.slf4j.LoggerFactory.getLogger;
@SuppressWarnings("checkstyle:TypeName")
public class BukkitGetBlocks_1_14 extends CharGetBlocks {
private static final Logger log = LoggerFactory.getLogger(BukkitGetBlocks_1_14.class);
public ChunkSection[] sections;
public Chunk nmsChunk;
public WorldServer world;
public int chunkX;
public int chunkZ;
public NibbleArray[] blockLight = new NibbleArray[16];
public NibbleArray[] skyLight = new NibbleArray[16];
public BukkitGetBlocks_1_14(World world, int chunkX, int chunkZ) {
this(((CraftWorld) world).getHandle(), chunkX, chunkZ);
}
public BukkitGetBlocks_1_14(WorldServer world, int chunkX, int chunkZ) {
this.world = world;
this.chunkX = chunkX;
this.chunkZ = chunkZ;
}
public int getX() {
return chunkX;
}
public int getZ() {
return chunkZ;
}
@Override
public BiomeType getBiomeType(int x, int y, int z) {
BiomeBase base = getChunk().getBiomeIndex()[(z << 4) + x];
return BukkitAdapter.adapt(CraftBlock.biomeBaseToBiome(base));
}
@Override
public CompoundTag getTile(int x, int y, int z) {
TileEntity tileEntity = getChunk().getTileEntity(
new BlockPosition((x & 15) + (chunkX << 4), y, (z & 15) + (chunkZ << 4)));
if (tileEntity == null) {
return null;
}
return new LazyCompoundTag_1_14(
Suppliers.memoize(() -> tileEntity.save(new NBTTagCompound())));
}
private static final Function<BlockPosition, BlockVector3> posNms2We =
v -> BlockVector3.at(v.getX(), v.getY(), v.getZ());
private static final Function<TileEntity, CompoundTag> nmsTile2We =
tileEntity -> new LazyCompoundTag_1_14(
Suppliers.memoize(() -> tileEntity.save(new NBTTagCompound())));
@Override
public Map<BlockVector3, CompoundTag> getTiles() {
Map<BlockPosition, TileEntity> nmsTiles = getChunk().getTileEntities();
if (nmsTiles.isEmpty()) {
return Collections.emptyMap();
}
return AdaptedMap.immutable(nmsTiles, posNms2We, nmsTile2We);
}
@Override
public int getSkyLight(int x, int y, int z) {
int layer = y >> 4;
if (skyLight[layer] == null) {
//getDataLayerData
SectionPosition sectionPosition = SectionPosition.a(nmsChunk.getPos(), layer);
NibbleArray nibbleArray =
world.getChunkProvider().getLightEngine().a(EnumSkyBlock.SKY).a(sectionPosition);
// If the server hasn't generated the section's NibbleArray yet, it will be null
if (nibbleArray == null) {
byte[] a = new byte[2048];
// Safe enough to assume if it's not created, it's under the sky. Unlikely to be created before lighting is fixed anyway.
Arrays.fill(a, (byte) 15);
nibbleArray = new NibbleArray(a);
((LightEngine) world.getChunkProvider().getLightEngine())
.a(EnumSkyBlock.SKY, sectionPosition, nibbleArray);
}
skyLight[layer] = nibbleArray;
}
long l = BlockPosition.a(x, y, z);
return skyLight[layer]
.a(SectionPosition.b(BlockPosition.b(l)), SectionPosition.b(BlockPosition.c(l)),
SectionPosition.b(BlockPosition.d(l)));
}
@Override
public int getEmmittedLight(int x, int y, int z) {
int layer = y >> 4;
if (blockLight[layer] == null) {
//getDataLayerData
SectionPosition sectionPosition = SectionPosition.a(nmsChunk.getPos(), layer);
NibbleArray nibbleArray =
world.getChunkProvider().getLightEngine().a(EnumSkyBlock.BLOCK).a(sectionPosition);
// If the server hasn't generated the section's NibbleArray yet, it will be null
if (nibbleArray == null) {
byte[] a = new byte[2048];
// Safe enough to assume if it's not created, it's under the sky. Unlikely to be created before lighting is fixed anyway.
Arrays.fill(a, (byte) 15);
nibbleArray = new NibbleArray(a);
((LightEngine) world.getChunkProvider().getLightEngine())
.a(EnumSkyBlock.BLOCK, sectionPosition, nibbleArray);
}
blockLight[layer] = nibbleArray;
}
long l = BlockPosition.a(x, y, z);
return blockLight[layer]
.a(SectionPosition.b(BlockPosition.b(l)), SectionPosition.b(BlockPosition.c(l)),
SectionPosition.b(BlockPosition.d(l)));
}
@Override public int[] getHeightMap(HeightMapType type) {
long[] longArray = getChunk().heightMap.get(HeightMap.Type.valueOf(type.name())).a();
BitArray bitArray = new BitArray(9, 256, longArray);
return bitArray.toRaw(new int[256]);
}
@Override
public CompoundTag getEntity(UUID uuid) {
Entity entity = world.getEntity(uuid);
if (entity != null) {
org.bukkit.entity.Entity bukkitEnt = entity.getBukkitEntity();
return BukkitAdapter.adapt(bukkitEnt).getState().getNbtData();
}
for (List<Entity> entry : getChunk().getEntitySlices()) {
if (entry != null) {
for (Entity ent : entry) {
if (uuid.equals(ent.getUniqueID())) {
org.bukkit.entity.Entity bukkitEnt = ent.getBukkitEntity();
return BukkitAdapter.adapt(bukkitEnt).getState().getNbtData();
}
}
}
}
return null;
}
@Override
public Set<CompoundTag> getEntities() {
List<Entity>[] slices = getChunk().getEntitySlices();
int size = 0;
for (List<Entity> slice : slices) {
if (slice != null) {
size += slice.size();
}
}
if (slices.length == 0) {
return Collections.emptySet();
}
int finalSize = size;
return new AbstractSet<CompoundTag>() {
@Override
public int size() {
return finalSize;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean contains(Object get) {
if (!(get instanceof CompoundTag)) {
return false;
}
CompoundTag getTag = (CompoundTag) get;
Map<String, Tag> value = getTag.getValue();
CompoundTag getParts = (CompoundTag) value.get("UUID");
UUID getUUID = new UUID(getParts.getLong("Most"), getParts.getLong("Least"));
for (List<Entity> slice : slices) {
if (slice != null) {
for (Entity entity : slice) {
UUID uuid = entity.getUniqueID();
if (uuid.equals(getUUID)) {
return true;
}
}
}
}
return false;
}
@NotNull
@Override
public Iterator<CompoundTag> iterator() {
Iterable<CompoundTag> result =
StreamSupport.stream(Iterables.concat(slices).spliterator(), false)
.map(input -> {
BukkitImplAdapter adapter =
WorldEditPlugin.getInstance().getBukkitImplAdapter();
NBTTagCompound tag = new NBTTagCompound();
return (CompoundTag) adapter.toNative(input.save(tag));
}).collect(Collectors.toList());
return result.iterator();
}
};
}
private void updateGet(BukkitGetBlocks_1_14 get, Chunk nmsChunk, ChunkSection[] sections,
ChunkSection section, char[] arr, int layer) {
synchronized (get) {
if (this.nmsChunk != nmsChunk) {
this.nmsChunk = nmsChunk;
this.sections = sections.clone();
this.reset();
}
if (this.sections == null) {
this.sections = sections.clone();
}
if (this.sections[layer] != section) {
this.sections[layer] = section;
}
this.blocks[layer] = arr;
}
}
private void removeEntity(Entity entity) {
entity.die();
}
public Chunk ensureLoaded(net.minecraft.server.v1_14_R1.World nmsWorld, int chunkX,
int chunkZ) {
return BukkitAdapter_1_14.ensureLoaded(nmsWorld, chunkX, chunkZ);
}
@Override
public <T extends Future<T>> T call(IChunkSet set, Runnable finalizer) {
try {
WorldServer nmsWorld = world;
Chunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ);
boolean fastmode = set.isFastMode() && Settings.IMP.QUEUE.NO_TICK_FASTMODE;
// Remove existing tiles
{
Map<BlockPosition, TileEntity> tiles = new HashMap<>(nmsChunk.getTileEntities());
if (!tiles.isEmpty()) {
for (Map.Entry<BlockPosition, TileEntity> entry : tiles.entrySet()) {
final BlockPosition pos = entry.getKey();
final int lx = pos.getX() & 15;
final int ly = pos.getY();
final int lz = pos.getZ() & 15;
final int layer = ly >> 4;
if (!set.hasSection(layer)) {
continue;
}
if (set.getBlock(lx, ly, lz).getOrdinal() != 0) {
TileEntity tile = entry.getValue();
nmsChunk.removeTileEntity(tile.getPosition());
}
}
}
}
int bitMask = 0;
synchronized (nmsChunk) {
ChunkSection[] sections = nmsChunk.getSections();
for (int layer = 0; layer < 16; layer++) {
if (!set.hasSection(layer)) {
continue;
}
bitMask |= 1 << layer;
char[] setArr = set.load(layer);
ChunkSection newSection;
ChunkSection existingSection = sections[layer];
if (existingSection == null) {
newSection = BukkitAdapter_1_14.newChunkSection(layer, setArr, fastmode);
if (BukkitAdapter_1_14
.setSectionAtomic(sections, null, newSection, layer)) {
updateGet(this, nmsChunk, sections, newSection, setArr, layer);
continue;
} else {
existingSection = sections[layer];
if (existingSection == null) {
log.error(
"Skipping invalid null section. chunk:" + chunkX + "," + chunkZ
+ " layer: " + layer);
continue;
}
}
}
//ensure that the server doesn't try to tick the chunksection while we're editing it.
BukkitAdapter_1_14.fieldTickingBlockCount.set(existingSection, (short) 0);
DelegateLock lock = BukkitAdapter_1_14.applyLock(existingSection);
synchronized (this) {
synchronized (lock) {
lock.untilFree();
if (this.nmsChunk != nmsChunk) {
this.nmsChunk = nmsChunk;
this.sections = null;
this.reset();
} else if (existingSection != getSections()[layer]) {
this.sections[layer] = existingSection;
this.reset();
} else if (!Arrays.equals(update(layer, new char[4096]), load(layer))) {
this.reset(layer);
} else if (lock.isModified()) {
this.reset(layer);
}
newSection = BukkitAdapter_1_14
.newChunkSection(layer, this::load, setArr, fastmode);
if (!BukkitAdapter_1_14
.setSectionAtomic(sections, existingSection, newSection, layer)) {
log.error("Failed to set chunk section:" + chunkX + "," + chunkZ
+ " layer: " + layer);
continue;
} else {
updateGet(this, nmsChunk, sections, newSection, setArr, layer);
}
}
}
}
// Biomes
BiomeType[] biomes = set.getBiomes();
if (biomes != null) {
// set biomes
final BiomeBase[] currentBiomes = nmsChunk.getBiomeIndex();
for (int i = 0; i < biomes.length; i++) {
final BiomeType biome = biomes[i];
if (biome != null) {
final Biome craftBiome = BukkitAdapter.adapt(biome);
currentBiomes[i] = CraftBlock.biomeToBiomeBase(craftBiome);
}
}
}
Map<HeightMapType, int[]> heightMaps = set.getHeightMaps();
for (Map.Entry<HeightMapType, int[]> entry : heightMaps.entrySet()) {
BitArray bitArray = new BitArray(9, 256);
bitArray.fromRaw(entry.getValue());
nmsChunk.heightMap.get(HeightMap.Type.valueOf(entry.getKey().name())).a(bitArray.getData());
}
boolean lightUpdate = false;
// Lighting
char[][] light = set.getLight();
if (light != null) {
lightUpdate = true;
try {
fillLightNibble(light, EnumSkyBlock.BLOCK);
} catch (Throwable e) {
e.printStackTrace();
}
}
char[][] skyLight = set.getSkyLight();
if (skyLight != null) {
lightUpdate = true;
try {
fillLightNibble(skyLight, EnumSkyBlock.SKY);
} catch (Throwable e) {
e.printStackTrace();
}
}
Runnable[] syncTasks = null;
int bx = chunkX << 4;
int bz = chunkZ << 4;
Set<UUID> entityRemoves = set.getEntityRemoves();
if (entityRemoves != null && !entityRemoves.isEmpty()) {
if (syncTasks == null) {
syncTasks = new Runnable[3];
}
syncTasks[2] = () -> {
final List<Entity>[] entities = nmsChunk.getEntitySlices();
for (final Collection<Entity> ents : entities) {
if (!ents.isEmpty()) {
final Iterator<Entity> iter = ents.iterator();
while (iter.hasNext()) {
final Entity entity = iter.next();
if (entityRemoves.contains(entity.getUniqueID())) {
iter.remove();
removeEntity(entity);
}
}
}
}
};
}
Set<CompoundTag> entities = set.getEntities();
if (entities != null && !entities.isEmpty()) {
if (syncTasks == null) {
syncTasks = new Runnable[2];
}
syncTasks[1] = () -> {
for (final CompoundTag nativeTag : entities) {
final Map<String, Tag> entityTagMap = nativeTag.getValue();
final StringTag idTag = (StringTag) entityTagMap.get("Id");
final ListTag posTag = (ListTag) entityTagMap.get("Pos");
final ListTag rotTag = (ListTag) entityTagMap.get("Rotation");
if (idTag == null || posTag == null || rotTag == null) {
getLogger(BukkitGetBlocks_1_14.class)
.debug("Unknown entity tag: " + nativeTag);
continue;
}
final double x = posTag.getDouble(0);
final double y = posTag.getDouble(1);
final double z = posTag.getDouble(2);
final float yaw = rotTag.getFloat(0);
final float pitch = rotTag.getFloat(1);
final String id = idTag.getValue();
EntityTypes<?> type = EntityTypes.a(id).orElse(null);
if (type != null) {
Entity entity = type.a(nmsWorld);
if (entity != null) {
BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter();
final NBTTagCompound tag = (NBTTagCompound) adapter.fromNative(nativeTag);
for (final String name : Constants.NO_COPY_ENTITY_NBT_FIELDS) {
tag.remove(name);
}
entity.f(tag);
entity.setLocation(x, y, z, yaw, pitch);
nmsWorld
.addEntity(entity, CreatureSpawnEvent.SpawnReason.CUSTOM);
}
}
}
};
}
// set tiles
Map<BlockVector3, CompoundTag> tiles = set.getTiles();
if (tiles != null && !tiles.isEmpty()) {
if (syncTasks == null) {
syncTasks = new Runnable[1];
}
syncTasks[0] = () -> {
for (final Map.Entry<BlockVector3, CompoundTag> entry : tiles.entrySet()) {
final CompoundTag nativeTag = entry.getValue();
final BlockVector3 blockHash = entry.getKey();
final int x = blockHash.getX() + bx;
final int y = blockHash.getY();
final int z = blockHash.getZ() + bz;
final BlockPosition pos = new BlockPosition(x, y, z);
synchronized (nmsWorld) {
TileEntity tileEntity = nmsWorld.getTileEntity(pos);
if (tileEntity == null || tileEntity.isRemoved()) {
nmsWorld.removeTileEntity(pos);
tileEntity = nmsWorld.getTileEntity(pos);
}
if (tileEntity != null) {
BukkitImplAdapter adapter =
WorldEditPlugin.getInstance().getBukkitImplAdapter();
final NBTTagCompound tag =
(NBTTagCompound) adapter.fromNative(nativeTag);
tag.set("x", new NBTTagInt(x));
tag.set("y", new NBTTagInt(y));
tag.set("z", new NBTTagInt(z));
tileEntity.load(tag);
}
}
}
};
}
Runnable callback;
if (bitMask == 0 && biomes == null && !lightUpdate) {
callback = null;
} else {
int finalMask = bitMask != 0 ? bitMask : lightUpdate ? set.getBitMask() : 0;
boolean finalLightUpdate = lightUpdate;
callback = () -> {
// Set Modified
nmsChunk.d(true); // Set Modified
nmsChunk.mustNotSave = false;
nmsChunk.markDirty();
// send to player
BukkitAdapter_1_14
.sendChunk(nmsWorld, chunkX, chunkZ, finalMask, finalLightUpdate);
if (finalizer != null) {
finalizer.run();
}
};
}
if (syncTasks != null) {
QueueHandler queueHandler = Fawe.get().getQueueHandler();
Runnable[] finalSyncTasks = syncTasks;
// Chain the sync tasks and the callback
Callable<Future> chain = () -> {
try {
// Run the sync tasks
for (Runnable task : finalSyncTasks) {
if (task != null) {
task.run();
}
}
if (callback == null) {
if (finalizer != null) {
finalizer.run();
}
return null;
} else {
return queueHandler.async(callback, null);
}
} catch (Throwable e) {
e.printStackTrace();
throw e;
}
};
return (T) (Future) queueHandler.sync(chain);
} else {
if (callback == null) {
if (finalizer != null) {
finalizer.run();
}
} else {
callback.run();
}
}
}
return null;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
@Override
public synchronized char[] update(int layer, char[] data) {
ChunkSection section = getSections()[layer];
// Section is null, return empty array
if (section == null) {
data = new char[4096];
Arrays.fill(data, (char) 1);
return data;
}
if (data == null || data == FaweCache.IMP.EMPTY_CHAR_4096) {
data = new char[4096];
Arrays.fill(data, (char) 1);
}
DelegateLock lock = BukkitAdapter_1_14.applyLock(section);
synchronized (lock) {
lock.untilFree();
lock.setModified(false);
// Efficiently convert ChunkSection to raw data
try {
FAWE_Spigot_v1_14_R4 adapter =
((FAWE_Spigot_v1_14_R4) WorldEditPlugin.getInstance().getBukkitImplAdapter());
final DataPaletteBlock<IBlockData> blocks = section.getBlocks();
final DataBits bits = (DataBits) BukkitAdapter_1_14.fieldBits.get(blocks);
final DataPalette<IBlockData> palette =
(DataPalette<IBlockData>) BukkitAdapter_1_14.fieldPalette.get(blocks);
final int bitsPerEntry = bits.c();
final long[] blockStates = bits.a();
new BitArray(bitsPerEntry, 4096, blockStates).toRaw(data);
int num_palette;
if (palette instanceof DataPaletteLinear) {
num_palette = ((DataPaletteLinear<IBlockData>) palette).b();
} else if (palette instanceof DataPaletteHash) {
num_palette = ((DataPaletteHash<IBlockData>) palette).b();
} else {
num_palette = 0;
int[] paletteToBlockInts = FaweCache.IMP.PALETTE_TO_BLOCK.get();
char[] paletteToBlockChars = FaweCache.IMP.PALETTE_TO_BLOCK_CHAR.get();
try {
for (int i = 0; i < 4096; i++) {
char paletteVal = data[i];
char ordinal = paletteToBlockChars[paletteVal];
if (ordinal == Character.MAX_VALUE) {
paletteToBlockInts[num_palette++] = paletteVal;
IBlockData ibd = palette.a(data[i]);
if (ibd == null) {
ordinal = BlockTypes.AIR.getDefaultState().getOrdinalChar();
} else {
ordinal = adapter.adaptToChar(ibd);
}
// Don't read "empty".
if (ordinal == 0) {
ordinal = 1;
}
paletteToBlockChars[paletteVal] = ordinal;
}
data[i] = ordinal;
}
} finally {
for (int i = 0; i < num_palette; i++) {
int paletteVal = paletteToBlockInts[i];
paletteToBlockChars[paletteVal] = Character.MAX_VALUE;
}
}
return data;
}
char[] paletteToOrdinal = FaweCache.IMP.PALETTE_TO_BLOCK_CHAR.get();
try {
if (num_palette != 1) {
for (int i = 0; i < num_palette; i++) {
char ordinal = ordinal(palette.a(i), adapter);
paletteToOrdinal[i] = ordinal;
}
for (int i = 0; i < 4096; i++) {
char paletteVal = data[i];
char val = paletteToOrdinal[paletteVal];
if (val == Character.MAX_VALUE) {
val = ordinal(palette.a(i), adapter);
paletteToOrdinal[i] = val;
}
// Don't read "empty".
if (val == 0) {
val = 1;
}
data[i] = val;
}
} else {
char ordinal = ordinal(palette.a(0), adapter);
// Don't read "empty".
if (ordinal == 0) {
ordinal = 1;
}
Arrays.fill(data, ordinal);
}
} finally {
for (int i = 0; i < num_palette; i++) {
paletteToOrdinal[i] = Character.MAX_VALUE;
}
}
return data;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
private final char ordinal(IBlockData ibd, FAWE_Spigot_v1_14_R4 adapter) {
if (ibd == null) {
return BlockTypes.AIR.getDefaultState().getOrdinalChar();
} else {
return adapter.adaptToChar(ibd);
}
}
public ChunkSection[] getSections() {
ChunkSection[] tmp = sections;
if (tmp == null) {
synchronized (this) {
tmp = sections;
if (tmp == null) {
Chunk chunk = getChunk();
sections = tmp = chunk.getSections().clone();
}
}
}
return tmp;
}
public Chunk getChunk() {
Chunk tmp = nmsChunk;
if (tmp == null) {
synchronized (this) {
tmp = nmsChunk;
if (tmp == null) {
nmsChunk = tmp = ensureLoaded(this.world, chunkX, chunkZ);
}
}
}
return tmp;
}
private void fillLightNibble(char[][] light, EnumSkyBlock skyBlock) {
for (int Y = 0; Y < 16; Y++) {
if (light[Y] == null) {
continue;
}
SectionPosition sectionPosition = SectionPosition.a(nmsChunk.getPos(), Y);
NibbleArray nibble =
world.getChunkProvider().getLightEngine().a(skyBlock).a(sectionPosition);
if (nibble == null) {
byte[] a = new byte[2048];
Arrays.fill(a, skyBlock == EnumSkyBlock.SKY ? (byte) 15 : (byte) 0);
nibble = new NibbleArray(a);
((LightEngine) world.getChunkProvider().getLightEngine())
.a(skyBlock, sectionPosition, nibble);
}
synchronized (nibble) {
for (int i = 0; i < 4096; i++) {
if (light[Y][i] < 16) {
nibble.a(i, light[Y][i]);
}
}
}
}
}
@Override
public boolean hasSection(int layer) {
return getSections()[layer] != null;
}
@Override
public boolean trim(boolean aggressive) {
if (aggressive) {
sections = null;
nmsChunk = null;
return super.trim(true);
} else {
for (int i = 0; i < 16; i++) {
if (!hasSection(i) || super.sections[i] == CharBlocks.EMPTY) {
continue;
}
ChunkSection existing = getSections()[i];
try {
final DataPaletteBlock<IBlockData> blocksExisting = existing.getBlocks();
final DataPalette<IBlockData> palette =
(DataPalette<IBlockData>) BukkitAdapter_1_14.fieldPalette
.get(blocksExisting);
int paletteSize;
if (palette instanceof DataPaletteLinear) {
paletteSize = ((DataPaletteLinear<IBlockData>) palette).b();
} else if (palette instanceof DataPaletteHash) {
paletteSize = ((DataPaletteHash<IBlockData>) palette).b();
} else {
super.trim(false, i);
continue;
}
if (paletteSize == 1) {
//If the cached palette size is 1 then no blocks can have been changed i.e. do not need to update these chunks.
continue;
}
super.trim(false, i);
} catch (IllegalAccessException ignored) {
super.trim(false, i);
}
}
return true;
}
}
}

Datei anzeigen

@ -1,176 +0,0 @@
package com.boydti.fawe.bukkit.adapter.mc1_14;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.adapter.impl.FAWE_Spigot_v1_14_R4;
import com.sk89q.worldedit.internal.block.BlockStateIdAccess;
import com.sk89q.worldedit.internal.wna.WorldNativeAccess;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import net.minecraft.server.v1_14_R1.Block;
import net.minecraft.server.v1_14_R1.BlockPosition;
import net.minecraft.server.v1_14_R1.Chunk;
import net.minecraft.server.v1_14_R1.ChunkProviderServer;
import net.minecraft.server.v1_14_R1.EnumDirection;
import net.minecraft.server.v1_14_R1.IBlockData;
import net.minecraft.server.v1_14_R1.NBTBase;
import net.minecraft.server.v1_14_R1.NBTTagCompound;
import net.minecraft.server.v1_14_R1.PlayerChunk;
import net.minecraft.server.v1_14_R1.TileEntity;
import net.minecraft.server.v1_14_R1.World;
import org.bukkit.craftbukkit.v1_14_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_14_R1.block.data.CraftBlockData;
import org.bukkit.event.block.BlockPhysicsEvent;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.Objects;
public class FAWEWorldNativeAccess_1_14 implements WorldNativeAccess<Chunk, IBlockData, BlockPosition> {
private static final int UPDATE = 1, NOTIFY = 2;
private final FAWE_Spigot_v1_14_R4 adapter;
private final WeakReference<World> world;
private SideEffectSet sideEffectSet;
public FAWEWorldNativeAccess_1_14(FAWE_Spigot_v1_14_R4 adapter, WeakReference<World> world) {
this.adapter = adapter;
this.world = world;
}
private World getWorld() {
return Objects.requireNonNull(world.get(), "The reference to the world was lost");
}
@Override
public void setCurrentSideEffectSet(SideEffectSet sideEffectSet) {
this.sideEffectSet = sideEffectSet;
}
@Override
public Chunk getChunk(int x, int z) {
return getWorld().getChunkAt(x, z);
}
@Override
public IBlockData toNative(com.sk89q.worldedit.world.block.BlockState state) {
int stateId = BlockStateIdAccess.getBlockStateId(state);
return BlockStateIdAccess.isValidInternalId(stateId)
? Block.getByCombinedId(stateId)
: ((CraftBlockData) BukkitAdapter.adapt(state)).getState();
}
@Override
public IBlockData getBlockState(Chunk chunk, BlockPosition position) {
return chunk.getType(position);
}
@Nullable
@Override
public IBlockData setBlockState(Chunk chunk, BlockPosition position, IBlockData state) {
return chunk.setType(position, state, false);
}
@Override
public IBlockData getValidBlockForPosition(IBlockData block, BlockPosition position) {
return Block.b(block, getWorld(), position);
}
@Override
public BlockPosition getPosition(int x, int y, int z) {
return new BlockPosition(x, y, z);
}
@Override
public void updateLightingForBlock(BlockPosition position) {
getWorld().getChunkProvider().getLightEngine().a(position);
}
@Override
public boolean updateTileEntity(BlockPosition position, CompoundTag tag) {
// We will assume that the tile entity was created for us,
// though we do not do this on the other versions
TileEntity tileEntity = getWorld().getTileEntity(position);
if (tileEntity == null) {
return false;
}
NBTBase nativeTag = adapter.fromNative(tag);
tileEntity.load((NBTTagCompound) nativeTag);
return true;
}
@Override
public void notifyBlockUpdate(BlockPosition position, IBlockData oldState, IBlockData newState) {
getWorld().notify(position, oldState, newState, UPDATE | NOTIFY);
}
@Override
public boolean isChunkTicking(Chunk chunk) {
return chunk.getState().isAtLeast(PlayerChunk.State.TICKING);
}
@Override
public void markBlockChanged(BlockPosition position) {
((ChunkProviderServer) getWorld().getChunkProvider()).flagDirty(position);
}
private static final EnumDirection[] NEIGHBOUR_ORDER = {
EnumDirection.WEST, EnumDirection.EAST,
EnumDirection.DOWN, EnumDirection.UP,
EnumDirection.NORTH, EnumDirection.SOUTH
};
@Override
public void notifyNeighbors(BlockPosition pos, IBlockData oldState, IBlockData newState) {
World world = getWorld();
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
world.update(pos, oldState.getBlock());
} else {
// When we don't want events, manually run the physics without them.
// Un-nest neighbour updating
for (EnumDirection direction : NEIGHBOUR_ORDER) {
BlockPosition shifted = pos.shift(direction);
world.getType(shifted).doPhysics(world, shifted, oldState.getBlock(), pos, false);
}
}
if (newState.isComplexRedstone()) {
world.updateAdjacentComparators(pos, newState.getBlock());
}
}
@Override
public void updateNeighbors(BlockPosition pos, IBlockData oldState, IBlockData newState, int recursionLimit) {
World world = getWorld();
// a == updateNeighbors
// b == updateDiagonalNeighbors
oldState.b(world, pos, NOTIFY);
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
CraftWorld craftWorld = world.getWorld();
if (craftWorld != null) {
BlockPhysicsEvent event = new BlockPhysicsEvent(
craftWorld.getBlockAt(pos.getX(), pos.getY(), pos.getZ()),
CraftBlockData.fromData(newState));
world.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
}
}
newState.a(world, pos, NOTIFY);
newState.b(world, pos, NOTIFY);
}
@Override
public void onBlockStateChange(BlockPosition pos, IBlockData oldState, IBlockData newState) {
getWorld().a(pos, oldState, newState);
}
@Override
public <B extends BlockStateHolder<B>> boolean setBlock(BlockVector3 position, B block, SideEffectSet sideEffects) throws WorldEditException {
return this.adapter.setBlock(this.getChunk(position.getBlockX() >> 4, position.getBlockZ() >> 4).bukkitChunk, position.getBlockX(), position.getBlockY(), position.getBlockZ(), block, sideEffectSet.shouldApply(SideEffect.LIGHTING));
}
}

Datei anzeigen

@ -1,28 +0,0 @@
package com.boydti.fawe.bukkit.adapter.mc1_14;
import com.boydti.fawe.bukkit.adapter.MapChunkUtil;
import net.minecraft.server.v1_14_R1.PacketPlayOutMapChunk;
public class MapChunkUtil_1_14 extends MapChunkUtil<PacketPlayOutMapChunk> {
public MapChunkUtil_1_14() throws NoSuchFieldException {
fieldX = PacketPlayOutMapChunk.class.getDeclaredField("a");
fieldZ = PacketPlayOutMapChunk.class.getDeclaredField("b");
fieldBitMask = PacketPlayOutMapChunk.class.getDeclaredField("c");
fieldHeightMap = PacketPlayOutMapChunk.class.getDeclaredField("d");
fieldChunkData = PacketPlayOutMapChunk.class.getDeclaredField("e");
fieldBlockEntities = PacketPlayOutMapChunk.class.getDeclaredField("f");
fieldFull = PacketPlayOutMapChunk.class.getDeclaredField("g");
fieldX.setAccessible(true);
fieldZ.setAccessible(true);
fieldBitMask.setAccessible(true);
fieldHeightMap.setAccessible(true);
fieldChunkData.setAccessible(true);
fieldBlockEntities.setAccessible(true);
fieldFull.setAccessible(true);
}
@Override
public PacketPlayOutMapChunk createPacket() {
return new PacketPlayOutMapChunk();
}
}

Datei anzeigen

@ -1,152 +0,0 @@
package com.boydti.fawe.bukkit.adapter.mc1_14.nbt;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import net.minecraft.server.v1_14_R1.NBTBase;
import net.minecraft.server.v1_14_R1.NBTNumber;
import net.minecraft.server.v1_14_R1.NBTTagCompound;
import net.minecraft.server.v1_14_R1.NBTTagList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
public class LazyCompoundTag_1_14 extends CompoundTag {
private final Supplier<NBTTagCompound> nmsTag;
public LazyCompoundTag_1_14(Supplier<NBTTagCompound> tag) {
super(null);
this.nmsTag = tag;
}
public LazyCompoundTag_1_14(NBTTagCompound tag) {
this(() -> tag);
}
public NBTTagCompound get() {
return nmsTag.get();
}
@Override
public Map<String, Tag> getValue() {
Map<String, Tag> value = super.getValue();
if (value == null) {
Tag tag = WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(nmsTag.get());
setValue(((CompoundTag) tag).getValue());
}
return super.getValue();
}
public boolean containsKey(String key) {
return nmsTag.get().hasKey(key);
}
public byte[] getByteArray(String key) {
return nmsTag.get().getByteArray(key);
}
public byte getByte(String key) {
return nmsTag.get().getByte(key);
}
public double getDouble(String key) {
return nmsTag.get().getDouble(key);
}
public double asDouble(String key) {
NBTBase value = nmsTag.get().get(key);
if (value instanceof NBTNumber) {
return ((NBTNumber) value).asDouble();
}
return 0;
}
public float getFloat(String key) {
return nmsTag.get().getFloat(key);
}
public int[] getIntArray(String key) {
return nmsTag.get().getIntArray(key);
}
public int getInt(String key) {
return nmsTag.get().getInt(key);
}
public int asInt(String key) {
NBTBase value = nmsTag.get().get(key);
if (value instanceof NBTNumber) {
return ((NBTNumber) value).asInt();
}
return 0;
}
public List<Tag> getList(String key) {
NBTBase tag = nmsTag.get().get(key);
if (tag instanceof NBTTagList) {
ArrayList<Tag> list = new ArrayList<>();
NBTTagList nbtList = (NBTTagList) tag;
for (NBTBase elem : nbtList) {
if (elem instanceof NBTTagCompound) {
list.add(new LazyCompoundTag_1_14((NBTTagCompound) elem));
} else {
list.add(WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(elem));
}
}
return list;
}
return Collections.emptyList();
}
public ListTag getListTag(String key) {
NBTBase tag = nmsTag.get().get(key);
if (tag instanceof NBTTagList) {
return (ListTag) WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(tag);
}
return new ListTag(StringTag.class, Collections.<Tag>emptyList());
}
@SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(String key, Class<T> listType) {
ListTag listTag = getListTag(key);
if (listTag.getType().equals(listType)) {
return (List<T>) listTag.getValue();
} else {
return Collections.emptyList();
}
}
public long[] getLongArray(String key) {
return nmsTag.get().getLongArray(key);
}
public long getLong(String key) {
return nmsTag.get().getLong(key);
}
public long asLong(String key) {
NBTBase value = nmsTag.get().get(key);
if (value instanceof NBTNumber) {
return ((NBTNumber) value).asLong();
}
return 0;
}
public short getShort(String key) {
return nmsTag.get().getShort(key);
}
public String getString(String key) {
return nmsTag.get().getString(key);
}
@Override
public String toString() {
return nmsTag.get().toString();
}
}

Datei anzeigen

@ -28,7 +28,7 @@ import org.bukkit.plugin.RegisteredServiceProvider;
public class VaultResolver implements PermissionsResolver { public class VaultResolver implements PermissionsResolver {
private static Permission perms = null; public static Permission perms = null;
public static PermissionsResolver factory(Server server, YAMLProcessor config) { public static PermissionsResolver factory(Server server, YAMLProcessor config) {
if (server.getPluginManager().getPlugin("Vault") == null) { if (server.getPluginManager().getPlugin("Vault") == null) {

Datei anzeigen

@ -19,13 +19,12 @@
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.bukkit.FaweBukkit;
import com.boydti.fawe.config.Caption; import com.boydti.fawe.config.Caption;
import com.boydti.fawe.config.Settings; import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.RunnableVal; import com.boydti.fawe.object.RunnableVal;
import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.TaskManager;
import com.sk89q.util.StringUtil; import com.sk89q.util.StringUtil;
import com.sk89q.wepif.VaultResolver;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.blocks.BaseItemStack;
@ -240,13 +239,15 @@ public class BukkitPlayer extends AbstractPlayerActor {
* Permissions are used to managing WorldEdit region restrictions * Permissions are used to managing WorldEdit region restrictions
* - The `/wea` command will give/remove the required bypass permission * - The `/wea` command will give/remove the required bypass permission
*/ */
if (Fawe.<FaweBukkit>imp().getVault() == null || Fawe.<FaweBukkit> imp().getVault().permission == null) { if (VaultResolver.perms != null) {
player.addAttachment(plugin).setPermission(permission, value); if (value) {
} else if (value) { if (!VaultResolver.perms.playerAdd(player, permission)) {
if (!Fawe.<FaweBukkit> imp().getVault().permission.playerAdd(player, permission)) { player.addAttachment(plugin).setPermission(permission, value);
}
} else if (!VaultResolver.perms.playerRemove(player, permission)) {
player.addAttachment(plugin).setPermission(permission, value); player.addAttachment(plugin).setPermission(permission, value);
} }
} else if (!Fawe.<FaweBukkit>imp().getVault().permission.playerRemove(player, permission)) { } else {
player.addAttachment(plugin).setPermission(permission, value); player.addAttachment(plugin).setPermission(permission, value);
} }
} }

Datei anzeigen

@ -22,7 +22,6 @@ package com.sk89q.worldedit.bukkit;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.bukkit.FaweBukkit; import com.boydti.fawe.bukkit.FaweBukkit;
import com.boydti.fawe.util.MainUtil;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.sk89q.util.yaml.YAMLProcessor; import com.sk89q.util.yaml.YAMLProcessor;
import com.sk89q.wepif.PermissionsResolverManager; import com.sk89q.wepif.PermissionsResolverManager;
@ -32,7 +31,6 @@ import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.adapter.AdapterLoadException; import com.sk89q.worldedit.bukkit.adapter.AdapterLoadException;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplLoader; import com.sk89q.worldedit.bukkit.adapter.BukkitImplLoader;
import com.sk89q.worldedit.bukkit.adapter.impl.FAWE_Spigot_v1_14_R4;
import com.sk89q.worldedit.bukkit.adapter.impl.FAWE_Spigot_v1_15_R2; import com.sk89q.worldedit.bukkit.adapter.impl.FAWE_Spigot_v1_15_R2;
import com.sk89q.worldedit.bukkit.adapter.impl.FAWE_Spigot_v1_16_R1; import com.sk89q.worldedit.bukkit.adapter.impl.FAWE_Spigot_v1_16_R1;
import com.sk89q.worldedit.bukkit.adapter.impl.FAWE_Spigot_v1_16_R2; import com.sk89q.worldedit.bukkit.adapter.impl.FAWE_Spigot_v1_16_R2;
@ -67,12 +65,7 @@ import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldInitEvent; import org.bukkit.event.world.WorldInitEvent;
import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue; import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -82,16 +75,12 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level; import java.util.logging.Level;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -118,77 +107,15 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
private static final Logger log = LoggerFactory.getLogger(WorldEditPlugin.class); private static final Logger log = LoggerFactory.getLogger(WorldEditPlugin.class);
public static final String CUI_PLUGIN_CHANNEL = "worldedit:cui"; public static final String CUI_PLUGIN_CHANNEL = "worldedit:cui";
private static WorldEditPlugin INSTANCE; private static WorldEditPlugin INSTANCE;
// The BSTATS_ID needs to be modified for FAWE to prevent contaminating WorldEdit stats
private static final int BSTATS_PLUGIN_ID = 1403; private static final int BSTATS_PLUGIN_ID = 1403;
private BukkitImplAdapter bukkitAdapter; private BukkitImplAdapter bukkitAdapter;
private BukkitServerInterface server; private BukkitServerInterface server;
private BukkitConfiguration config; private BukkitConfiguration config;
private static Map<String, Plugin> lookupNames;
static {
// Disable AWE as otherwise both fail to load
PluginManager manager = Bukkit.getPluginManager();
try {
Field pluginsField = manager.getClass().getDeclaredField("plugins");
Field lookupNamesField = manager.getClass().getDeclaredField("lookupNames");
pluginsField.setAccessible(true);
lookupNamesField.setAccessible(true);
List<Plugin> plugins = (List<Plugin>) pluginsField.get(manager);
lookupNames = (Map<String, Plugin>) lookupNamesField.get(manager);
pluginsField.set(manager, new ArrayList<Plugin>(plugins) {
@Override
public boolean add(Plugin plugin) {
if (plugin.getName().startsWith("AsyncWorldEdit")) {
log.debug("Disabling `" + plugin.getName() + "` as it is incompatible");
} else {
return super.add(plugin);
}
return false;
}
});
lookupNamesField.set(manager, lookupNames = new ConcurrentHashMap<String, Plugin>(lookupNames) {
@Override
public Plugin put(@NotNull String key, @NotNull Plugin plugin) {
if (plugin.getName().startsWith("AsyncWorldEdit")) {
return null;
}
return super.put(key, plugin);
}
});
} catch (Throwable ignored) {
}
}
public WorldEditPlugin() {
init();
}
public WorldEditPlugin(JavaPluginLoader loader, PluginDescriptionFile desc, File dataFolder, File jarFile) {
super(loader, desc, dataFolder, jarFile);
init();
}
private void init() {
if (lookupNames != null) {
lookupNames.putIfAbsent("FastAsyncWorldEdit".toLowerCase(Locale.ROOT), this);
lookupNames.putIfAbsent("WorldEdit".toLowerCase(Locale.ROOT), this);
lookupNames.putIfAbsent("FastAsyncWorldEdit", this);
lookupNames.putIfAbsent("WorldEdit", this);
rename();
}
setEnabled(true);
}
@Override @Override
public void onLoad() { public void onLoad() {
if (INSTANCE != null) {
return;
}
rename();
INSTANCE = this; INSTANCE = this;
FaweBukkit imp = new FaweBukkit(this);
//noinspection ResultOfMethodCallIgnored //noinspection ResultOfMethodCallIgnored
getDataFolder().mkdirs(); getDataFolder().mkdirs();
@ -204,7 +131,15 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
ChunkDeleter.runFromFile(delChunks, true); ChunkDeleter.runFromFile(delChunks, true);
} }
fail(() -> PermissionsResolverManager.initialize(INSTANCE), "Failed to initialize permissions resolver"); if (this.getDataFolder().getParentFile().listFiles(file -> {
if (file.getName().equals("DummyFawe.jar")) {
file.delete();
return true;
}
return false;
}).length > 0) {
getLogger().warning("DummyFawe detected and automatically deleted! This file is no longer necessary.");
}
} }
/** /**
@ -212,10 +147,8 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
*/ */
@Override @Override
public void onEnable() { public void onEnable() {
if (INSTANCE != null) {
return; new FaweBukkit(this);
}
onLoad();
PermissionsResolverManager.initialize(this); // Setup permission resolver PermissionsResolverManager.initialize(this); // Setup permission resolver
@ -247,7 +180,6 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
} }
} }
//todo consider removing this again because it is better to stay consistent with upstream
// Setup metrics // Setup metrics
new Metrics(this, BSTATS_PLUGIN_ID); new Metrics(this, BSTATS_PLUGIN_ID);
} }
@ -335,44 +267,6 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
} }
} }
private void rename() {
File dir = new File(getDataFolder().getParentFile(), "FastAsyncWorldEdit");
try {
Field descriptionField = JavaPlugin.class.getDeclaredField("dataFolder");
descriptionField.setAccessible(true);
descriptionField.set(this, dir);
} catch (Throwable e) {
e.printStackTrace();
}
try {
File pluginsFolder = MainUtil.getJarFile().getParentFile();
for (File file : pluginsFolder.listFiles()) {
if (file.length() == 2052) {
return;
}
}
Plugin plugin = Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit");
File dummy = MainUtil.copyFile(MainUtil.getJarFile(), "DummyFawe.src", pluginsFolder, "DummyFawe.jar");
if (dummy != null && dummy.exists() && plugin == this) {
try {
Bukkit.getPluginManager().loadPlugin(dummy);
} catch (Throwable e) {
if (Bukkit.getUpdateFolderFile().mkdirs()) {
MainUtil.copyFile(MainUtil.getJarFile(), "DummyFawe.src", pluginsFolder, Bukkit.getUpdateFolder() + File.separator + "DummyFawe.jar");
} else {
getLogger().info("Please delete DummyFawe.jar and restart");
}
}
getLogger().info("Please restart the server if you have any plugins which depend on FAWE.");
} else if (dummy == null) {
MainUtil.copyFile(MainUtil.getJarFile(), "DummyFawe.src", pluginsFolder, "update" + File.separator + "DummyFawe.jar");
}
} catch (Throwable e) {
e.printStackTrace();
}
}
private void fail(Runnable run, String message) { private void fail(Runnable run, String message) {
try { try {
run.run(); run.run();
@ -399,7 +293,6 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
// Attempt to load a Bukkit adapter // Attempt to load a Bukkit adapter
BukkitImplLoader adapterLoader = new BukkitImplLoader(); BukkitImplLoader adapterLoader = new BukkitImplLoader();
try { try {
adapterLoader.addClass(FAWE_Spigot_v1_14_R4.class);
adapterLoader.addClass(FAWE_Spigot_v1_15_R2.class); adapterLoader.addClass(FAWE_Spigot_v1_15_R2.class);
adapterLoader.addClass(FAWE_Spigot_v1_16_R1.class); adapterLoader.addClass(FAWE_Spigot_v1_16_R1.class);
adapterLoader.addClass(FAWE_Spigot_v1_16_R2.class); adapterLoader.addClass(FAWE_Spigot_v1_16_R2.class);

Datei anzeigen

@ -1,457 +0,0 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.bukkit.adapter.impl;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.beta.IChunkGet;
import com.boydti.fawe.beta.implementation.packet.ChunkPacket;
import com.boydti.fawe.beta.implementation.queue.SingleThreadQueueExtent;
import com.boydti.fawe.bukkit.adapter.mc1_14.*;
import com.boydti.fawe.bukkit.adapter.mc1_14.nbt.LazyCompoundTag_1_14;
import com.google.common.io.Files;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.blocks.TileEntityBlock;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.CachedBukkitAdapter;
import com.sk89q.worldedit.bukkit.adapter.IDelegateBukkitImplAdapter;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.entity.LazyBaseEntity;
import com.sk89q.worldedit.internal.wna.WorldNativeAccess;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.*;
import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.registry.BlockMaterial;
import net.minecraft.server.v1_14_R1.*;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World.Environment;
import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.v1_14_R1.CraftChunk;
import org.bukkit.craftbukkit.v1_14_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_14_R1.block.CraftBlock;
import org.bukkit.craftbukkit.v1_14_R1.block.data.CraftBlockData;
import org.bukkit.craftbukkit.v1_14_R1.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_14_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_14_R1.inventory.CraftItemStack;
import org.bukkit.entity.Player;
import org.bukkit.generator.ChunkGenerator;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.OptionalInt;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.jnbt.StringTag;
public final class FAWE_Spigot_v1_14_R4 extends CachedBukkitAdapter implements IDelegateBukkitImplAdapter<NBTBase> {
private final Spigot_v1_14_R4 parent;
private char[] ibdToStateOrdinal;
// ------------------------------------------------------------------------
// Code that may break between versions of Minecraft
// ------------------------------------------------------------------------
public FAWE_Spigot_v1_14_R4() throws NoSuchFieldException, NoSuchMethodException {
this.parent = new Spigot_v1_14_R4();
}
@Override
public BukkitImplAdapter<NBTBase> getParent() {
return parent;
}
private synchronized boolean init() {
if (ibdToStateOrdinal != null && ibdToStateOrdinal[1] != 0) return false;
ibdToStateOrdinal = new char[Block.REGISTRY_ID.a()]; // size
for (int i = 0; i < ibdToStateOrdinal.length; i++) {
BlockState state = BlockTypesCache.states[i];
BlockMaterial_1_14 material = (BlockMaterial_1_14) state.getMaterial();
int id = Block.REGISTRY_ID.getId(material.getState());
ibdToStateOrdinal[id] = state.getOrdinalChar();
}
return true;
}
@Override
public BlockMaterial getMaterial(BlockType blockType) {
Block block = getBlock(blockType);
return new BlockMaterial_1_14(block);
}
@Override
public BlockMaterial getMaterial(BlockState state) {
IBlockData bs = ((CraftBlockData) Bukkit.createBlockData(state.getAsString())).getState();
return new BlockMaterial_1_14(bs.getBlock(), bs);
}
public Block getBlock(BlockType blockType) {
return IRegistry.BLOCK.get(new MinecraftKey(blockType.getNamespace(), blockType.getResource()));
}
@SuppressWarnings("deprecation")
@Override
public BaseBlock getBlock(Location location) {
checkNotNull(location);
CraftWorld craftWorld = ((CraftWorld) location.getWorld());
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
org.bukkit.block.Block bukkitBlock = location.getBlock();
BlockState state = BukkitAdapter.adapt(bukkitBlock.getBlockData());
if (state.getBlockType().getMaterial().hasContainer()) {
//Read the NBT data
TileEntity te = craftWorld.getHandle().getTileEntity(new BlockPosition(x, y, z));
if (te != null) {
NBTTagCompound tag = new NBTTagCompound();
te.save(tag); // readTileEntityIntoTag
return state.toBaseBlock((CompoundTag) toNative(tag));
}
}
return state.toBaseBlock();
}
@Override
public Set<SideEffect> getSupportedSideEffects() {
return SideEffectSet.defaults().getSideEffectsToApply();
}
public boolean setBlock(org.bukkit.Chunk chunk, int x, int y, int z, BlockStateHolder state, boolean update) {
CraftChunk craftChunk = (CraftChunk) chunk;
Chunk nmsChunk = craftChunk.getHandle();
World nmsWorld = nmsChunk.getWorld();
IBlockData blockData = ((BlockMaterial_1_14) state.getMaterial()).getState();
ChunkSection[] sections = nmsChunk.getSections();
int y4 = y >> 4;
ChunkSection section = sections[y4];
IBlockData existing;
if (section == null) {
existing = ((BlockMaterial_1_14) BlockTypes.AIR.getDefaultState().getMaterial()).getState();
} else {
existing = section.getType(x & 15, y & 15, z & 15);
}
BlockPosition pos = new BlockPosition(x, y, z);
nmsChunk.removeTileEntity(pos); // Force delete the old tile entity
CompoundTag nativeTag = state instanceof BaseBlock ? ((BaseBlock)state).getNbtData() : null;
if (nativeTag != null || existing instanceof TileEntityBlock) {
nmsWorld.setTypeAndData(pos, blockData, 0);
// remove tile
if (nativeTag != null) {
// We will assume that the tile entity was created for us,
// though we do not do this on the Forge version
TileEntity tileEntity = nmsWorld.getTileEntity(pos);
if (tileEntity != null) {
NBTTagCompound tag = (NBTTagCompound) fromNative(nativeTag);
tag.set("x", new NBTTagInt(x));
tag.set("y", new NBTTagInt(y));
tag.set("z", new NBTTagInt(z));
tileEntity.load(tag); // readTagIntoTileEntity
}
}
} else {
if (existing == blockData) return true;
if (section == null) {
if (blockData.isAir()) return true;
sections[y4] = section = new ChunkSection(y4 << 4);
}
nmsChunk.setType(pos = new BlockPosition(x, y, z), blockData, false);
}
if (update) {
nmsWorld.getMinecraftWorld().notify(pos, existing, blockData, 0);
}
return true;
}
@Override
public WorldNativeAccess<?, ?, ?> createWorldNativeAccess(org.bukkit.World world) {
return new FAWEWorldNativeAccess_1_14(this,
new WeakReference<>(((CraftWorld) world).getHandle()));
}
@Nullable
private static String getEntityId(Entity entity) {
MinecraftKey minecraftkey = EntityTypes.getName(entity.getEntityType());
return minecraftkey == null ? null : minecraftkey.toString();
}
private static void readEntityIntoTag(Entity entity, NBTTagCompound tag) {
entity.save(tag);
}
@Override
public BaseEntity getEntity(org.bukkit.entity.Entity entity) {
checkNotNull(entity);
CraftEntity craftEntity = ((CraftEntity) entity);
Entity mcEntity = craftEntity.getHandle();
String id = getEntityId(mcEntity);
if (id != null) {
EntityType type = com.sk89q.worldedit.world.entity.EntityTypes.get(id);
Supplier<CompoundTag> saveTag = () -> {
NBTTagCompound tag = new NBTTagCompound();
readEntityIntoTag(mcEntity, tag);
//add Id for AbstractChangeSet to work
CompoundTag natve = (CompoundTag) toNative(tag);
natve.getValue().put("Id", new StringTag(id));
return natve;
};
return new LazyBaseEntity(type, saveTag);
} else {
return null;
}
}
@Override
public OptionalInt getInternalBlockStateId(BlockState state) {
BlockMaterial_1_14 material = (BlockMaterial_1_14) state.getMaterial();
IBlockData mcState = material.getCraftBlockData().getState();
return OptionalInt.of(Block.REGISTRY_ID.getId(mcState));
}
@Override
public BlockState adapt(BlockData blockData) {
CraftBlockData cbd = ((CraftBlockData) blockData);
IBlockData ibd = cbd.getState();
return adapt(ibd);
}
public BlockState adapt(IBlockData ibd) {
return BlockTypesCache.states[adaptToChar(ibd)];
}
/**
* @deprecated
* Method unused. Use #adaptToChar(IBlockData).
*/
@Deprecated
public int adaptToInt(IBlockData ibd) {
synchronized (this) {
try {
int id = Block.REGISTRY_ID.getId(ibd);
return ibdToStateOrdinal[id];
} catch (NullPointerException e) {
init();
return adaptToInt(ibd);
}
}
}
public char adaptToChar(IBlockData ibd) {
synchronized (this) {
try {
int id = Block.REGISTRY_ID.getId(ibd);
return ibdToStateOrdinal[id];
} catch (NullPointerException e) {
init();
return adaptToChar(ibd);
} catch(ArrayIndexOutOfBoundsException e1){
Fawe.debug("Attempted to convert " + ibd.getBlock() + " with ID " + Block.REGISTRY_ID.getId(ibd) + " to char. ibdToStateOrdinal length: " + ibdToStateOrdinal.length + ". Defaulting to air!");
return 0;
}
}
}
@Override
public <B extends BlockStateHolder<B>> BlockData adapt(B state) {
BlockMaterial_1_14 material = (BlockMaterial_1_14) state.getMaterial();
return material.getCraftBlockData();
}
private MapChunkUtil_1_14 mapUtil = new MapChunkUtil_1_14();
@Override
public void sendFakeChunk(org.bukkit.World world, Player player, ChunkPacket packet) {
WorldServer nmsWorld = ((CraftWorld) world).getHandle();
PlayerChunk map = BukkitAdapter_1_14.getPlayerChunk(nmsWorld, packet.getChunkX(), packet.getChunkZ());
if (map != null && map.hasBeenLoaded()) {
boolean flag = false;
PlayerChunk.d players = map.players;
Stream<EntityPlayer> stream = players.a(new ChunkCoordIntPair(packet.getChunkX(), packet.getChunkZ()), flag);
EntityPlayer checkPlayer = player == null ? null : ((CraftPlayer) player).getHandle();
stream.filter(entityPlayer -> checkPlayer == null || entityPlayer == checkPlayer)
.forEach(entityPlayer -> {
synchronized (packet) {
PacketPlayOutMapChunk nmsPacket = (PacketPlayOutMapChunk) packet.getNativePacket();
if (nmsPacket == null) {
nmsPacket = mapUtil.create( this, packet);
packet.setNativePacket(nmsPacket);
}
try {
FaweCache.IMP.CHUNK_FLAG.get().set(true);
entityPlayer.playerConnection.sendPacket(nmsPacket);
} finally {
FaweCache.IMP.CHUNK_FLAG.get().set(false);
}
}
});
}
}
@Override
public Map<String, ? extends Property<?>> getProperties(BlockType blockType) {
return getParent().getProperties(blockType);
}
@Override
public org.bukkit.inventory.ItemStack adapt(BaseItemStack item) {
ItemStack stack = new ItemStack(IRegistry.ITEM.get(MinecraftKey.a(item.getType().getId())), item.getAmount());
stack.setTag(((NBTTagCompound) fromNative(item.getNbtData())));
return CraftItemStack.asCraftMirror(stack);
}
@Override
public BaseItemStack adapt(org.bukkit.inventory.ItemStack itemStack) {
final ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack);
final BaseItemStack weStack = new BaseItemStack(BukkitAdapter.asItemType(itemStack.getType()), itemStack.getAmount());
weStack.setNbtData(((CompoundTag) toNative(nmsStack.getTag())));
return weStack;
}
@Override
public Tag toNative(NBTBase foreign) {
return parent.toNative(foreign);
}
@Override
public NBTBase fromNative(Tag foreign) {
if (foreign instanceof LazyCompoundTag_1_14) {
return ((LazyCompoundTag_1_14) foreign).get();
}
return parent.fromNative(foreign);
}
@Override
public boolean regenerate(org.bukkit.World world, Region region, EditSession editSession) {
WorldServer originalWorld = ((CraftWorld) world).getHandle();
ChunkProviderServer provider = originalWorld.getChunkProvider();
if (!(provider instanceof ChunkProviderServer)) {
return false;
}
File saveFolder = Files.createTempDir();
// register this just in case something goes wrong
// normally it should be deleted at the end of this method
saveFolder.deleteOnExit();
try {
MinecraftServer server = originalWorld.getServer().getServer();
WorldNBTStorage originalDataManager = originalWorld.getDataManager();
WorldNBTStorage saveHandler = new WorldNBTStorage(saveFolder, originalDataManager.getDirectory().getName(), server, originalDataManager.getDataFixer());
WorldData newWorldData = new WorldData(originalWorld.worldData.a((NBTTagCompound) null),
server.dataConverterManager, getDataVersion(), null);
ChunkGenerator gen = world.getGenerator();
Environment env = world.getEnvironment();
try (WorldServer freshWorld = new WorldServer(server,
server.executorService, saveHandler,
newWorldData,
originalWorld.worldProvider.getDimensionManager(),
originalWorld.getMethodProfiler(),
server.worldLoadListenerFactory.create(11),
env,
gen){
@Override
public boolean addEntityChunk(net.minecraft.server.v1_14_R1.Entity entity) {
//Fixes #320; Prevent adding entities so we aren't attempting to spawn them asynchronously
return false;
}
}) {
// Pre-gen all the chunks
// We need to also pull one more chunk in every direction
Fawe.get().getQueueHandler().startSet(true);
try {
SingleThreadQueueExtent extent = new SingleThreadQueueExtent();
extent.init(null, (x, z) -> new BukkitGetBlocks_1_14(freshWorld, x, z) {
@Override
public Chunk ensureLoaded(World nmsWorld, int chunkX, int chunkZ) {
Chunk cached = nmsWorld.getChunkIfLoaded(chunkX, chunkZ);
if (cached != null) return cached;
Future<Chunk> future = Fawe.get().getQueueHandler().sync((Supplier<Chunk>) () -> freshWorld.getChunkAt(
chunkX, chunkZ));
while (!future.isDone()) {
// this feels so dirty
freshWorld.getChunkProvider().runTasks();
}
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
}, null);
for (BlockVector3 vec : region) {
editSession.setBlock(vec, extent.getFullBlock(vec));
}
} finally {
Fawe.get().getQueueHandler().endSet(true);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (MaxChangedBlocksException e) {
throw new RuntimeException(e);
} finally {
saveFolder.delete();
}
return true;
}
@Override
public IChunkGet get(org.bukkit.World world, int chunkX, int chunkZ) {
return new BukkitGetBlocks_1_14(world, chunkX, chunkZ);
}
@Override
public int getInternalBiomeId(BiomeType biome) {
BiomeBase base = CraftBlock.biomeToBiomeBase(BukkitAdapter.adapt(biome));
return IRegistry.BIOME.a(base);
}
}

Datei anzeigen

@ -1,720 +0,0 @@
package org.bstats.bukkit;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Metrics {
static {
// You can use the property to disable the check in your test environment
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
final String defaultPackage = new String(
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure nobody just copy & pastes the example and use the wrong package names
if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Is bStats enabled on this server?
private boolean enabled;
// Should failed requests be logged?
private static boolean logFailedRequests;
// Should the sent data be logged?
private static boolean logSentData;
// Should the response text be logged?
private static boolean logResponseStatusText;
// The uuid of the server
private static String serverUUID;
// The plugin
private final Plugin plugin;
// The plugin id
private final int pluginId;
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
* @param pluginId The id of the plugin.
* It can be found at <a href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
*/
public Metrics(Plugin plugin, int pluginId) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
this.pluginId = pluginId;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Should the sent data be logged?
config.addDefault("logSentData", false);
// Should the response text be logged?
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
}
// Load the data
enabled = config.getBoolean("enabled", true);
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
if (enabled) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) { }
}
// Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
}
}
}
/**
* Checks if bStats is enabled.
*
* @return Whether bStats is enabled or not.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!");
}
charts.add(chart);
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JsonObject getPluginData() {
JsonObject data = new JsonObject();
String pluginName = "FastAsyncWorldEdit";
String pluginVersion = plugin.getDescription().getVersion();
data.addProperty("pluginName", pluginName); // Append the name of the plugin
data.addProperty("id", pluginId); // Append the id of the plugin
data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
JsonArray customCharts = new JsonArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JsonObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.add("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JsonObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
String bukkitName = Bukkit.getName();
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JsonObject data = new JsonObject();
data.addProperty("serverUUID", serverUUID);
data.addProperty("playerAmount", playerAmount);
data.addProperty("onlineMode", onlineMode);
data.addProperty("bukkitVersion", bukkitVersion);
data.addProperty("bukkitName", bukkitName);
data.addProperty("javaVersion", javaVersion);
data.addProperty("osName", osName);
data.addProperty("osArch", osArch);
data.addProperty("osVersion", osVersion);
data.addProperty("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JsonObject data = getServerData();
JsonArray pluginData = new JsonArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin);
} else { // old bstats version compatibility
try {
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
jsonStringGetter.setAccessible(true);
String jsonString = (String) jsonStringGetter.invoke(plugin);
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
pluginData.add(object);
}
} catch (ClassNotFoundException e) {
// minecraft version 1.14+
if (logFailedRequests) {
this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
}
}
}
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
}
} catch (NoSuchFieldException ignored) { }
}
data.add("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(() -> {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}).start();
}
/**
* Sends the data to the bStats server.
*
* @param plugin Any plugin. It's just used to get a logger instance.
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data);
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(compressedData);
}
StringBuilder builder = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
}
if (logResponseStatusText) {
plugin.getLogger().info("Sent data to bStats and received response: " + builder);
}
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
gzip.write(str.getBytes(StandardCharsets.UTF_8));
}
return outputStream.toByteArray();
}
/**
* Represents a custom chart.
*/
public static abstract class CustomChart {
// The id of the chart
final String chartId;
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!");
}
this.chartId = chartId;
}
private JsonObject getRequestJsonObject() {
JsonObject chart = new JsonObject();
chart.addProperty("chartId", chartId);
try {
JsonObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.add("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return chart;
}
protected abstract JsonObject getChartData() throws Exception;
}
/**
* Represents a custom simple pie.
*/
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimplePie(String chartId, Callable<String> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
data.addProperty("value", value);
return data;
}
}
/**
* Represents a custom advanced pie.
*/
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.addProperty(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom drilldown pie.
*/
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JsonObject value = new JsonObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.addProperty(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
values.add(entryValues.getKey(), value);
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
data.addProperty("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.addProperty(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JsonArray categoryValues = new JsonArray();
categoryValues.add(new JsonPrimitive(entry.getValue()));
values.add(entry.getKey(), categoryValues);
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JsonArray categoryValues = new JsonArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(new JsonPrimitive(categoryValue));
}
values.add(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
}

Datei anzeigen

@ -1,9 +1,10 @@
name: WorldEdit name: FastAsyncWorldEdit
main: com.sk89q.worldedit.bukkit.WorldEditPlugin main: com.sk89q.worldedit.bukkit.WorldEditPlugin
version: "${internalVersion}" version: "${internalVersion}"
load: STARTUP load: STARTUP
api-version: 1.13 api-version: 1.15
softdepend: [Vault] softdepend: [Vault]
provides: [WorldEdit]
website: https://intellectualsites.github.io/download/fawe.html website: https://intellectualsites.github.io/download/fawe.html
description: Blazingly fast world manipulation for builders, large networks and developers. description: Blazingly fast world manipulation for builders, large networks and developers.
authors: [Empire92, MattBDev, IronApollo, dordsor21, NotMyFault] authors: [Empire92, MattBDev, IronApollo, dordsor21, NotMyFault]

Datei anzeigen

@ -53,12 +53,12 @@ public final class Constants {
public static final int DATA_VERSION_MC_1_13_2 = 1631; public static final int DATA_VERSION_MC_1_13_2 = 1631;
/** /**
* The DataVersion for Minecraft 1.16 * The DataVersion for Minecraft 1.14
*/ */
public static final int DATA_VERSION_MC_1_14 = 1952; public static final int DATA_VERSION_MC_1_14 = 1952;
/** /**
* The DataVersion for Minecraft 1.16 * The DataVersion for Minecraft 1.15
*/ */
public static final int DATA_VERSION_MC_1_15 = 2225; public static final int DATA_VERSION_MC_1_15 = 2225;

Datei anzeigen

@ -100,8 +100,6 @@ public final class BundledBlockData {
url = resourceLoader.getResource(BundledBlockData.class, "blocks.116.json"); url = resourceLoader.getResource(BundledBlockData.class, "blocks.116.json");
} else if (dataVersion >= Constants.DATA_VERSION_MC_1_15) { } else if (dataVersion >= Constants.DATA_VERSION_MC_1_15) {
url = resourceLoader.getResource(BundledBlockData.class, "blocks.115.json"); url = resourceLoader.getResource(BundledBlockData.class, "blocks.115.json");
} else if (dataVersion >= Constants.DATA_VERSION_MC_1_14) {
url = resourceLoader.getResource(BundledBlockData.class, "blocks.114.json");
} }
if (url == null) { if (url == null) {
url = resourceLoader.getResource(BundledBlockData.class, "blocks.json"); url = resourceLoader.getResource(BundledBlockData.class, "blocks.json");

Datei anzeigen

@ -87,8 +87,6 @@ public final class BundledItemData {
url = resourceLoader.getResource(BundledBlockData.class, "items.116.json"); url = resourceLoader.getResource(BundledBlockData.class, "items.116.json");
} else if (dataVersion >= Constants.DATA_VERSION_MC_1_15) { } else if (dataVersion >= Constants.DATA_VERSION_MC_1_15) {
url = resourceLoader.getResource(BundledBlockData.class, "items.115.json"); url = resourceLoader.getResource(BundledBlockData.class, "items.115.json");
} else if (dataVersion >= Constants.DATA_VERSION_MC_1_14) {
url = resourceLoader.getResource(BundledBlockData.class, "items.114.json");
} }
if (url == null) { if (url == null) {
url = resourceLoader.getResource(BundledBlockData.class, "items.json"); url = resourceLoader.getResource(BundledBlockData.class, "items.json");