ref: switch from adventure NBT to LinBus (#2778)

* Switch from adventure NBT to LinBus

* Cleanup

* Clean

* Reimplement NumberTag behaviour

* Use 0.1.0 release

* Fix build, remove fawe tags

---------

Co-authored-by: Octavia Togami <octavia.togami@gmail.com>
This commit is contained in:
Jordan
2024-06-26 21:55:47 +02:00
committed by GitHub
parent 6dd779f90b
commit ad5739e014
134 changed files with 2258 additions and 2542 deletions

View File

@ -125,7 +125,7 @@ public class MobSpawnerBlock extends BaseBlock {
@Override
public CompoundTag getNbtData() {
Map<String, Tag> values = new HashMap<>();
Map<String, Tag<?, ?>> values = new HashMap<>();
values.put("Delay", new ShortTag(delay));
values.put("SpawnCount", new ShortTag(spawnCount));
values.put("SpawnRange", new ShortTag(spawnRange));
@ -170,7 +170,7 @@ public class MobSpawnerBlock extends BaseBlock {
return;
}
Map<String, Tag> values = rootTag.getValue();
Map<String, Tag<?, ?>> values = rootTag.getValue();
Tag t = values.get("id");
if (!(t instanceof StringTag) || !((StringTag) t).getValue().equals(getNbtId())) {

View File

@ -104,7 +104,7 @@ public class SignBlock extends BaseBlock {
@Override
public CompoundTag getNbtData() {
Map<String, Tag> values = new HashMap<>();
Map<String, Tag<?, ?>> values = new HashMap<>();
if (isLegacy()) {
values.put("Text1", new StringTag(text[0]));
values.put("Text2", new StringTag(text[1]));
@ -112,7 +112,7 @@ public class SignBlock extends BaseBlock {
values.put("Text4", new StringTag(text[3]));
} else {
ListTag messages = new ListTag(StringTag.class, Arrays.stream(text).map(StringTag::new).collect(Collectors.toList()));
Map<String, Tag> frontTextTag = new HashMap<>();
Map<String, Tag<?, ?>> frontTextTag = new HashMap<>();
frontTextTag.put("messages", messages);
values.put("front_text", new CompoundTag(frontTextTag));
}
@ -125,9 +125,9 @@ public class SignBlock extends BaseBlock {
return;
}
Map<String, Tag> values = rootTag.getValue();
Map<String, Tag<?, ?>> values = rootTag.getValue();
Tag t;
Tag<?, ?> t;
text = new String[]{EMPTY, EMPTY, EMPTY, EMPTY};

View File

@ -100,8 +100,8 @@ public class SkullBlock extends BaseBlock {
@Override
public CompoundTag getNbtData() {
Map<String, Tag> values = new HashMap<>();
Map<String, Tag> inner = new HashMap<>();
Map<String, Tag<?, ?>> values = new HashMap<>();
Map<String, Tag<?, ?>> inner = new HashMap<>();
inner.put("Name", new StringTag(owner));
values.put(DeprecationUtil.getHeadOwnerKey(), new CompoundTag(inner));
return new CompoundTag(values);
@ -113,7 +113,7 @@ public class SkullBlock extends BaseBlock {
return;
}
Map<String, Tag> values = rootTag.getValue();
Map<String, Tag<?, ?>> values = rootTag.getValue();
Tag t;

View File

@ -532,7 +532,7 @@ public enum FaweCache implements Trimable {
}
public CompoundTag asTag(Map<String, Object> value) {
HashMap<String, Tag> map = new HashMap<>();
HashMap<String, Tag<?, ?>> map = new HashMap<>();
for (Map.Entry<String, Object> entry : value.entrySet()) {
Object child = entry.getValue();
Tag tag = asTag(child);

View File

@ -3,25 +3,25 @@ package com.fastasyncworldedit.core.entity;
import com.fastasyncworldedit.core.Fawe;
import com.fastasyncworldedit.core.util.TaskManager;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.entity.EntityType;
import org.enginehub.linbus.tree.LinCompoundTag;
import javax.annotation.Nullable;
import java.util.function.Supplier;
public class LazyBaseEntity extends BaseEntity {
private Supplier<CompoundBinaryTag> saveTag;
private Supplier<LinCompoundTag> saveTag;
public LazyBaseEntity(EntityType type, Supplier<CompoundBinaryTag> saveTag) {
public LazyBaseEntity(EntityType type, Supplier<LinCompoundTag> saveTag) {
super(type);
this.saveTag = saveTag;
}
@Nullable
@Override
public CompoundBinaryTag getNbt() {
Supplier<CompoundBinaryTag> tmp = saveTag;
public LinCompoundTag getNbt() {
Supplier<LinCompoundTag> tmp = saveTag;
if (tmp != null) {
saveTag = null;
if (Fawe.isMainThread()) {

View File

@ -29,8 +29,6 @@ import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
@ -81,7 +79,7 @@ public class StripNBTExtent extends AbstractDelegateExtent implements IBatchProc
return block;
}
CompoundTag nbt = localBlock.getNbtData();
Map<String, Tag> value = new HashMap<>(nbt.getValue());
Map<String, Tag<?, ?>> value = new HashMap<>(nbt.getValue());
for (String key : strip) {
value.remove(key);
}
@ -93,7 +91,7 @@ public class StripNBTExtent extends AbstractDelegateExtent implements IBatchProc
return entity;
}
CompoundTag nbt = entity.getNbtData();
Map<String, Tag> value = new HashMap<>(nbt.getValue());
Map<String, Tag<?, ?>> value = new HashMap<>(nbt.getValue());
for (String key : strip) {
value.remove(key);
}
@ -110,7 +108,7 @@ public class StripNBTExtent extends AbstractDelegateExtent implements IBatchProc
}
boolean isBv3ChunkMap = tiles instanceof BlockVector3ChunkMap;
for (final Map.Entry<BlockVector3, CompoundTag> entry : tiles.entrySet()) {
ImmutableMap.Builder<String, Tag> map = ImmutableMap.builder();
ImmutableMap.Builder<String, Tag<?, ?>> map = ImmutableMap.builder();
final AtomicBoolean isStripped = new AtomicBoolean(false);
entry.getValue().getValue().forEach((k, v) -> {
if (strip.contains(k.toLowerCase())) {
@ -132,7 +130,7 @@ public class StripNBTExtent extends AbstractDelegateExtent implements IBatchProc
Iterator<CompoundTag> iterator = entities.iterator();
while (iterator.hasNext()) {
CompoundTag entity = iterator.next();
ImmutableMap.Builder<String, Tag> map = ImmutableMap.builder();
ImmutableMap.Builder<String, Tag<?, ?>> map = ImmutableMap.builder();
final AtomicBoolean isStripped = new AtomicBoolean(false);
entity.getValue().forEach((k, v) -> {
if (strip.contains(k.toUpperCase(Locale.ROOT))) {

View File

@ -152,7 +152,7 @@ public class CPUOptimizedClipboard extends LinearClipboard {
public Collection<CompoundTag> getTileEntities() {
convertTilesToIndex();
nbtMapIndex.replaceAll((index, tag) -> {
Map<String, Tag> values = new HashMap<>(tag.getValue());
Map<String, Tag<?, ?>> values = new HashMap<>(tag.getValue());
if (!values.containsKey("x")) {
int y = index / getArea();
index -= y * getArea();
@ -176,7 +176,7 @@ public class CPUOptimizedClipboard extends LinearClipboard {
}
private boolean setTile(int index, CompoundTag tag) {
final Map<String, Tag> values = new HashMap<>(tag.getValue());
final Map<String, Tag<?, ?>> values = new HashMap<>(tag.getValue());
values.remove("x");
values.remove("y");
values.remove("z");

View File

@ -586,7 +586,7 @@ public class DiskOptimizedClipboard extends LinearClipboard {
for (BlockArrayClipboard.ClipboardEntity entity : entities) {
if (entity.getState() != null && entity.getState().getNbtData() != null) {
CompoundTag data = entity.getState().getNbtData();
HashMap<String, Tag> value = new HashMap<>(data.getValue());
HashMap<String, Tag<?, ?>> value = new HashMap<>(data.getValue());
List<DoubleTag> pos = new ArrayList<>(3);
pos.add(new DoubleTag(entity.getLocation().x()));
pos.add(new DoubleTag(entity.getLocation().x()));
@ -710,7 +710,7 @@ public class DiskOptimizedClipboard extends LinearClipboard {
@Override
public boolean setTile(int x, int y, int z, CompoundTag tag) {
final Map<String, Tag> values = new HashMap<>(tag.getValue());
final Map<String, Tag<?, ?>> values = new HashMap<>(tag.getValue());
values.put("x", new IntTag(x));
values.put("y", new IntTag(y));
values.put("z", new IntTag(z));

View File

@ -106,7 +106,7 @@ public abstract class LinearClipboard extends SimpleClipboard {
@Nullable
@Override
public Entity createEntity(Location location, BaseEntity entity, UUID uuid) {
Map<String, Tag> map = new HashMap<>(entity.getNbtData().getValue());
Map<String, Tag<?, ?>> map = new HashMap<>(entity.getNbtData().getValue());
NBTUtils.addUUIDToMap(map, uuid);
entity.setNbtData(new CompoundTag(map));
BlockArrayClipboard.ClipboardEntity ret = new BlockArrayClipboard.ClipboardEntity(location, entity);

View File

@ -254,7 +254,7 @@ public class MemoryOptimizedClipboard extends LinearClipboard {
@Override
public boolean setTile(int x, int y, int z, CompoundTag tag) {
final Map<String, Tag> values = new HashMap<>(tag.getValue());
final Map<String, Tag<?, ?>> values = new HashMap<>(tag.getValue());
values.put("x", new IntTag(x));
values.put("y", new IntTag(y));
values.put("z", new IntTag(z));

View File

@ -9,7 +9,7 @@ import com.fastasyncworldedit.core.internal.io.FaweInputStream;
import com.fastasyncworldedit.core.internal.io.FaweOutputStream;
import com.fastasyncworldedit.core.jnbt.streamer.StreamDelegate;
import com.fastasyncworldedit.core.jnbt.streamer.ValueReader;
import com.sk89q.jnbt.AdventureNBTConverter;
import com.sk89q.jnbt.LinBusConverter;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.NBTInputStream;
@ -109,10 +109,10 @@ public class FastSchematicReader extends NBTSchematicReader {
if (fixer == null || dataVersion == -1) {
return tag;
}
//FAWE start - BinaryTag
return (CompoundTag) AdventureNBTConverter.fromAdventure(fixer.fixUp(
//FAWE start - LinTag
return (CompoundTag) LinBusConverter.fromLinBus(fixer.fixUp(
DataFixer.FixTypes.BLOCK_ENTITY,
tag.asBinaryTag(),
tag.toLinTag(),
dataVersion
));
//FAWE end
@ -122,10 +122,10 @@ public class FastSchematicReader extends NBTSchematicReader {
if (fixer == null || dataVersion == -1) {
return tag;
}
//FAWE start - BinaryTag
return (CompoundTag) AdventureNBTConverter.fromAdventure(fixer.fixUp(
//FAWE start - LinTag
return (CompoundTag) LinBusConverter.fromLinBus(fixer.fixUp(
DataFixer.FixTypes.ENTITY,
tag.asBinaryTag(),
tag.toLinTag(),
dataVersion
));
//FAWE end
@ -344,7 +344,7 @@ public class FastSchematicReader extends NBTSchematicReader {
y = pos[1];
z = pos[2];
}
Map<String, Tag> values = new HashMap<>(tile.getValue());
Map<String, Tag<?, ?>> values = new HashMap<>(tile.getValue());
Tag id = values.get("Id");
if (id != null) {
values.put("x", new IntTag(x));
@ -371,7 +371,7 @@ public class FastSchematicReader extends NBTSchematicReader {
// entities
if (entities != null && !entities.isEmpty()) {
for (Map<String, Object> entRaw : entities) {
Map<String, Tag> value = new HashMap<>(FaweCache.INSTANCE.asTag(entRaw).getValue());
Map<String, Tag<?, ?>> value = new HashMap<>(FaweCache.INSTANCE.asTag(entRaw).getValue());
StringTag id = (StringTag) value.get("Id");
if (id == null) {
id = (StringTag) value.get("id");

View File

@ -149,7 +149,7 @@ public class FastSchematicWriter implements ClipboardWriter {
BaseBlock block = pos.getFullBlock(finalClipboard);
CompoundTag nbt = block.getNbtData();
if (nbt != null) {
Map<String, Tag> values = new HashMap<>(nbt.getValue());
Map<String, Tag<?, ?>> values = new HashMap<>(nbt.getValue());
// Positions are kept in NBT, we don't want that.
values.remove("x");
@ -223,7 +223,7 @@ public class FastSchematicWriter implements ClipboardWriter {
BaseEntity state = entity.getState();
if (state != null) {
Map<String, Tag> values = new HashMap<>();
Map<String, Tag<?, ?>> values = new HashMap<>();
// Put NBT provided data
CompoundTag rawTag = state.getNbtData();

View File

@ -70,7 +70,7 @@ public class MinecraftStructure implements ClipboardReader, ClipboardWriter {
throw new IOException("Root tag has name - are you sure this is a structure?");
}
Map<String, Tag> tags = ((CompoundTag) rootTag.getTag()).getValue();
Map<String, Tag<?, ?>> tags = ((CompoundTag) rootTag.getTag()).getValue();
ListTag size = (ListTag) tags.get("size");
int width = size.getInt(0);
@ -89,13 +89,13 @@ public class MinecraftStructure implements ClipboardReader, ClipboardWriter {
BlockState[] combinedArray = new BlockState[palette.size()];
for (int i = 0; i < palette.size(); i++) {
CompoundTag compound = palette.get(i);
Map<String, Tag> map = compound.getValue();
Map<String, Tag<?, ?>> map = compound.getValue();
String name = ((StringTag) map.get("Name")).getValue();
BlockType type = BlockTypes.get(name);
BlockState state = type.getDefaultState();
CompoundTag properties = (CompoundTag) map.get("Properties");
if (properties != null) {
for (Map.Entry<String, Tag> entry : properties.getValue().entrySet()) {
for (Map.Entry<String, Tag<?, ?>> entry : properties.getValue().entrySet()) {
String key = entry.getKey();
String value = ((StringTag) entry.getValue()).getValue();
Property<Object> property = type.getProperty(key);
@ -108,7 +108,7 @@ public class MinecraftStructure implements ClipboardReader, ClipboardWriter {
List<CompoundTag> blocksList = (List<CompoundTag>) tags.get("blocks").getValue();
try {
for (CompoundTag compound : blocksList) {
Map<String, Tag> blockMap = compound.getValue();
Map<String, Tag<?, ?>> blockMap = compound.getValue();
IntTag stateTag = (IntTag) blockMap.get("state");
ListTag posTag = (ListTag) blockMap.get("pos");
BlockState state = combinedArray[stateTag.getValue()];
@ -136,7 +136,7 @@ public class MinecraftStructure implements ClipboardReader, ClipboardWriter {
if (entities != null) {
List<CompoundTag> entityList = (List<CompoundTag>) (List<?>) entities.getValue();
for (CompoundTag entityEntry : entityList) {
Map<String, Tag> entityEntryMap = entityEntry.getValue();
Map<String, Tag<?, ?>> entityEntryMap = entityEntry.getValue();
ListTag posTag = (ListTag) entityEntryMap.get("pos");
CompoundTag nbtTag = (CompoundTag) entityEntryMap.get("nbt");
String id = nbtTag.getString("Id");
@ -216,7 +216,7 @@ public class MinecraftStructure implements ClipboardReader, ClipboardWriter {
if (!block.hasNbtData()) {
blocks.add(FaweCache.INSTANCE.asMap("state", index, "pos", pos));
} else {
Map<String, Tag> tag = new HashMap<>(block.getNbtData().getValue());
Map<String, Tag<?, ?>> tag = new HashMap<>(block.getNbtData().getValue());
tag.remove("x");
tag.remove("y");
tag.remove("z");
@ -246,7 +246,7 @@ public class MinecraftStructure implements ClipboardReader, ClipboardWriter {
BaseEntity state = entity.getState();
if (state != null) {
CompoundTag nbt = state.getNbtData();
Map<String, Tag> nbtMap = new HashMap<>(nbt.getValue());
Map<String, Tag<?, ?>> nbtMap = new HashMap<>(nbt.getValue());
// Replace rotation data
nbtMap.put("Rotation", writeRotation(entity.getLocation()));
nbtMap.put("id", new StringTag(state.getType().id()));

View File

@ -3,7 +3,6 @@ package com.fastasyncworldedit.core.history.change;
import com.fastasyncworldedit.core.util.MathMan;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.DoubleTag;
import com.sk89q.jnbt.LongTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.entity.BaseEntity;
@ -52,7 +51,7 @@ public class MutableEntityChange implements Change {
@SuppressWarnings({"unchecked"})
public void delete(UndoContext context) {
Map<String, Tag> map = tag.getValue();
Map<String, Tag<?, ?>> map = tag.getValue();
UUID uuid = tag.getUUID();
if (uuid == null) {
LOGGER.info("Skipping entity without uuid.");
@ -66,7 +65,7 @@ public class MutableEntityChange implements Change {
}
public void create(UndoContext context) {
Map<String, Tag> map = tag.getValue();
Map<String, Tag<?, ?>> map = tag.getValue();
Tag posTag = map.get("Pos");
if (posTag == null) {
LOGGER.warn("Missing pos tag: {}", tag);

View File

@ -112,7 +112,7 @@ public class BlockBagChangeSet extends AbstractDelegateChangeSet {
@Override
public void addTileCreate(CompoundTag nbt) {
if (nbt.containsKey("items")) {
Map<String, Tag> map = new HashMap<>(nbt.getValue());
Map<String, Tag<?, ?>> map = new HashMap<>(nbt.getValue());
map.remove("items");
}
super.addTileCreate(nbt);

View File

@ -19,7 +19,7 @@ public abstract class CompressedCompoundTag<T> extends CompoundTag {
}
@Override
public Map<String, Tag> getValue() {
public Map<String, Tag<?, ?>> getValue() {
if (in != null) {
decompress();
}
@ -36,8 +36,8 @@ public abstract class CompressedCompoundTag<T> extends CompoundTag {
try (NBTInputStream nbtIn = new NBTInputStream(adapt(in))) {
in = null;
CompoundTag tag = (CompoundTag) nbtIn.readTag();
Map<String, Tag> value = tag.getValue();
Map<String, Tag> raw = super.getValue();
Map<String, Tag<?, ?>> value = tag.getValue();
Map<String, Tag<?, ?>> raw = super.getValue();
raw.putAll(value);
} catch (IOException e) {
throw new RuntimeException(e);

View File

@ -17,7 +17,6 @@ import com.sk89q.jnbt.Tag;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Stack;
import java.util.regex.Pattern;
@ -409,7 +408,7 @@ public class JSON2NBT {
}
public Tag parse() throws NBTException {
HashMap<String, Tag> map = new HashMap<>();
HashMap<String, Tag<?, ?>> map = new HashMap<>();
for (Any JSON2NBT$any : this.tagList) {
map.put(JSON2NBT$any.json, JSON2NBT$any.parse());

View File

@ -1,11 +1,16 @@
package com.fastasyncworldedit.core.jnbt;
import com.sk89q.jnbt.Tag;
import org.enginehub.linbus.tree.LinTag;
/**
* A numerical {@link Tag}
*/
public abstract class NumberTag extends Tag {
public abstract class NumberTag<LT extends LinTag<? extends Number>> extends Tag<Number, LT> {
protected NumberTag(LT linTag) {
super(linTag);
}
@Override
public abstract Number getValue();

View File

@ -124,7 +124,7 @@ public interface IChunkExtent<T extends IChunk> extends Extent {
@Override
default Entity createEntity(Location location, BaseEntity entity, UUID uuid) {
final IChunk chunk = getOrCreateChunk(location.getBlockX() >> 4, location.getBlockZ() >> 4);
Map<String, Tag> map = new HashMap<>(entity.getNbtData().getValue()); //do not modify original entity data
Map<String, Tag<?, ?>> map = new HashMap<>(entity.getNbtData().getValue()); //do not modify original entity data
map.put("Id", new StringTag(entity.getType().getName()));
//Set pos

View File

@ -82,7 +82,7 @@ public final class BrushCache {
}
CompoundTag nbt = item.getNbtData();
Map<String, Tag> map;
Map<String, Tag<?, ?>> map;
if (nbt == null) {
if (tool == null) {
item.setNbtData(null);
@ -92,9 +92,10 @@ public final class BrushCache {
} else {
map = nbt.getValue();
}
item.setNbtData(nbt);
brushCache.remove(getKey(item));
CompoundTag display = (CompoundTag) map.get("display");
Map<String, Tag> displayMap;
Map<String, Tag<?, ?>> displayMap;
return tool;
}

View File

@ -427,7 +427,7 @@ public class MainUtil {
*/
@Nonnull
public static CompoundTag setPosition(@Nonnull CompoundTag tag, int x, int y, int z) {
Map<String, Tag> value = new HashMap<>(tag.getValue());
Map<String, Tag<?, ?>> value = new HashMap<>(tag.getValue());
value.put("x", new IntTag(x));
value.put("y", new IntTag(y));
value.put("z", new IntTag(z));
@ -443,7 +443,7 @@ public class MainUtil {
*/
@Nonnull
public static CompoundTag setEntityInfo(@Nonnull CompoundTag tag, @Nonnull Entity entity) {
Map<String, Tag> map = new HashMap<>(tag.getValue());
Map<String, Tag<?, ?>> map = new HashMap<>(tag.getValue());
map.put("Id", new StringTag(entity.getState().getType().id()));
ListTag pos = (ListTag) map.get("Pos");
if (pos != null) {

View File

@ -1,13 +1,12 @@
package com.fastasyncworldedit.core.util;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.BinaryTagType;
import com.sk89q.worldedit.util.nbt.BinaryTagTypes;
import com.sk89q.worldedit.util.nbt.ByteBinaryTag;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.IntBinaryTag;
import com.sk89q.worldedit.util.nbt.ShortBinaryTag;
import com.sk89q.worldedit.world.storage.InvalidFormatException;
import org.enginehub.linbus.tree.LinByteTag;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinIntTag;
import org.enginehub.linbus.tree.LinShortTag;
import org.enginehub.linbus.tree.LinTag;
import org.enginehub.linbus.tree.LinTagType;
import java.util.HashMap;
import java.util.Map;
@ -23,9 +22,9 @@ public class NbtUtils {
* @return child tag
* @throws InvalidFormatException if the format of the items is invalid
*/
public static <T extends BinaryTag> T getChildTag(CompoundBinaryTag tag, String key, BinaryTagType<T> expected) throws
public static <T extends LinTag> T getChildTag(LinCompoundTag tag, String key, LinTagType expected) throws
InvalidFormatException {
BinaryTag childTag = tag.get(key);
LinTag childTag = tag.value().get(key);
if (childTag == null) {
throw new InvalidFormatException("Missing a \"" + key + "\" tag");
}
@ -48,35 +47,35 @@ public class NbtUtils {
* @throws InvalidFormatException if the format of the items is invalid
* @since 2.1.0
*/
public static int getInt(CompoundBinaryTag tag, String key) throws InvalidFormatException {
BinaryTag childTag = tag.get(key);
public static int getInt(LinCompoundTag tag, String key) throws InvalidFormatException {
LinTag childTag = tag.value().get(key);
if (childTag == null) {
throw new InvalidFormatException("Missing a \"" + key + "\" tag");
}
BinaryTagType<?> type = childTag.type();
if (type == BinaryTagTypes.INT) {
return ((IntBinaryTag) childTag).intValue();
LinTagType<?> type = childTag.type();
if (type == LinTagType.intTag()) {
return ((LinIntTag) childTag).value();
}
if (type == BinaryTagTypes.BYTE) {
return ((ByteBinaryTag) childTag).intValue();
if (type == LinTagType.byteTag()) {
return ((LinByteTag) childTag).value();
}
if (type == BinaryTagTypes.SHORT) {
return ((ShortBinaryTag) childTag).intValue();
if (type == LinTagType.shortTag()) {
return ((LinShortTag) childTag).value();
}
throw new InvalidFormatException(key + " tag is not of int, short or byte tag type.");
}
/**
* Get a mutable map of the values stored inside a {@link CompoundBinaryTag}
* Get a mutable map of the values stored inside a {@link LinCompoundTag}
*
* @param tag {@link CompoundBinaryTag} to get values for
* @param tag {@link LinCompoundTag} to get values for
* @return Mutable map of values
* @since 2.1.0
*/
public static Map<String, BinaryTag> getCompoundBinaryTagValues(CompoundBinaryTag tag) {
Map<String, BinaryTag> value = new HashMap<>();
tag.forEach((e) -> value.put(e.getKey(), e.getValue()));
public static Map<String, LinTag<?>> getLinCompoundTagValues(LinCompoundTag tag) {
Map<String, LinTag<?>> value = new HashMap<>();
value.putAll(tag.value());
return value;
}

View File

@ -10,9 +10,10 @@ import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.sk89q.worldedit.blocks.BaseItem;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.nbt.TagStringIO;
import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.item.ItemTypes;
import org.enginehub.linbus.format.snbt.LinStringIO;
import org.enginehub.linbus.tree.LinCompoundTag;
import java.io.IOException;
import java.lang.reflect.Type;
@ -36,7 +37,10 @@ public final class BaseItemAdapter implements JsonDeserializer<BaseItem>, JsonSe
return new BaseItem(itemType);
}
try {
return new BaseItem(itemType, LazyReference.computed(TagStringIO.get().asCompound(nbt.getAsString())));
return new BaseItem(
itemType,
LazyReference.computed(LinCompoundTag.readFrom(LinStringIO.readFromString(nbt.getAsString())))
);
} catch (IOException e) {
throw new JsonParseException("Could not deserialize BaseItem", e);
}
@ -50,12 +54,8 @@ public final class BaseItemAdapter implements JsonDeserializer<BaseItem>, JsonSe
) {
JsonObject obj = new JsonObject();
obj.add("itemType", jsonSerializationContext.serialize(baseItem.getType()));
try {
obj.add("nbt", baseItem.getNbt() == null ? null : new JsonPrimitive(TagStringIO.get().asString(baseItem.getNbt())));
return obj;
} catch (IOException e) {
throw new JsonParseException("Could not deserialize BaseItem", e);
}
obj.add("nbt", baseItem.getNbt() == null ? null : new JsonPrimitive(LinStringIO.writeToString(baseItem.getNbt())));
return obj;
}
}

View File

@ -1,110 +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.jnbt;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.BinaryTagType;
import com.sk89q.worldedit.util.nbt.BinaryTagTypes;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
/**
* Converts between JNBT and Adventure-NBT classes.
*
* @deprecated JNBT is being removed in WE8.
*/
@Deprecated(forRemoval = true)
public class AdventureNBTConverter {
private static final BiMap<Class<? extends Tag>, BinaryTagType<?>> TAG_TYPES =
new ImmutableBiMap.Builder<Class<? extends Tag>, BinaryTagType<?>>()
.put(ByteArrayTag.class, BinaryTagTypes.BYTE_ARRAY)
.put(ByteTag.class, BinaryTagTypes.BYTE)
.put(CompoundTag.class, BinaryTagTypes.COMPOUND)
.put(DoubleTag.class, BinaryTagTypes.DOUBLE)
.put(EndTag.class, BinaryTagTypes.END)
.put(FloatTag.class, BinaryTagTypes.FLOAT)
.put(IntArrayTag.class, BinaryTagTypes.INT_ARRAY)
.put(IntTag.class, BinaryTagTypes.INT)
.put(ListTag.class, BinaryTagTypes.LIST)
.put(LongArrayTag.class, BinaryTagTypes.LONG_ARRAY)
.put(LongTag.class, BinaryTagTypes.LONG)
.put(ShortTag.class, BinaryTagTypes.SHORT)
.put(StringTag.class, BinaryTagTypes.STRING)
.build();
private static final Map<BinaryTagType<?>, Function<BinaryTag, Tag>> CONVERSION;
static {
ImmutableMap.Builder<BinaryTagType<?>, Function<BinaryTag, Tag>> conversion =
ImmutableMap.builder();
for (Map.Entry<Class<? extends Tag>, BinaryTagType<?>> tag : TAG_TYPES.entrySet()) {
Constructor<?>[] constructors = tag.getKey().getConstructors();
for (Constructor<?> c : constructors) {
if (c.getParameterCount() == 1 && BinaryTag.class.isAssignableFrom(c.getParameterTypes()[0])) {
conversion.put(tag.getValue(), binaryTag -> {
try {
return (Tag) c.newInstance(binaryTag);
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
// I assume this is always a RuntimeException since we control the ctor
throw (RuntimeException) e.getCause();
}
});
break;
}
}
}
CONVERSION = conversion.build();
}
public static BinaryTagType<?> getAdventureType(Class<? extends Tag> type) {
return Objects.requireNonNull(TAG_TYPES.get(type), () -> "Missing entry for " + type);
}
public static Class<? extends Tag> getJNBTType(BinaryTagType<?> type) {
return Objects.requireNonNull(TAG_TYPES.inverse().get(type), () -> "Missing entry for " + type);
}
private AdventureNBTConverter() {
}
public static Tag fromAdventure(BinaryTag other) {
if (other == null) {
return null;
}
Function<BinaryTag, Tag> conversion = CONVERSION.get(other.type());
if (conversion == null) {
throw new IllegalArgumentException("Can't convert other of type " + other.getClass().getCanonicalName());
}
return conversion.apply(other);
}
}

View File

@ -19,41 +19,26 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.ByteArrayBinaryTag;
import org.enginehub.linbus.tree.LinByteArrayTag;
/**
* The {@code TAG_Byte_Array} tag.
*
* @deprecated Use {@link ByteArrayBinaryTag}.
* @deprecated Use {@link LinByteArrayTag}.
*/
@Deprecated
public final class ByteArrayTag extends Tag {
private final ByteArrayBinaryTag innerTag;
public final class ByteArrayTag extends Tag<byte[], LinByteArrayTag> {
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public ByteArrayTag(byte[] value) {
super();
this.innerTag = ByteArrayBinaryTag.of(value);
this(LinByteArrayTag.of(value));
}
public ByteArrayTag(ByteArrayBinaryTag adventureTag) {
super();
this.innerTag = adventureTag;
}
@Override
public byte[] getValue() {
return innerTag.value();
}
@Override
public ByteArrayBinaryTag asBinaryTag() {
return innerTag;
public ByteArrayTag(LinByteArrayTag tag) {
super(tag);
}
//FAWE start

View File

@ -19,41 +19,32 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.ByteBinaryTag;
import com.fastasyncworldedit.core.jnbt.NumberTag;
import org.enginehub.linbus.tree.LinByteTag;
/**
* The {@code TAG_Byte} tag.
*
* @deprecated Use {@link ByteBinaryTag}.
* @deprecated Use {@link LinByteTag}.
*/
@Deprecated
public final class ByteTag extends Tag {
private final ByteBinaryTag innerTag;
public final class ByteTag extends NumberTag<LinByteTag> {
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public ByteTag(byte value) {
super();
this.innerTag = ByteBinaryTag.of(value);
this(LinByteTag.of(value));
}
public ByteTag(ByteBinaryTag adventureTag) {
super();
this.innerTag = adventureTag;
public ByteTag(LinByteTag tag) {
super(tag);
}
@Override
public Byte getValue() {
return innerTag.value();
}
@Override
public ByteBinaryTag asBinaryTag() {
return innerTag;
return linTag.value();
}
//FAWE start

View File

@ -25,10 +25,11 @@ import com.google.common.collect.Maps;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.BinaryTagLike;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.NumberBinaryTag;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinNumberTag;
import org.enginehub.linbus.tree.LinTag;
import org.enginehub.linbus.tree.LinTagType;
import java.util.Collections;
import java.util.HashMap;
@ -39,26 +40,24 @@ import java.util.UUID;
/**
* The {@code TAG_Compound} tag.
*
* @deprecated Use {@link com.sk89q.worldedit.util.nbt.CompoundBinaryTag}.
* @deprecated Use {@link LinCompoundTag}.
*/
@Deprecated
public class CompoundTag extends Tag {
private final CompoundBinaryTag innerTag;
//FAWE start - nonfinal
public class CompoundTag extends Tag<Object, LinCompoundTag> {
//FAWE end
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public CompoundTag(Map<String, Tag> value) {
this(CompoundBinaryTag.builder()
.put(Maps.transformValues(value, BinaryTagLike::asBinaryTag))
.build());
public CompoundTag(Map<String, Tag<?, ?>> value) {
this(LinCompoundTag.of(Maps.transformValues(value, Tag::toLinTag)));
}
public CompoundTag(CompoundBinaryTag adventureTag) {
this.innerTag = adventureTag;
public CompoundTag(LinCompoundTag tag) {
super(tag);
}
/**
@ -68,16 +67,16 @@ public class CompoundTag extends Tag {
* @return true if the tag contains the given key
*/
public boolean containsKey(String key) {
return innerTag.keySet().contains(key);
return linTag.value().containsKey(key);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Map<String, Tag> getValue() {
ImmutableMap.Builder<String, Tag> map = ImmutableMap.builder();
for (String key : innerTag.keySet()) {
map.put(key, AdventureNBTConverter.fromAdventure(innerTag.get(key)));
}
return map.build();
public Map<String, Tag<?, ?>> getValue() {
return ImmutableMap.copyOf(Maps.transformValues(
linTag.value(),
tag -> (Tag<?, ?>) LinBusConverter.toJnbtTag((LinTag) tag)
));
}
/**
@ -86,7 +85,7 @@ public class CompoundTag extends Tag {
* @param value the value
* @return the new compound tag
*/
public CompoundTag setValue(Map<String, Tag> value) {
public CompoundTag setValue(Map<String, Tag<?, ?>> value) {
return new CompoundTag(value);
}
@ -96,7 +95,7 @@ public class CompoundTag extends Tag {
* @return the builder
*/
public CompoundTagBuilder createBuilder() {
return new CompoundTagBuilder(innerTag);
return new CompoundTagBuilder(linTag);
}
/**
@ -109,7 +108,8 @@ public class CompoundTag extends Tag {
* @return a byte array
*/
public byte[] getByteArray(String key) {
return this.innerTag.getByteArray(key);
var tag = linTag.findTag(key, LinTagType.byteArrayTag());
return tag == null ? new byte[0] : tag.value();
}
/**
@ -122,7 +122,8 @@ public class CompoundTag extends Tag {
* @return a byte
*/
public byte getByte(String key) {
return this.innerTag.getByte(key);
var tag = linTag.findTag(key, LinTagType.byteTag());
return tag == null ? 0 : tag.value();
}
/**
@ -135,7 +136,8 @@ public class CompoundTag extends Tag {
* @return a double
*/
public double getDouble(String key) {
return this.innerTag.getDouble(key);
var tag = linTag.findTag(key, LinTagType.doubleTag());
return tag == null ? 0 : tag.value();
}
/**
@ -149,9 +151,10 @@ public class CompoundTag extends Tag {
* @return a double
*/
public double asDouble(String key) {
BinaryTag tag = this.innerTag.get(key);
if (tag instanceof NumberBinaryTag) {
return ((NumberBinaryTag) tag).doubleValue();
var tag = linTag.value().get(key);
if (tag instanceof LinNumberTag<?> numberTag) {
Number value = numberTag.value();
return value.doubleValue();
}
return 0;
}
@ -166,7 +169,8 @@ public class CompoundTag extends Tag {
* @return a float
*/
public float getFloat(String key) {
return this.innerTag.getFloat(key);
var tag = linTag.findTag(key, LinTagType.floatTag());
return tag == null ? 0 : tag.value();
}
/**
@ -179,7 +183,8 @@ public class CompoundTag extends Tag {
* @return an int array
*/
public int[] getIntArray(String key) {
return this.innerTag.getIntArray(key);
var tag = linTag.findTag(key, LinTagType.intArrayTag());
return tag == null ? new int[0] : tag.value();
}
/**
@ -192,7 +197,8 @@ public class CompoundTag extends Tag {
* @return an int
*/
public int getInt(String key) {
return this.innerTag.getInt(key);
var tag = linTag.findTag(key, LinTagType.intTag());
return tag == null ? 0 : tag.value();
}
/**
@ -206,9 +212,10 @@ public class CompoundTag extends Tag {
* @return an int
*/
public int asInt(String key) {
BinaryTag tag = this.innerTag.get(key);
if (tag instanceof NumberBinaryTag) {
return ((NumberBinaryTag) tag).intValue();
var tag = linTag.value().get(key);
if (tag instanceof LinNumberTag<?> numberTag) {
Number value = numberTag.value();
return value.intValue();
}
return 0;
}
@ -222,7 +229,7 @@ public class CompoundTag extends Tag {
* @param key the key
* @return a list of tags
*/
public List<Tag> getList(String key) {
public List<? extends Tag<?, ?>> getList(String key) {
return getListTag(key).getValue();
}
@ -235,8 +242,15 @@ public class CompoundTag extends Tag {
* @param key the key
* @return a tag list instance
*/
public ListTag getListTag(String key) {
return new ListTag(this.innerTag.getList(key));
public <EV, E extends LinTag<EV>> ListTag<EV, E> getListTag(String key) {
LinListTag<E> tag = linTag.findTag(key, LinTagType.listTag());
if (tag == null) {
// This is actually hella unsafe. But eh.
@SuppressWarnings("unchecked")
LinTagType<E> endGenerically = (LinTagType<E>) LinTagType.endTag();
return new ListTag<>(LinListTag.empty(endGenerically));
}
return new ListTag<>(tag);
}
/**
@ -253,8 +267,8 @@ public class CompoundTag extends Tag {
* @return a list of tags
*/
@SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(String key, Class<T> listType) {
ListTag listTag = getListTag(key);
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 {
@ -272,7 +286,8 @@ public class CompoundTag extends Tag {
* @return an int array
*/
public long[] getLongArray(String key) {
return this.innerTag.getLongArray(key);
var tag = linTag.findTag(key, LinTagType.longArrayTag());
return tag == null ? new long[0] : tag.value();
}
/**
@ -285,7 +300,8 @@ public class CompoundTag extends Tag {
* @return a long
*/
public long getLong(String key) {
return this.innerTag.getLong(key);
var tag = linTag.findTag(key, LinTagType.longTag());
return tag == null ? 0 : tag.value();
}
/**
@ -299,9 +315,10 @@ public class CompoundTag extends Tag {
* @return a long
*/
public long asLong(String key) {
BinaryTag tag = this.innerTag.get(key);
if (tag instanceof NumberBinaryTag) {
return ((NumberBinaryTag) tag).longValue();
var tag = linTag.value().get(key);
if (tag instanceof LinNumberTag<?> numberTag) {
Number value = numberTag.value();
return value.longValue();
}
return 0;
}
@ -316,7 +333,8 @@ public class CompoundTag extends Tag {
* @return a short
*/
public short getShort(String key) {
return this.innerTag.getShort(key);
var tag = linTag.findTag(key, LinTagType.shortTag());
return tag == null ? 0 : tag.value();
}
/**
@ -329,12 +347,8 @@ public class CompoundTag extends Tag {
* @return a string
*/
public String getString(String key) {
return this.innerTag.getString(key);
}
@Override
public CompoundBinaryTag asBinaryTag() {
return this.innerTag;
var tag = linTag.findTag(key, LinTagType.stringTag());
return tag == null ? "" : tag.value();
}
@ -357,7 +371,7 @@ public class CompoundTag extends Tag {
}
public Vector3 getEntityPosition() {
List<Tag> posTags = getList("Pos");
List<? extends Tag<?, ?>> posTags = getList("Pos");
double x = ((NumberTag) posTags.get(0)).getValue().doubleValue();
double y = ((NumberTag) posTags.get(1)).getValue().doubleValue();
double z = ((NumberTag) posTags.get(2)).getValue().doubleValue();
@ -365,7 +379,7 @@ public class CompoundTag extends Tag {
}
public Location getEntityLocation(Extent extent) {
List<Tag> rotTag = getList("Rotation");
List<? extends Tag<?, ?>> rotTag = getList("Rotation");
float yaw = ((NumberTag) rotTag.get(0)).getValue().floatValue();
float pitch = ((NumberTag) rotTag.get(1)).getValue().floatValue();
return new Location(extent, getEntityPosition(), yaw, pitch);
@ -382,7 +396,7 @@ public class CompoundTag extends Tag {
if (this.getValue().isEmpty()) {
return raw;
}
for (Map.Entry<String, Tag> entry : getValue().entrySet()) {
for (Map.Entry<String, Tag<?, ?>> entry : getValue().entrySet()) {
raw.put(entry.getKey(), entry.getValue().toRaw());
}
return raw;

View File

@ -19,27 +19,27 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import org.enginehub.linbus.tree.LinCompoundTag;
import java.util.Map;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Helps create compound tags.
*
* @deprecated Use {@link com.sk89q.worldedit.util.nbt.CompoundBinaryTag.Builder}.
* @deprecated Use {@link LinCompoundTag.Builder}.
*/
@Deprecated
public class CompoundTagBuilder {
private final CompoundBinaryTag.Builder builder = CompoundBinaryTag.builder();
private final LinCompoundTag.Builder builder;
/**
* Create a new instance.
*/
CompoundTagBuilder() {
this.builder = LinCompoundTag.builder();
}
/**
@ -47,11 +47,9 @@ public class CompoundTagBuilder {
*
* @param source the value
*/
CompoundTagBuilder(CompoundBinaryTag source) {
CompoundTagBuilder(LinCompoundTag source) {
checkNotNull(source);
for (String key : source.keySet()) {
this.builder.put(key, Objects.requireNonNull(source.get(key)));
}
this.builder = source.toBuilder();
}
/**
@ -61,10 +59,10 @@ public class CompoundTagBuilder {
* @param value the value
* @return this object
*/
public CompoundTagBuilder put(String key, Tag value) {
public CompoundTagBuilder put(String key, Tag<?, ?> value) {
checkNotNull(key);
checkNotNull(value);
this.builder.put(key, value.asBinaryTag());
this.builder.put(key, value.toLinTag());
return this;
}
@ -215,9 +213,9 @@ public class CompoundTagBuilder {
* @param value the map of tags
* @return this object
*/
public CompoundTagBuilder putAll(Map<String, ? extends Tag> value) {
public CompoundTagBuilder putAll(Map<String, ? extends Tag<?, ?>> value) {
checkNotNull(value);
for (Map.Entry<String, ? extends Tag> entry : value.entrySet()) {
for (Map.Entry<String, ? extends Tag<?, ?>> entry : value.entrySet()) {
put(entry.getKey(), entry.getValue());
}
return this;

View File

@ -20,17 +20,15 @@
package com.sk89q.jnbt;
import com.fastasyncworldedit.core.jnbt.NumberTag;
import com.sk89q.worldedit.util.nbt.DoubleBinaryTag;
import org.enginehub.linbus.tree.LinDoubleTag;
/**
* The {@code TAG_Double} tag.
*
* @deprecated Use {@link DoubleBinaryTag}.
* @deprecated Use {@link LinDoubleTag}.
*/
@Deprecated
public final class DoubleTag extends NumberTag {
private final DoubleBinaryTag innerTag;
public final class DoubleTag extends NumberTag<LinDoubleTag> {
/**
* Creates the tag with an empty name.
@ -38,23 +36,16 @@ public final class DoubleTag extends NumberTag {
* @param value the value of the tag
*/
public DoubleTag(double value) {
super();
this.innerTag = DoubleBinaryTag.of(value);
this(LinDoubleTag.of(value));
}
public DoubleTag(DoubleBinaryTag adventureTag) {
super();
this.innerTag = adventureTag;
}
@Override
public DoubleBinaryTag asBinaryTag() {
return this.innerTag;
public DoubleTag(LinDoubleTag tag) {
super(tag);
}
@Override
public Double getValue() {
return innerTag.value();
return linTag.value();
}
//FAWE start

View File

@ -19,24 +19,17 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.EndBinaryTag;
import org.enginehub.linbus.tree.LinEndTag;
/**
* The {@code TAG_End} tag.
*
* @deprecated Use {@link com.sk89q.worldedit.util.nbt.EndBinaryTag}.
* @deprecated Use {@link LinEndTag}.
*/
@Deprecated
public final class EndTag extends Tag {
@Override
public Object getValue() {
return null;
}
@Override
public EndBinaryTag asBinaryTag() {
return EndBinaryTag.get();
public final class EndTag extends Tag<Object, LinEndTag> {
public EndTag() {
super(LinEndTag.instance());
}
//FAWE start

View File

@ -20,17 +20,14 @@
package com.sk89q.jnbt;
import com.fastasyncworldedit.core.jnbt.NumberTag;
import com.sk89q.worldedit.util.nbt.FloatBinaryTag;
import org.enginehub.linbus.tree.LinFloatTag;
/**
* The {@code TAG_Float} tag.
*
* @deprecated Use {@link FloatBinaryTag}.
* @deprecated Use {@link LinFloatTag}.
*/
@Deprecated
public final class FloatTag extends NumberTag {
private final FloatBinaryTag innerTag;
public final class FloatTag extends NumberTag<LinFloatTag> {
/**
* Creates the tag with an empty name.
@ -38,23 +35,16 @@ public final class FloatTag extends NumberTag {
* @param value the value of the tag
*/
public FloatTag(float value) {
super();
this.innerTag = FloatBinaryTag.of(value);
this(LinFloatTag.of(value));
}
public FloatTag(FloatBinaryTag adventureTag) {
super();
this.innerTag = adventureTag;
}
@Override
public FloatBinaryTag asBinaryTag() {
return this.innerTag;
public FloatTag(LinFloatTag tag) {
super(tag);
}
@Override
public Float getValue() {
return innerTag.value();
return linTag.value();
}
//FAWE start

View File

@ -19,44 +19,33 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.IntArrayBinaryTag;
import org.enginehub.linbus.tree.LinIntArrayTag;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_Int_Array} tag.
*
* @deprecated Use {@link IntArrayBinaryTag}.
* @deprecated Use {@link LinIntArrayTag}.
*/
@Deprecated
public final class IntArrayTag extends Tag {
private final IntArrayBinaryTag innerTag;
public final class IntArrayTag extends Tag<int[], LinIntArrayTag> {
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public IntArrayTag(int[] value) {
super();
checkNotNull(value);
this.innerTag = IntArrayBinaryTag.of(value);
this(LinIntArrayTag.of(checkNotNull(value)));
}
public IntArrayTag(IntArrayBinaryTag adventureTag) {
super();
this.innerTag = adventureTag;
}
@Override
public IntArrayBinaryTag asBinaryTag() {
return this.innerTag;
public IntArrayTag(LinIntArrayTag tag) {
super(tag);
}
@Override
public int[] getValue() {
return innerTag.value();
return linTag.value();
}
//FAWE start

View File

@ -19,17 +19,16 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.IntBinaryTag;
import com.fastasyncworldedit.core.jnbt.NumberTag;
import org.enginehub.linbus.tree.LinIntTag;
/**
* The {@code TAG_Int} tag.
*
* @deprecated Use {@link IntBinaryTag}.
* @deprecated Use {@link LinIntTag}.
*/
@Deprecated
public final class IntTag extends Tag {
private final IntBinaryTag innerTag;
public final class IntTag extends NumberTag<LinIntTag> {
/**
* Creates the tag with an empty name.
@ -37,23 +36,16 @@ public final class IntTag extends Tag {
* @param value the value of the tag
*/
public IntTag(int value) {
super();
this.innerTag = IntBinaryTag.of(value);
this(LinIntTag.of(value));
}
public IntTag(IntBinaryTag adventureTag) {
super();
this.innerTag = adventureTag;
}
@Override
public IntBinaryTag asBinaryTag() {
return this.innerTag;
public IntTag(LinIntTag tag) {
super(tag);
}
@Override
public Integer getValue() {
return innerTag.value();
return linTag.value();
}
//FAWE start

View File

@ -20,27 +20,27 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import org.enginehub.linbus.tree.LinCompoundTag;
import java.util.Map;
/**
* Allows detection of the version-specific LazyCompoundTag classes.
*
* @deprecated Use {@link CompoundBinaryTag}.
* @deprecated Use {@link LinCompoundTag}.
*/
@Deprecated
public abstract class LazyCompoundTag extends CompoundTag {
public LazyCompoundTag(Map<String, Tag> value) {
public LazyCompoundTag(Map<String, Tag<?, ?>> value) {
super(value);
}
public LazyCompoundTag(CompoundBinaryTag adventureTag) {
public LazyCompoundTag(LinCompoundTag adventureTag) {
super(adventureTag);
}
@Override
public abstract CompoundBinaryTag asBinaryTag();
public abstract LinCompoundTag toLinTag();
}

View File

@ -0,0 +1,140 @@
/*
* 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.jnbt;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
import org.enginehub.linbus.tree.LinByteArrayTag;
import org.enginehub.linbus.tree.LinByteTag;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinDoubleTag;
import org.enginehub.linbus.tree.LinFloatTag;
import org.enginehub.linbus.tree.LinIntArrayTag;
import org.enginehub.linbus.tree.LinIntTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinLongArrayTag;
import org.enginehub.linbus.tree.LinLongTag;
import org.enginehub.linbus.tree.LinShortTag;
import org.enginehub.linbus.tree.LinStringTag;
import org.enginehub.linbus.tree.LinTag;
import org.enginehub.linbus.tree.LinTagType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
/**
* Converts between JNBT and Adventure-NBT classes.
*
* @deprecated JNBT is being removed in WE8.
*/
@Deprecated(forRemoval = true)
public class LinBusConverter {
private static final BiMap<Class<? extends Tag>, LinTagType<?>> TAG_TYPES =
new ImmutableBiMap.Builder<Class<? extends Tag>, LinTagType<?>>()
.put(ByteArrayTag.class, LinTagType.byteArrayTag())
.put(ByteTag.class, LinTagType.byteTag())
.put(CompoundTag.class, LinTagType.compoundTag())
.put(DoubleTag.class, LinTagType.doubleTag())
.put(EndTag.class, LinTagType.endTag())
.put(FloatTag.class, LinTagType.floatTag())
.put(IntArrayTag.class, LinTagType.intArrayTag())
.put(IntTag.class, LinTagType.intTag())
.put(ListTag.class, LinTagType.listTag())
.put(LongArrayTag.class, LinTagType.longArrayTag())
.put(LongTag.class, LinTagType.longTag())
.put(ShortTag.class, LinTagType.shortTag())
.put(StringTag.class, LinTagType.stringTag())
.build();
private static final Map<LinTagType<?>, Function<LinTag, Tag>> CONVERSION;
static {
ImmutableMap.Builder<LinTagType<?>, Function<LinTag, Tag>> conversion =
ImmutableMap.builder();
for (Map.Entry<Class<? extends Tag>, LinTagType<?>> tag : TAG_TYPES.entrySet()) {
Constructor<?>[] constructors = tag.getKey().getConstructors();
for (Constructor<?> c : constructors) {
if (c.getParameterCount() == 1 && LinTag.class.isAssignableFrom(c.getParameterTypes()[0])) {
conversion.put(tag.getValue(), linTag -> {
try {
return (Tag) c.newInstance(linTag);
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
// I assume this is always a RuntimeException since we control the ctor
throw (RuntimeException) e.getCause();
}
});
break;
}
}
}
CONVERSION = conversion.build();
}
public static LinTagType<?> getAdventureType(Class<? extends Tag> type) {
return Objects.requireNonNull(TAG_TYPES.get(type), () -> "Missing entry for " + type);
}
public static Class<? extends Tag> getJNBTType(LinTagType<?> type) {
return Objects.requireNonNull(TAG_TYPES.inverse().get(type), () -> "Missing entry for " + type);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <V, LT extends LinTag<? extends V>> Tag<V, LT> toJnbtTag(LT tag) {
return (Tag<V, LT>) switch (tag.type().id()) {
case BYTE_ARRAY -> new ByteArrayTag((LinByteArrayTag) tag);
case BYTE -> new ByteTag((LinByteTag) tag);
case COMPOUND -> new CompoundTag((LinCompoundTag) tag);
case DOUBLE -> new DoubleTag((LinDoubleTag) tag);
case END -> new EndTag();
case FLOAT -> new FloatTag((LinFloatTag) tag);
case INT_ARRAY -> new IntArrayTag((LinIntArrayTag) tag);
case INT -> new IntTag((LinIntTag) tag);
case LIST -> new ListTag((LinListTag<?>) tag);
case LONG_ARRAY -> new LongArrayTag((LinLongArrayTag) tag);
case LONG -> new LongTag((LinLongTag) tag);
case SHORT -> new ShortTag((LinShortTag) tag);
case STRING -> new StringTag((LinStringTag) tag);
};
}
private LinBusConverter() {
}
public static Tag fromLinBus(LinTag other) {
if (other == null) {
return null;
}
Function<LinTag, Tag> conversion = CONVERSION.get(other.type());
if (conversion == null) {
throw new IllegalArgumentException("Can't convert other of type " + other.getClass().getCanonicalName());
}
return conversion.apply(other);
}
}

View File

@ -19,10 +19,20 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.BinaryTagLike;
import com.sk89q.worldedit.util.nbt.ListBinaryTag;
import com.sk89q.worldedit.util.nbt.NumberBinaryTag;
import org.enginehub.linbus.common.LinTagId;
import org.enginehub.linbus.tree.LinByteArrayTag;
import org.enginehub.linbus.tree.LinByteTag;
import org.enginehub.linbus.tree.LinDoubleTag;
import org.enginehub.linbus.tree.LinFloatTag;
import org.enginehub.linbus.tree.LinIntArrayTag;
import org.enginehub.linbus.tree.LinIntTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinLongTag;
import org.enginehub.linbus.tree.LinNumberTag;
import org.enginehub.linbus.tree.LinShortTag;
import org.enginehub.linbus.tree.LinStringTag;
import org.enginehub.linbus.tree.LinTag;
import org.enginehub.linbus.tree.LinTagType;
import javax.annotation.Nullable;
import java.util.Collections;
@ -34,12 +44,10 @@ import java.util.stream.Collectors;
/**
* The {@code TAG_List} tag.
*
* @deprecated Use {@link com.sk89q.worldedit.util.nbt.ListBinaryTag}.
* @deprecated Use {@link LinListTag}.
*/
@Deprecated
public final class ListTag extends Tag {
private final ListBinaryTag innerTag;
public final class ListTag<EV, E extends LinTag<EV>> extends Tag<Object, LinListTag<E>> {
/**
* Creates the tag with an empty name.
@ -47,20 +55,15 @@ public final class ListTag extends Tag {
* @param type the type of tag
* @param value the value of the tag
*/
public ListTag(Class<? extends Tag> type, List<? extends Tag> value) {
this(ListBinaryTag.of(
AdventureNBTConverter.getAdventureType(type),
value.stream().map(BinaryTagLike::asBinaryTag).collect(Collectors.toList())
public ListTag(Class<? extends Tag<EV, E>> type, List<? extends Tag<EV, E>> value) {
this(LinListTag.of(
LinTagType.fromId(LinTagId.fromId(NBTUtils.getTypeCode(type))),
value.stream().map(Tag::toLinTag).collect(Collectors.toList())
));
}
public ListTag(ListBinaryTag adventureTag) {
this.innerTag = adventureTag;
}
@Override
public ListBinaryTag asBinaryTag() {
return this.innerTag;
public ListTag(LinListTag<E> tag) {
super(tag);
}
/**
@ -68,15 +71,14 @@ public final class ListTag extends Tag {
*
* @return The type of item in this list.
*/
public Class<? extends Tag> getType() {
return AdventureNBTConverter.getJNBTType(this.innerTag.elementType());
@SuppressWarnings("unchecked")
public Class<? extends Tag<EV, E>> getType() {
return (Class<? extends Tag<EV, E>>) NBTUtils.getTypeClass(linTag.elementType().id().id());
}
@Override
public List<Tag> getValue() {
return this.innerTag.stream()
.map(AdventureNBTConverter::fromAdventure)
.collect(Collectors.toList());
public List<? extends Tag<EV, E>> getValue() {
return linTag.value().stream().map(LinBusConverter::toJnbtTag).toList();
}
/**
@ -85,17 +87,31 @@ public final class ListTag extends Tag {
* @param list the new list
* @return a new list tag
*/
public ListTag setValue(List<Tag> list) {
return new ListTag(getType(), list);
public ListTag<EV, E> setValue(List<? extends Tag<EV, E>> list) {
return new ListTag<>(getType(), list);
}
private <T> T accessIfExists(int index, Supplier<T> defaultValue, IntFunction<T> accessor) {
if (index >= this.innerTag.size()) {
if (index >= this.linTag.value().size()) {
return defaultValue.get();
}
return accessor.apply(index);
}
@SuppressWarnings("unchecked")
private <T, LT extends LinTag<T>> T extractViaValue(
int index, Class<LT> requiredType, Supplier<T> defaultValue
) {
if (index >= this.linTag.value().size()) {
return defaultValue.get();
}
E value = this.linTag.get(index);
if (!requiredType.isInstance(value)) {
return defaultValue.get();
}
return (T) value.value();
}
/**
* Get the tag if it exists at the given index.
*
@ -103,11 +119,11 @@ public final class ListTag extends Tag {
* @return the tag or null
*/
@Nullable
public Tag getIfExists(int index) {
public Tag<EV, E> getIfExists(int index) {
return accessIfExists(
index,
() -> null,
i -> AdventureNBTConverter.fromAdventure(this.innerTag.get(i))
index,
() -> null,
i -> LinBusConverter.toJnbtTag(this.linTag.get(i))
);
}
@ -121,11 +137,7 @@ public final class ListTag extends Tag {
* @return a byte array
*/
public byte[] getByteArray(int index) {
return accessIfExists(
index,
() -> new byte[0],
this.innerTag::getByteArray
);
return extractViaValue(index, LinByteArrayTag.class, () -> new byte[0]);
}
/**
@ -138,11 +150,7 @@ public final class ListTag extends Tag {
* @return a byte
*/
public byte getByte(int index) {
return accessIfExists(
index,
() -> (byte) 0,
this.innerTag::getByte
);
return extractViaValue(index, LinByteTag.class, () -> (byte) 0);
}
/**
@ -155,11 +163,7 @@ public final class ListTag extends Tag {
* @return a double
*/
public double getDouble(int index) {
return accessIfExists(
index,
() -> 0.0,
this.innerTag::getDouble
);
return extractViaValue(index, LinDoubleTag.class, () -> 0.0);
}
/**
@ -174,15 +178,11 @@ public final class ListTag extends Tag {
*/
public double asDouble(int index) {
return accessIfExists(
index,
() -> 0.0,
i -> {
BinaryTag tag = this.innerTag.get(i);
if (tag instanceof NumberBinaryTag) {
return ((NumberBinaryTag) tag).doubleValue();
}
return 0.0;
}
index,
() -> 0.0,
i -> this.linTag.get(i) instanceof LinNumberTag<?> tag
? tag.value().doubleValue()
: 0.0
);
}
@ -196,11 +196,7 @@ public final class ListTag extends Tag {
* @return a float
*/
public float getFloat(int index) {
return accessIfExists(
index,
() -> 0.0f,
this.innerTag::getFloat
);
return extractViaValue(index, LinFloatTag.class, () -> 0f);
}
/**
@ -213,11 +209,7 @@ public final class ListTag extends Tag {
* @return an int array
*/
public int[] getIntArray(int index) {
return accessIfExists(
index,
() -> new int[0],
this.innerTag::getIntArray
);
return extractViaValue(index, LinIntArrayTag.class, () -> new int[0]);
}
/**
@ -230,11 +222,7 @@ public final class ListTag extends Tag {
* @return an int
*/
public int getInt(int index) {
return accessIfExists(
index,
() -> 0,
this.innerTag::getInt
);
return extractViaValue(index, LinIntTag.class, () -> 0);
}
/**
@ -249,15 +237,11 @@ public final class ListTag extends Tag {
*/
public int asInt(int index) {
return accessIfExists(
index,
() -> 0,
i -> {
BinaryTag tag = this.innerTag.get(i);
if (tag instanceof NumberBinaryTag) {
return ((NumberBinaryTag) tag).intValue();
}
return 0;
}
index,
() -> 0,
i -> this.linTag.get(i) instanceof LinNumberTag<?> tag
? tag.value().intValue()
: 0
);
}
@ -270,7 +254,7 @@ public final class ListTag extends Tag {
* @param index the index
* @return a list of tags
*/
public List<Tag> getList(int index) {
public List<? extends Tag<?, ?>> getList(int index) {
return getListTag(index).getValue();
}
@ -283,11 +267,12 @@ public final class ListTag extends Tag {
* @param index the index
* @return a tag list instance
*/
public ListTag getListTag(int index) {
return new ListTag(accessIfExists(
index,
ListBinaryTag::empty,
this.innerTag::getList
@SuppressWarnings("unchecked")
public ListTag<?, ?> getListTag(int index) {
return new ListTag<>(extractViaValue(
index,
LinListTag.class,
() -> LinListTag.empty(LinTagType.endTag())
));
}
@ -305,8 +290,8 @@ public final class ListTag extends Tag {
* @return a list of tags
*/
@SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(int index, Class<T> listType) {
ListTag listTag = getListTag(index);
public <T extends Tag<?, ?>> List<T> getList(int index, Class<T> listType) {
ListTag<?, ?> listTag = getListTag(index);
if (listTag.getType().equals(listType)) {
return (List<T>) listTag.getValue();
} else {
@ -324,11 +309,7 @@ public final class ListTag extends Tag {
* @return a long
*/
public long getLong(int index) {
return accessIfExists(
index,
() -> 0L,
this.innerTag::getLong
);
return extractViaValue(index, LinLongTag.class, () -> 0L);
}
/**
@ -343,15 +324,11 @@ public final class ListTag extends Tag {
*/
public long asLong(int index) {
return accessIfExists(
index,
() -> 0L,
i -> {
BinaryTag tag = this.innerTag.get(i);
if (tag instanceof NumberBinaryTag) {
return ((NumberBinaryTag) tag).longValue();
}
return 0L;
}
index,
() -> 0L,
i -> this.linTag.get(i) instanceof LinNumberTag<?> tag
? tag.value().longValue()
: 0L
);
}
@ -365,11 +342,7 @@ public final class ListTag extends Tag {
* @return a short
*/
public short getShort(int index) {
return accessIfExists(
index,
() -> (short) 0,
this.innerTag::getShort
);
return extractViaValue(index, LinShortTag.class, () -> (short) 0);
}
/**
@ -382,11 +355,7 @@ public final class ListTag extends Tag {
* @return a string
*/
public String getString(int index) {
return accessIfExists(
index,
() -> "",
this.innerTag::getString
);
return extractViaValue(index, LinStringTag.class, () -> "");
}
//FAWE start

View File

@ -19,11 +19,11 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.BinaryTagType;
import com.sk89q.worldedit.util.nbt.ListBinaryTag;
import org.enginehub.linbus.common.LinTagId;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinTag;
import org.enginehub.linbus.tree.LinTagType;
import java.util.Arrays;
import java.util.Collection;
import static com.google.common.base.Preconditions.checkNotNull;
@ -31,12 +31,12 @@ import static com.google.common.base.Preconditions.checkNotNull;
/**
* Helps create list tags.
*
* @deprecated Use {@link com.sk89q.worldedit.util.nbt.ListBinaryTag.Builder}.
* @deprecated Use {@link LinListTag.Builder}.
*/
@Deprecated
public class ListTagBuilder {
public class ListTagBuilder<V, LT extends LinTag<V>> {
private final ListBinaryTag.Builder<BinaryTag> builder;
private final LinListTag.Builder<LT> builder;
/**
* Create a new instance.
@ -44,11 +44,11 @@ public class ListTagBuilder {
* @param type of tag contained in this list
*/
@SuppressWarnings("unchecked")
ListTagBuilder(Class<? extends Tag> type) {
ListTagBuilder(Class<? extends Tag<V, LT>> type) {
checkNotNull(type);
this.builder = type != EndTag.class
? ListBinaryTag.builder((BinaryTagType<BinaryTag>) AdventureNBTConverter.getAdventureType(type))
: ListBinaryTag.builder();
this.builder = (LinListTag.Builder<LT>) LinListTag.builder(LinTagType.fromId(LinTagId.fromId(
NBTUtils.getTypeCode(type)
)));
}
/**
@ -57,9 +57,9 @@ public class ListTagBuilder {
* @param value the tag
* @return this object
*/
public ListTagBuilder add(Tag value) {
public ListTagBuilder<V, LT> add(Tag<V, LT> value) {
checkNotNull(value);
builder.add(value.asBinaryTag());
builder.add(value.toLinTag());
return this;
}
@ -69,9 +69,9 @@ public class ListTagBuilder {
* @param value a list of tags
* @return this object
*/
public ListTagBuilder addAll(Collection<? extends Tag> value) {
public ListTagBuilder<V, LT> addAll(Collection<? extends Tag<V, LT>> value) {
checkNotNull(value);
for (Tag v : value) {
for (Tag<V, LT> v : value) {
add(v);
}
return this;
@ -82,8 +82,8 @@ public class ListTagBuilder {
*
* @return the new list tag
*/
public ListTag build() {
return new ListTag(this.builder.build());
public ListTag<V, LT> build() {
return new ListTag<>(this.builder.build());
}
/**
@ -91,8 +91,8 @@ public class ListTagBuilder {
*
* @return a new builder
*/
public static ListTagBuilder create(Class<? extends Tag> type) {
return new ListTagBuilder(type);
public static <V, LT extends LinTag<V>> ListTagBuilder<V, LT> create(Class<? extends Tag<V, LT>> type) {
return new ListTagBuilder<>(type);
}
/**
@ -100,22 +100,24 @@ public class ListTagBuilder {
*
* @return a new builder
*/
public static ListTagBuilder createWith(Tag... entries) {
@SafeVarargs
public static <V, LT extends LinTag<V>> ListTagBuilder<V, LT> createWith(Tag<V, LT>... entries) {
checkNotNull(entries);
if (entries.length == 0) {
throw new IllegalArgumentException("This method needs an array of at least one entry");
}
Class<? extends Tag> type = entries[0].getClass();
for (int i = 1; i < entries.length; i++) {
if (!type.isInstance(entries[i])) {
@SuppressWarnings("unchecked")
Class<? extends Tag<V, LT>> type = (Class<? extends Tag<V, LT>>) entries[0].getClass();
ListTagBuilder<V, LT> builder = new ListTagBuilder<>(type);
for (Tag<V, LT> entry : entries) {
if (!type.isInstance(entry)) {
throw new IllegalArgumentException("An array of different tag types was provided");
}
builder.add(entry);
}
ListTagBuilder builder = new ListTagBuilder(type);
builder.addAll(Arrays.asList(entries));
return builder;
}

View File

@ -19,44 +19,33 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.LongArrayBinaryTag;
import org.enginehub.linbus.tree.LinLongArrayTag;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_Long_Array} tag.
*
* @deprecated Use {@link LongArrayBinaryTag}.
* @deprecated Use {@link LinLongArrayTag}.
*/
@Deprecated
public class LongArrayTag extends Tag {
private final LongArrayBinaryTag innerTag;
public class LongArrayTag extends Tag<long[], LinLongArrayTag> {
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public LongArrayTag(long[] value) {
super();
checkNotNull(value);
this.innerTag = LongArrayBinaryTag.of(value);
this(LinLongArrayTag.of(checkNotNull(value)));
}
public LongArrayTag(LongArrayBinaryTag adventureTag) {
super();
this.innerTag = adventureTag;
}
@Override
public LongArrayBinaryTag asBinaryTag() {
return this.innerTag;
public LongArrayTag(LinLongArrayTag tag) {
super(tag);
}
@Override
public long[] getValue() {
return innerTag.value();
return linTag.value();
}
//FAWE start

View File

@ -19,41 +19,32 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.LongBinaryTag;
import com.fastasyncworldedit.core.jnbt.NumberTag;
import org.enginehub.linbus.tree.LinLongTag;
/**
* The {@code TAG_Long} tag.
*
* @deprecated Use {@link LongBinaryTag}.
* @deprecated Use {@link LinLongTag}.
*/
@Deprecated
public final class LongTag extends Tag {
private final LongBinaryTag innerTag;
public final class LongTag extends NumberTag<LinLongTag> {
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public LongTag(long value) {
super();
this.innerTag = LongBinaryTag.of(value);
this(LinLongTag.of(value));
}
public LongTag(LongBinaryTag adventureTag) {
super();
this.innerTag = adventureTag;
}
@Override
public LongBinaryTag asBinaryTag() {
return this.innerTag;
public LongTag(LinLongTag tag) {
super(tag);
}
@Override
public Long getValue() {
return innerTag.value();
return linTag.value();
}
//FAWE start

View File

@ -50,7 +50,6 @@ public final class NBTConstants {
* Default private constructor.
*/
private NBTConstants() {
}
/**
@ -60,37 +59,27 @@ public final class NBTConstants {
* @return tag class
* @throws IllegalArgumentException thrown if the tag ID is not valid
*/
public static Class<? extends Tag> getClassFromType(int id) {
switch (id) {
case TYPE_END:
return EndTag.class;
case TYPE_BYTE:
return ByteTag.class;
case TYPE_SHORT:
return ShortTag.class;
case TYPE_INT:
return IntTag.class;
case TYPE_LONG:
return LongTag.class;
case TYPE_FLOAT:
return FloatTag.class;
case TYPE_DOUBLE:
return DoubleTag.class;
case TYPE_BYTE_ARRAY:
return ByteArrayTag.class;
case TYPE_STRING:
return StringTag.class;
case TYPE_LIST:
return ListTag.class;
case TYPE_COMPOUND:
return CompoundTag.class;
case TYPE_INT_ARRAY:
return IntArrayTag.class;
case TYPE_LONG_ARRAY:
return LongArrayTag.class;
default:
throw new IllegalArgumentException("Unknown tag type ID of " + id);
}
public static Class<? extends Tag<?, ?>> getClassFromType(int id) {
return switch (id) {
case TYPE_END -> EndTag.class;
case TYPE_BYTE -> ByteTag.class;
case TYPE_SHORT -> ShortTag.class;
case TYPE_INT -> IntTag.class;
case TYPE_LONG -> LongTag.class;
case TYPE_FLOAT -> FloatTag.class;
case TYPE_DOUBLE -> DoubleTag.class;
case TYPE_BYTE_ARRAY -> ByteArrayTag.class;
case TYPE_STRING -> StringTag.class;
case TYPE_LIST -> {
@SuppressWarnings("unchecked")
var aClass = (Class<? extends Tag<?, ?>>) (Class<?>) ListTag.class;
yield aClass;
}
case TYPE_COMPOUND -> CompoundTag.class;
case TYPE_INT_ARRAY -> IntArrayTag.class;
case TYPE_LONG_ARRAY -> LongArrayTag.class;
default -> throw new IllegalArgumentException("Unknown tag type ID of " + id);
};
}
}

View File

@ -21,6 +21,7 @@ package com.sk89q.jnbt;
import com.fastasyncworldedit.core.jnbt.streamer.StreamDelegate;
import com.fastasyncworldedit.core.jnbt.streamer.ValueReader;
import org.enginehub.linbus.stream.LinBinaryIO;
import java.io.Closeable;
import java.io.DataInputStream;
@ -44,8 +45,9 @@ import java.util.Map;
* https://minecraft.gamepedia.com/NBT_format</a>.
* </p>
*
* @deprecated JNBT is being removed for adventure-nbt in WorldEdit 8.
* @deprecated JNBT is being removed for lin-bus in WorldEdit 8, use {@link LinBinaryIO} instead
*/
@SuppressWarnings("removal")
@Deprecated(forRemoval = true)
public final class NBTInputStream implements Closeable {
@ -77,7 +79,6 @@ public final class NBTInputStream implements Closeable {
* Reads an NBT tag from the stream.
*
* @return The tag that was read.
* @throws IOException if an I/O error occurs.
*/
public NamedTag readNamedTag() throws IOException {
return readNamedTag(0);
@ -617,7 +618,7 @@ public final class NBTInputStream implements Closeable {
return new ListTag(NBTUtils.getTypeClass(childType), tagList);
case NBTConstants.TYPE_COMPOUND:
Map<String, Tag> tagMap = new HashMap<>();
Map<String, Tag<?, ?>> tagMap = new HashMap<>();
while (true) {
NamedTag namedTag = readNamedTag(depth + 1);
Tag tag = namedTag.getTag();

View File

@ -20,6 +20,7 @@
package com.sk89q.jnbt;
import com.fastasyncworldedit.core.internal.io.LittleEndianOutputStream;
import org.enginehub.linbus.stream.LinBinaryIO;
import java.io.Closeable;
import java.io.DataOutput;
@ -44,8 +45,9 @@ import static com.google.common.base.Preconditions.checkNotNull;
* https://minecraft.gamepedia.com/NBT_format</a>.
* </p>
*
* @deprecated JNBT is being removed for adventure-nbt in WorldEdit 8.
* @deprecated JNBT is being removed for lin-bus in WorldEdit 8, use {@link LinBinaryIO} instead
*/
@SuppressWarnings("removal")
@Deprecated(forRemoval = true)
public final class NBTOutputStream extends OutputStream implements Closeable, DataOutput {
@ -61,7 +63,7 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
* @param os The output stream.
* @throws IOException if an I/O error occurs.
*/
public NBTOutputStream(OutputStream os) throws IOException {
public NBTOutputStream(OutputStream os) {
this(os instanceof DataOutput ? (DataOutput) os : new DataOutputStream(os));
}
@ -91,11 +93,11 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
* @param tag The tag to write.
* @throws IOException if an I/O error occurs.
*/
public void writeNamedTag(String name, Tag tag) throws IOException {
public void writeNamedTag(String name, Tag<?, ?> tag) throws IOException {
checkNotNull(name);
checkNotNull(tag);
int type = NBTUtils.getTypeCode(tag.getClass());
int type = tag.getTypeCode();
writeNamedTagName(name, type);
if (type == NBTConstants.TYPE_END) {
@ -196,7 +198,7 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
}
public void writeTag(Tag tag) throws IOException {
int type = NBTUtils.getTypeCode(tag.getClass());
int type = tag.getTypeCode();
os.writeByte(type);
writeTagPayload(tag);
}
@ -212,7 +214,7 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
* @throws IOException if an I/O error occurs.
*/
public void writeTagPayload(Tag tag) throws IOException {
int type = NBTUtils.getTypeCode(tag.getClass());
int type = tag.getTypeCode();
switch (type) {
case NBTConstants.TYPE_END:
writeEndTagPayload((EndTag) tag);
@ -287,7 +289,7 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
* @throws IOException if an I/O error occurs.
*/
private void writeCompoundTagPayload(CompoundTag tag) throws IOException {
for (Map.Entry<String, Tag> entry : tag.getValue().entrySet()) {
for (Map.Entry<String, Tag<?, ?>> entry : tag.getValue().entrySet()) {
writeNamedTag(entry.getKey(), entry.getValue());
}
os.writeByte((byte) 0); // end tag - better way?
@ -300,7 +302,7 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
* @throws IOException if an I/O error occurs.
*/
private void writeListTagPayload(ListTag tag) throws IOException {
Class<? extends Tag> clazz = tag.getType();
Class<? extends Tag<?, ?>> clazz = tag.getType();
if (clazz == null) {
clazz = CompoundTag.class;
}

View File

@ -20,7 +20,6 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.util.nbt.BinaryTagTypes;
import com.sk89q.worldedit.world.storage.InvalidFormatException;
import java.util.Map;
@ -33,6 +32,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
*
* @deprecated JNBT is being removed for adventure-nbt in WorldEdit 8.
*/
@SuppressWarnings("ALL")
@Deprecated
public final class NBTUtils {
@ -48,7 +48,7 @@ public final class NBTUtils {
* @param clazz the tag class
* @return The type name.
*/
public static String getTypeName(Class<? extends Tag> clazz) {
public static String getTypeName(Class<? extends Tag<?, ?>> clazz) {
if (clazz.equals(ByteArrayTag.class)) {
return "TAG_Byte_Array";
} else if (clazz.equals(ByteTag.class)) {
@ -77,7 +77,7 @@ public final class NBTUtils {
return "TAG_Long_Array";
} else {
throw new IllegalArgumentException("Invalid tag class ("
+ clazz.getName() + ").");
+ clazz.getName() + ").");
}
}
@ -88,11 +88,35 @@ public final class NBTUtils {
* @return The type code.
* @throws IllegalArgumentException if the tag class is invalid.
*/
public static int getTypeCode(Class<? extends Tag> clazz) {
if (LazyCompoundTag.class.isAssignableFrom(clazz)) {
return BinaryTagTypes.COMPOUND.id();
public static int getTypeCode(Class<? extends Tag<?, ?>> clazz) {
if (clazz == ByteArrayTag.class) {
return NBTConstants.TYPE_BYTE_ARRAY;
} else if (clazz == ByteTag.class) {
return NBTConstants.TYPE_BYTE;
} else if (clazz == CompoundTag.class) {
return NBTConstants.TYPE_COMPOUND;
} else if (clazz == DoubleTag.class) {
return NBTConstants.TYPE_DOUBLE;
} else if (clazz == EndTag.class) {
return NBTConstants.TYPE_END;
} else if (clazz == FloatTag.class) {
return NBTConstants.TYPE_FLOAT;
} else if (clazz == IntArrayTag.class) {
return NBTConstants.TYPE_INT_ARRAY;
} else if (clazz == IntTag.class) {
return NBTConstants.TYPE_INT;
} else if (clazz.equals(ListTag.class) /* I hate this, it wouldn't do == b/c generics */) {
return NBTConstants.TYPE_LIST;
} else if (clazz == LongArrayTag.class) {
return NBTConstants.TYPE_LONG_ARRAY;
} else if (clazz == LongTag.class) {
return NBTConstants.TYPE_LONG;
} else if (clazz == ShortTag.class) {
return NBTConstants.TYPE_SHORT;
} else if (clazz == StringTag.class) {
return NBTConstants.TYPE_STRING;
}
return AdventureNBTConverter.getAdventureType(clazz).id();
throw new IllegalArgumentException("Invalid tag class (" + clazz.getName() + ")");
}
/**
@ -102,38 +126,8 @@ public final class NBTUtils {
* @return The class.
* @throws IllegalArgumentException if the tag type is invalid.
*/
public static Class<? extends Tag> getTypeClass(int type) {
switch (type) {
case NBTConstants.TYPE_END:
return EndTag.class;
case NBTConstants.TYPE_BYTE:
return ByteTag.class;
case NBTConstants.TYPE_SHORT:
return ShortTag.class;
case NBTConstants.TYPE_INT:
return IntTag.class;
case NBTConstants.TYPE_LONG:
return LongTag.class;
case NBTConstants.TYPE_FLOAT:
return FloatTag.class;
case NBTConstants.TYPE_DOUBLE:
return DoubleTag.class;
case NBTConstants.TYPE_BYTE_ARRAY:
return ByteArrayTag.class;
case NBTConstants.TYPE_STRING:
return StringTag.class;
case NBTConstants.TYPE_LIST:
return ListTag.class;
case NBTConstants.TYPE_COMPOUND:
return CompoundTag.class;
case NBTConstants.TYPE_INT_ARRAY:
return IntArrayTag.class;
case NBTConstants.TYPE_LONG_ARRAY:
return LongArrayTag.class;
default:
throw new IllegalArgumentException("Invalid tag type : " + type
+ ".");
}
public static Class<? extends Tag<?, ?>> getTypeClass(int type) {
return NBTConstants.getClassFromType(type);
}
/**
@ -145,7 +139,7 @@ public final class NBTUtils {
* @param listTag the list tag
* @return a vector
*/
public static Vector3 toVector(ListTag listTag) {
public static Vector3 toVector(ListTag<?, ?> listTag) {
checkNotNull(listTag);
return Vector3.at(listTag.asDouble(0), listTag.asDouble(1), listTag.asDouble(2));
}
@ -159,12 +153,12 @@ public final class NBTUtils {
* @return child tag
* @throws InvalidFormatException if the format of the items is invalid
*/
public static <T extends Tag> T getChildTag(Map<String, Tag> items, String key, Class<T> expected) throws
public static <T extends Tag<?, ?>> T getChildTag(Map<String, Tag<?, ?>> items, String key, Class<T> expected) throws
InvalidFormatException {
if (!items.containsKey(key)) {
throw new InvalidFormatException("Missing a \"" + key + "\" tag");
}
Tag tag = items.get(key);
Tag<?, ?> tag = items.get(key);
if (!expected.isInstance(tag)) {
throw new InvalidFormatException(key + " tag is not of tag type " + expected.getName());
}
@ -179,7 +173,7 @@ public final class NBTUtils {
* @param uuid {@link UUID} to add
* @since 2.4.0
*/
public static void addUUIDToMap(Map<String, Tag> map, UUID uuid) {
public static void addUUIDToMap(Map<String, Tag<?, ?>> map, UUID uuid) {
int[] uuidArray = new int[4];
uuidArray[0] = (int) (uuid.getMostSignificantBits() >> 32);
uuidArray[1] = (int) uuid.getMostSignificantBits();

View File

@ -30,7 +30,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
public class NamedTag {
private final String name;
private final Tag tag;
private final Tag<?, ?> tag;
/**
* Create a new named tag.
@ -38,7 +38,7 @@ public class NamedTag {
* @param name the name
* @param tag the tag
*/
public NamedTag(String name, Tag tag) {
public NamedTag(String name, Tag<?, ?> tag) {
checkNotNull(name);
checkNotNull(tag);
this.name = name;
@ -59,7 +59,7 @@ public class NamedTag {
*
* @return the tag
*/
public Tag getTag() {
public Tag<?, ?> getTag() {
return tag;
}

View File

@ -19,41 +19,32 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.ShortBinaryTag;
import com.fastasyncworldedit.core.jnbt.NumberTag;
import org.enginehub.linbus.tree.LinShortTag;
/**
* The {@code TAG_Short} tag.
*
* @deprecated Use {@link ShortBinaryTag}.
* @deprecated Use {@link LinShortTag}.
*/
@Deprecated
public final class ShortTag extends Tag {
private final ShortBinaryTag innerTag;
public final class ShortTag extends NumberTag<LinShortTag> {
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public ShortTag(short value) {
super();
this.innerTag = ShortBinaryTag.of(value);
super(LinShortTag.of(value));
}
public ShortTag(ShortBinaryTag adventureTag) {
super();
this.innerTag = adventureTag;
}
@Override
public ShortBinaryTag asBinaryTag() {
return this.innerTag;
public ShortTag(LinShortTag tag) {
super(tag);
}
@Override
public Short getValue() {
return innerTag.value();
return linTag.value();
}
//FAWE start

View File

@ -19,44 +19,33 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.StringBinaryTag;
import org.enginehub.linbus.tree.LinStringTag;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_String} tag.
*
* @deprecated Use {@link StringBinaryTag}.
* @deprecated Use {@link LinStringTag}.
*/
@Deprecated
public final class StringTag extends Tag {
private final StringBinaryTag innerTag;
public final class StringTag extends Tag<String, LinStringTag> {
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public StringTag(String value) {
super();
checkNotNull(value);
this.innerTag = StringBinaryTag.of(value);
super(LinStringTag.of(checkNotNull(value)));
}
public StringTag(StringBinaryTag adventureTag) {
super();
this.innerTag = adventureTag;
}
@Override
public StringBinaryTag asBinaryTag() {
return this.innerTag;
public StringTag(LinStringTag tag) {
super(tag);
}
@Override
public String getValue() {
return innerTag.value();
return linTag.value();
}
//FAWE start

View File

@ -19,26 +19,43 @@
package com.sk89q.jnbt;
import com.sk89q.worldedit.util.nbt.BinaryTagLike;
import org.enginehub.linbus.tree.LinTag;
import org.enginehub.linbus.tree.ToLinTag;
import javax.annotation.Nonnull;
/**
* Represents a NBT tag.
*
* @deprecated JNBT is being removed for adventure-nbt in WorldEdit 8.
* @deprecated JNBT is being removed for lin-bus in WorldEdit 8, use {@link LinTag} instead
*/
@Deprecated(forRemoval = true)
public abstract class Tag implements BinaryTagLike {
@Deprecated
public abstract class Tag<V, LT extends LinTag<? extends V>> implements ToLinTag<LT> {
protected final LT linTag;
protected Tag(LT linTag) {
this.linTag = linTag;
}
/**
* Gets the value of this tag.
*
* @return the value
*/
public abstract Object getValue();
public V getValue() {
return linTag.value();
}
@Override
public String toString() {
return asBinaryTag().toString();
return toLinTag().toString();
}
@Override
@Nonnull
public LT toLinTag() {
return linTag;
}
//FAWE start

View File

@ -76,7 +76,6 @@ import com.sk89q.worldedit.util.Countable;
import com.sk89q.worldedit.util.HandSide;
import com.sk89q.worldedit.util.Identifiable;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
@ -84,6 +83,8 @@ import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.snapshot.experimental.Snapshot;
import com.zaxxer.sparsebits.SparseBitSet;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinTagType;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ -1513,13 +1514,13 @@ public class LocalSession implements TextureHolder {
BaseBlock block = ServerCUIHandler.createStructureBlock(player);
if (block != null) {
CompoundBinaryTag tags = Objects.requireNonNull(
block.getNbt(), "createStructureBlock should return nbt"
LinCompoundTag tags = Objects.requireNonNull(
block.getNbt(), "createStructureBlock should return nbt"
);
BlockVector3 tempCuiTemporaryBlock = BlockVector3.at(
tags.getInt("x"),
tags.getInt("y"),
tags.getInt("z")
tags.getTag("x", LinTagType.intTag()).valueAsInt(),
tags.getTag("y", LinTagType.intTag()).valueAsInt(),
tags.getTag("z", LinTagType.intTag()).valueAsInt()
);
// If it's null, we don't need to do anything. The old was already removed.
if (cuiTemporaryBlock != null && !tempCuiTemporaryBlock.equals(cuiTemporaryBlock)) {

View File

@ -20,15 +20,13 @@
package com.sk89q.worldedit.blocks;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.TagStringIO;
import com.sk89q.worldedit.world.NbtValued;
import com.sk89q.worldedit.world.item.ItemType;
import org.enginehub.linbus.format.snbt.LinStringIO;
import org.enginehub.linbus.tree.LinCompoundTag;
import javax.annotation.Nullable;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull;
@ -42,9 +40,7 @@ public class BaseItem implements NbtValued {
private ItemType itemType;
@Nullable
//FAWE start - Use LR & CBT over CompoundTag
private LazyReference<CompoundBinaryTag> nbtData;
//FAWE end
private LazyReference<LinCompoundTag> nbtData;
/**
* Construct the object.
@ -56,6 +52,29 @@ public class BaseItem implements NbtValued {
this.itemType = itemType;
}
/**
* Construct the object.
*
* @param itemType Type of the item
* @param nbtData NBT Compound tag
*/
@Deprecated
public BaseItem(ItemType itemType, @Nullable CompoundTag nbtData) {
this(itemType, nbtData == null ? null : LazyReference.from(nbtData::toLinTag));
}
/**
* Construct the object.
*
* @param itemType Type of the item
* @param tag NBT Compound tag
*/
public BaseItem(ItemType itemType, @Nullable LazyReference<LinCompoundTag> tag) {
checkNotNull(itemType);
this.itemType = itemType;
this.nbtData = tag;
}
/**
* Get the type of item.
*
@ -77,29 +96,6 @@ public class BaseItem implements NbtValued {
//FAWE start
/**
* Construct the object.
*
* @param itemType Type of the item
* @param nbtData NBT Compound tag
*/
@Deprecated
public BaseItem(ItemType itemType, @Nullable CompoundTag nbtData) {
this(itemType, nbtData == null ? null : LazyReference.from(nbtData::asBinaryTag));
}
/**
* Construct the object.
*
* @param itemType Type of the item
* @param tag NBT Compound tag
*/
public BaseItem(ItemType itemType, @Nullable LazyReference<CompoundBinaryTag> tag) {
checkNotNull(itemType);
this.itemType = itemType;
this.nbtData = tag;
}
@Deprecated
@Nullable
public Object getNativeItem() {
@ -108,25 +104,20 @@ public class BaseItem implements NbtValued {
@Nullable
@Override
public LazyReference<CompoundBinaryTag> getNbtReference() {
public LazyReference<LinCompoundTag> getNbtReference() {
return this.nbtData;
}
@Override
public void setNbtReference(@Nullable LazyReference<CompoundBinaryTag> nbtData) {
public void setNbtReference(@Nullable LazyReference<LinCompoundTag> nbtData) {
this.nbtData = nbtData;
}
@Override
public String toString() {
String nbtString = "";
LazyReference<CompoundBinaryTag> nbtData = this.nbtData;
if (nbtData != null) {
try {
nbtString = TagStringIO.get().asString(nbtData.getValue());
} catch (IOException e) {
WorldEdit.logger.error("Failed to serialize NBT of Item", e);
}
nbtString = LinStringIO.writeToString(nbtData.getValue());
}
return getType().id() + nbtString;

View File

@ -24,8 +24,8 @@ import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.item.ItemType;
import org.enginehub.linbus.tree.LinCompoundTag;
/**
* Represents a stack of BaseItems.
@ -70,6 +70,18 @@ public class BaseItemStack extends BaseItem {
this.amount = amount;
}
/**
* Construct the object.
*
* @param id The item type
* @param tag Tag value
* @param amount amount in the stack
*/
public BaseItemStack(ItemType id, LazyReference<LinCompoundTag> tag, int amount) {
super(id, tag);
this.amount = amount;
}
/**
* Get the number of items in the stack.
*
@ -93,18 +105,4 @@ public class BaseItemStack extends BaseItem {
.getRegistries().getItemRegistry().getRichName(this);
}
//FAWE start
/**
* Construct the object.
*
* @param id The item type
* @param tag Tag value
* @param amount amount in the stack
*/
public BaseItemStack(ItemType id, LazyReference<CompoundBinaryTag> tag, int amount) {
super(id, tag);
this.amount = amount;
}
//FAWE end
}

View File

@ -21,10 +21,10 @@ package com.sk89q.worldedit.entity;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.NbtValued;
import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.entity.EntityTypes;
import org.enginehub.linbus.tree.LinCompoundTag;
import javax.annotation.Nullable;
@ -47,7 +47,7 @@ public class BaseEntity implements NbtValued {
private final EntityType type;
@Nullable
private LazyReference<CompoundBinaryTag> nbtData;
private LazyReference<LinCompoundTag> nbtData;
/**
* Create a new base entity.
@ -69,7 +69,7 @@ public class BaseEntity implements NbtValued {
* @param type the entity type
* @param nbtData NBT data
*/
public BaseEntity(EntityType type, LazyReference<CompoundBinaryTag> nbtData) {
public BaseEntity(EntityType type, LazyReference<LinCompoundTag> nbtData) {
this(type);
setNbtReference(nbtData);
}
@ -97,12 +97,12 @@ public class BaseEntity implements NbtValued {
@Nullable
@Override
public LazyReference<CompoundBinaryTag> getNbtReference() {
public LazyReference<LinCompoundTag> getNbtReference() {
return nbtData;
}
@Override
public void setNbtReference(@Nullable LazyReference<CompoundBinaryTag> nbtData) {
public void setNbtReference(@Nullable LazyReference<LinCompoundTag> nbtData) {
this.nbtData = nbtData;
}

View File

@ -20,7 +20,6 @@
package com.sk89q.worldedit.extension.factory.parser;
import com.fastasyncworldedit.core.configuration.Caption;
import com.fastasyncworldedit.core.util.NbtUtils;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.blocks.BaseItem;
import com.sk89q.worldedit.blocks.BaseItemStack;
@ -35,13 +34,13 @@ import com.sk89q.worldedit.util.HandSide;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.TagStringIO;
import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.item.ItemTypes;
import com.sk89q.worldedit.world.registry.LegacyMapper;
import org.enginehub.linbus.format.snbt.LinStringIO;
import org.enginehub.linbus.stream.exception.NbtParseException;
import org.enginehub.linbus.tree.LinCompoundTag;
import java.io.IOException;
import java.util.Locale;
import java.util.stream.Stream;
@ -59,7 +58,7 @@ public class DefaultItemParser extends InputParser<BaseItem> {
@Override
public BaseItem parseFromInput(String input, ParserContext context) throws InputParseException {
ItemType itemType;
CompoundBinaryTag itemNbtData = null;
LinCompoundTag itemNbtData = null;
BaseItem item = null;
@ -128,20 +127,21 @@ public class DefaultItemParser extends InputParser<BaseItem> {
}
if (nbtString != null) {
LinCompoundTag otherTag;
try {
CompoundBinaryTag otherTag = TagStringIO.get().asCompound(nbtString);
if (itemNbtData == null) {
itemNbtData = otherTag;
} else {
itemNbtData.put(NbtUtils.getCompoundBinaryTagValues(otherTag));
}
} catch (IOException e) {
otherTag = LinStringIO.readFromStringUsing(nbtString, LinCompoundTag::readFrom);
} catch (NbtParseException e) {
throw new NoMatchException(TranslatableComponent.of(
"worldedit.error.invalid-nbt",
TextComponent.of(input),
TextComponent.of(e.getMessage())
));
}
if (itemNbtData == null) {
itemNbtData = otherTag;
} else {
itemNbtData = itemNbtData.toBuilder().putAll(otherTag.value()).build();
}
}
item = new BaseItem(itemType, itemNbtData == null ? null : LazyReference.computed(itemNbtData));

View File

@ -186,7 +186,7 @@ public class BlockArrayClipboard implements Clipboard {
}
@Override
public <B extends BlockStateHolder<B>> boolean setBlock(BlockVector3 position, B block) throws WorldEditException {
public <B extends BlockStateHolder<B>> boolean setBlock(BlockVector3 position, B block) {
if (region.contains(position)) {
//FAWE - get points
final int x = position.x();

View File

@ -153,7 +153,7 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
CompoundTag schematicTag = (CompoundTag) rootTag.getTag();
// Check
Map<String, Tag> schematic = schematicTag.getValue();
Map<String, Tag<?, ?>> schematic = schematicTag.getValue();
if (!schematic.containsKey("Version")) {
return false;
}

View File

@ -20,17 +20,7 @@
package com.sk89q.worldedit.extent.clipboard.io;
import com.google.common.collect.ImmutableList;
import com.sk89q.jnbt.AdventureNBTConverter;
import com.sk89q.jnbt.ByteArrayTag;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.NBTInputStream;
import com.sk89q.jnbt.NamedTag;
import com.sk89q.jnbt.ShortTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
@ -49,7 +39,7 @@ import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.collection.BlockMap;
import com.sk89q.worldedit.world.DataFixer;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.entity.EntityType;
@ -57,27 +47,25 @@ import com.sk89q.worldedit.world.entity.EntityTypes;
import com.sk89q.worldedit.world.registry.LegacyMapper;
import com.sk89q.worldedit.world.storage.NBTConversions;
import org.apache.logging.log4j.Logger;
import org.enginehub.linbus.tree.LinByteArrayTag;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinRootEntry;
import org.enginehub.linbus.tree.LinTagType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.UncheckedIOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Reads schematic files that are compatible with MCEdit and other editors.
*/
public class MCEditSchematicReader extends NBTSchematicReader {
private static final Logger LOGGER = LogManagerCompat.getLogger();
private final NBTInputStream inputStream;
private final DataFixer fixer;
private final LinRootEntry root;
private static final ImmutableList<NBTCompatibilityHandler> COMPATIBILITY_HANDLERS
= ImmutableList.of(
new SignCompatibilityHandler(),
@ -98,30 +86,30 @@ public class MCEditSchematicReader extends NBTSchematicReader {
* @param inputStream the input stream to read from
*/
public MCEditSchematicReader(NBTInputStream inputStream) {
checkNotNull(inputStream);
this.inputStream = inputStream;
this.fixer = null;
//com.sk89q.worldedit.WorldEdit.getInstance().getPlatformManager().queryCapability(
//com.sk89q.worldedit.extension.platform.Capability.WORLD_EDITING).getDataFixer();
try {
var tag = inputStream.readNamedTag();
this.root = new LinRootEntry(tag.getName(), (LinCompoundTag) tag.getTag().toLinTag());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
MCEditSchematicReader(LinRootEntry root) {
this.root = root;
}
@Override
public Clipboard read() throws IOException {
// Schematic tag
NamedTag rootTag = inputStream.readNamedTag();
if (!rootTag.getName().equals("Schematic")) {
if (!root.name().equals("Schematic")) {
throw new IOException("Tag 'Schematic' does not exist or is not first");
}
CompoundTag schematicTag = (CompoundTag) rootTag.getTag();
var schematicTag = root.value();
// Check
Map<String, Tag> schematic = schematicTag.getValue();
if (!schematic.containsKey("Blocks")) {
if (!schematicTag.value().containsKey("Blocks")) {
throw new IOException("Schematic file is missing a 'Blocks' tag");
}
// Check type of Schematic
String materials = requireTag(schematic, "Materials", StringTag.class).getValue();
String materials = schematicTag.getTag("Materials", LinTagType.stringTag()).value();
if (!materials.equals("Alpha")) {
throw new IOException("Schematic file is not an Alpha schematic");
}
@ -134,42 +122,38 @@ public class MCEditSchematicReader extends NBTSchematicReader {
Region region;
// Get information
short width = requireTag(schematic, "Width", ShortTag.class).getValue();
short height = requireTag(schematic, "Height", ShortTag.class).getValue();
short length = requireTag(schematic, "Length", ShortTag.class).getValue();
short width = schematicTag.getTag("Width", LinTagType.shortTag()).valueAsShort();
short height = schematicTag.getTag("Height", LinTagType.shortTag()).valueAsShort();
short length = schematicTag.getTag("Length", LinTagType.shortTag()).valueAsShort();
try {
int originX = requireTag(schematic, "WEOriginX", IntTag.class).getValue();
int originY = requireTag(schematic, "WEOriginY", IntTag.class).getValue();
int originZ = requireTag(schematic, "WEOriginZ", IntTag.class).getValue();
BlockVector3 min = BlockVector3.at(originX, originY, originZ);
int originX = schematicTag.getTag("WEOriginX", LinTagType.intTag()).valueAsInt();
int originY = schematicTag.getTag("WEOriginY", LinTagType.intTag()).valueAsInt();
int originZ = schematicTag.getTag("WEOriginZ", LinTagType.intTag()).valueAsInt();
BlockVector3 min = BlockVector3.at(originX, originY, originZ);
int offsetX = requireTag(schematic, "WEOffsetX", IntTag.class).getValue();
int offsetY = requireTag(schematic, "WEOffsetY", IntTag.class).getValue();
int offsetZ = requireTag(schematic, "WEOffsetZ", IntTag.class).getValue();
BlockVector3 offset = BlockVector3.at(offsetX, offsetY, offsetZ);
int offsetX = schematicTag.getTag("WEOffsetX", LinTagType.intTag()).valueAsInt();
int offsetY = schematicTag.getTag("WEOffsetY", LinTagType.intTag()).valueAsInt();
int offsetZ = schematicTag.getTag("WEOffsetZ", LinTagType.intTag()).valueAsInt();
BlockVector3 offset = BlockVector3.at(offsetX, offsetY, offsetZ);
origin = min.subtract(offset);
region = new CuboidRegion(min, min.add(width, height, length).subtract(BlockVector3.ONE));
} catch (IOException ignored) {
origin = BlockVector3.ZERO;
region = new CuboidRegion(origin, origin.add(width, height, length).subtract(BlockVector3.ONE));
}
origin = min.subtract(offset);
region = new CuboidRegion(min, min.add(width, height, length).subtract(BlockVector3.ONE));
// ====================================================================
// Blocks
// ====================================================================
// Get blocks
byte[] blockId = requireTag(schematic, "Blocks", ByteArrayTag.class).getValue();
byte[] blockData = requireTag(schematic, "Data", ByteArrayTag.class).getValue();
byte[] blockId = schematicTag.getTag("Blocks", LinTagType.byteArrayTag()).value();
byte[] blockData = schematicTag.getTag("Data", LinTagType.byteArrayTag()).value();
byte[] addId = new byte[0];
short[] blocks = new short[blockId.length]; // Have to later combine IDs
// We support 4096 block IDs using the same method as vanilla Minecraft, where
// the highest 4 bits are stored in a separate byte array.
if (schematic.containsKey("AddBlocks")) {
addId = requireTag(schematic, "AddBlocks", ByteArrayTag.class).getValue();
LinByteArrayTag addBlocks = schematicTag.findTag("AddBlocks", LinTagType.byteArrayTag());
if (addBlocks != null) {
addId = addBlocks.value();
}
// Combine the AddBlocks data with the first 8-bit block ID
@ -186,21 +170,17 @@ public class MCEditSchematicReader extends NBTSchematicReader {
}
// Need to pull out tile entities
final ListTag tileEntityTag = getTag(schematic, "TileEntities", ListTag.class);
List<Tag> tileEntities = tileEntityTag == null ? new ArrayList<>() : tileEntityTag.getValue();
var tileEntityTag = schematicTag.findListTag("TileEntities", LinTagType.compoundTag());
List<LinCompoundTag> tileEntities = tileEntityTag == null ? List.of() : tileEntityTag.value();
BlockMap<BaseBlock> tileEntityBlocks = BlockMap.createForBaseBlock();
for (Tag tag : tileEntities) {
if (!(tag instanceof CompoundTag)) {
continue;
}
CompoundTag t = (CompoundTag) tag;
Map<String, Tag> values = new HashMap<>(t.getValue());
String id = t.getString("id");
values.put("id", new StringTag(convertBlockEntityId(id)));
int x = t.getInt("x");
int y = t.getInt("y");
int z = t.getInt("z");
for (LinCompoundTag tag : tileEntities) {
var newTag = tag.toBuilder();
String id = tag.getTag("id", LinTagType.stringTag()).value();
newTag.putString("id", convertBlockEntityId(id));
int x = tag.getTag("x", LinTagType.intTag()).valueAsInt();
int y = tag.getTag("y", LinTagType.intTag()).valueAsInt();
int z = tag.getTag("z", LinTagType.intTag()).valueAsInt();
int index = y * width * length + z * width + x;
//FAWE start - tile entity safety - perhaps caused by the old issue with tile entities created in the wrong
@ -211,44 +191,17 @@ public class MCEditSchematicReader extends NBTSchematicReader {
}
BlockState block = getBlockState(blocks[index], blockData[index]);
BlockState newBlock = block;
if (newBlock != null) {
for (NBTCompatibilityHandler handler : COMPATIBILITY_HANDLERS) {
if (handler.isAffectedBlock(newBlock)) {
newBlock = handler.updateNBT(block, values).toImmutableState();
if (newBlock == null || values.isEmpty()) {
break;
}
}
if (block == null) {
continue;
}
var updatedBlock = block.toBaseBlock(LazyReference.from(newTag::build));
for (NBTCompatibilityHandler handler : COMPATIBILITY_HANDLERS) {
updatedBlock = handler.updateNbt(updatedBlock);
if (updatedBlock.getNbtReference() == null) {
break;
}
}
if (values.isEmpty()) {
t = null;
} else {
t = new CompoundTag(values);
}
if (fixer != null && t != null) {
//FAWE start - BinaryTag
t = (CompoundTag) AdventureNBTConverter.fromAdventure(fixer.fixUp(
DataFixer.FixTypes.BLOCK_ENTITY,
t.asBinaryTag(),
-1
));
//FAWE end
}
BlockVector3 vec = BlockVector3.at(x, y, z);
// Insert into the map if we have changed the block or have a tag
BlockState blockToInsert = newBlock != null
? newBlock
: (t != null ? block : null);
if (blockToInsert != null) {
BaseBlock baseBlock = t != null
? blockToInsert.toBaseBlock(new CompoundTag(t.getValue()))
: blockToInsert.toBaseBlock();
tileEntityBlocks.put(vec, baseBlock);
}
tileEntityBlocks.put(BlockVector3.at(x, y, z), updatedBlock);
}
BlockArrayClipboard clipboard = new BlockArrayClipboard(region);
@ -261,16 +214,10 @@ public class MCEditSchematicReader extends NBTSchematicReader {
for (int z = 0; z < length; ++z) {
int index = y * width * length + z * width + x;
BlockVector3 pt = BlockVector3.at(x, y, z);
BaseBlock state = Optional.ofNullable(tileEntityBlocks.get(pt))
.orElseGet(() -> {
BlockState blockState = getBlockState(blocks[index], blockData[index]);
return blockState == null ? null : blockState.toBaseBlock();
});
try {
if (state != null) {
clipboard.setBlock(region.getMinimumPoint().add(pt), state);
} else {
BaseBlock state = tileEntityBlocks.get(pt);
if (state == null) {
BlockState blockState = getBlockState(blocks[index], blockData[index]);
if (blockState == null) {
short block = blocks[index];
byte data = blockData[index];
int combined = block << 8 | data;
@ -278,9 +225,12 @@ public class MCEditSchematicReader extends NBTSchematicReader {
LOGGER.warn("Unknown block when loading schematic: {} {}. This is most likely a" +
"bad schematic.", block, data);
}
continue;
}
} catch (WorldEditException ignored) { // BlockArrayClipboard won't throw this
state = blockState.toBaseBlock();
}
clipboard.setBlock(region.getMinimumPoint().add(pt), state);
}
}
}
@ -289,40 +239,25 @@ public class MCEditSchematicReader extends NBTSchematicReader {
// Entities
// ====================================================================
ListTag entityList = getTag(schematic, "Entities", ListTag.class);
var entityList = schematicTag.findListTag("Entities", LinTagType.compoundTag());
if (entityList != null) {
List<Tag> entityTags = entityList.getValue();
for (Tag tag : entityTags) {
if (tag instanceof CompoundTag) {
CompoundTag compound = (CompoundTag) tag;
if (fixer != null) {
//FAWE start - BinaryTag
compound = (CompoundTag) AdventureNBTConverter.fromAdventure(fixer.fixUp(
DataFixer.FixTypes.ENTITY,
compound.asBinaryTag(),
-1
));
//FAWE end
}
String id = convertEntityId(compound.getString("id"));
Location location = NBTConversions.toLocation(
clipboard,
compound.getListTag("Pos"),
compound.getListTag("Rotation")
);
if (!id.isEmpty()) {
EntityType entityType = EntityTypes.get(id.toLowerCase(Locale.ROOT));
if (entityType != null) {
for (EntityNBTCompatibilityHandler compatibilityHandler : ENTITY_COMPATIBILITY_HANDLERS) {
if (compatibilityHandler.isAffectedEntity(entityType, compound)) {
compound = compatibilityHandler.updateNBT(entityType, compound);
}
}
BaseEntity state = new BaseEntity(entityType, compound);
clipboard.createEntity(location, state);
} else {
LOGGER.warn("Unknown entity when pasting schematic: " + id.toLowerCase(Locale.ROOT));
for (LinCompoundTag tag : entityList.value()) {
String id = convertEntityId(tag.getTag("id", LinTagType.stringTag()).value());
Location location = NBTConversions.toLocation(
clipboard,
tag.getListTag("Pos", LinTagType.doubleTag()),
tag.getListTag("Rotation", LinTagType.floatTag())
);
if (!id.isEmpty()) {
EntityType entityType = EntityTypes.get(id.toLowerCase(Locale.ROOT));
if (entityType != null) {
for (EntityNBTCompatibilityHandler compatibilityHandler : ENTITY_COMPATIBILITY_HANDLERS) {
tag = compatibilityHandler.updateNbt(entityType, tag);
}
BaseEntity state = new BaseEntity(entityType, LazyReference.computed(tag));
clipboard.createEntity(location, state);
} else {
LOGGER.warn("Unknown entity when pasting schematic: " + id.toLowerCase(Locale.ROOT));
}
}
}
@ -494,7 +429,6 @@ public class MCEditSchematicReader extends NBTSchematicReader {
@Override
public void close() throws IOException {
inputStream.close();
}
}

View File

@ -30,13 +30,13 @@ import java.util.Map;
*/
public abstract class NBTSchematicReader implements ClipboardReader {
protected static <T extends Tag> T requireTag(Map<String, Tag> items, String key, Class<T> expected) throws IOException {
protected static <T extends Tag<?, ?>> T requireTag(Map<String, Tag<?, ?>> items, String key, Class<T> expected) throws IOException {
if (!items.containsKey(key)) {
throw new IOException("Schematic file is missing a \"" + key + "\" tag of type "
+ expected.getName());
}
Tag tag = items.get(key);
Tag<?, ?> tag = items.get(key);
if (!expected.isInstance(tag)) {
throw new IOException(key + " tag is not of tag type " + expected.getName() + ", got "
+ tag.getClass().getName() + " instead");
@ -46,12 +46,12 @@ public abstract class NBTSchematicReader implements ClipboardReader {
}
@Nullable
protected static <T extends Tag> T getTag(Map<String, Tag> items, String key, Class<T> expected) {
protected static <T extends Tag<?, ?>> T getTag(Map<String, Tag<?, ?>> items, String key, Class<T> expected) {
if (!items.containsKey(key)) {
return null;
}
Tag test = items.get(key);
Tag<?, ?> test = items.get(key);
if (!expected.isInstance(test)) {
return null;
}

View File

@ -21,7 +21,7 @@ package com.sk89q.worldedit.extent.clipboard.io;
import com.fastasyncworldedit.core.configuration.Caption;
import com.google.common.collect.Maps;
import com.sk89q.jnbt.AdventureNBTConverter;
import com.sk89q.jnbt.LinBusConverter;
import com.sk89q.jnbt.ByteArrayTag;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.IntArrayTag;
@ -64,7 +64,6 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.OptionalInt;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
@ -97,7 +96,7 @@ public class SpongeSchematicReader extends NBTSchematicReader {
@Override
public Clipboard read() throws IOException {
CompoundTag schematicTag = getBaseTag();
Map<String, Tag> schematic = schematicTag.getValue();
Map<String, Tag<?, ?>> schematic = schematicTag.getValue();
final Platform platform = WorldEdit.getInstance().getPlatformManager()
.queryCapability(Capability.WORLD_EDITING);
@ -147,7 +146,7 @@ public class SpongeSchematicReader extends NBTSchematicReader {
public OptionalInt getDataVersion() {
try {
CompoundTag schematicTag = getBaseTag();
Map<String, Tag> schematic = schematicTag.getValue();
Map<String, Tag<?, ?>> schematic = schematicTag.getValue();
if (schematicVersion == 1) {
return OptionalInt.of(Constants.DATA_VERSION_MC_1_13_2);
} else if (schematicVersion == 2) {
@ -168,7 +167,7 @@ public class SpongeSchematicReader extends NBTSchematicReader {
CompoundTag schematicTag = (CompoundTag) rootTag.getTag();
// Check
Map<String, Tag> schematic = schematicTag.getValue();
Map<String, Tag<?, ?>> schematic = schematicTag.getValue();
// Be lenient about the specific nesting level of the Schematic tag
// Also allows checking the version from newer versions of the specification
@ -184,7 +183,7 @@ public class SpongeSchematicReader extends NBTSchematicReader {
private BlockArrayClipboard readVersion1(CompoundTag schematicTag) throws IOException {
BlockVector3 origin;
Region region;
Map<String, Tag> schematic = schematicTag.getValue();
Map<String, Tag<?, ?>> schematic = schematicTag.getValue();
int width = requireTag(schematic, "Width", ShortTag.class).getValue();
int height = requireTag(schematic, "Height", ShortTag.class).getValue();
@ -206,7 +205,7 @@ public class SpongeSchematicReader extends NBTSchematicReader {
CompoundTag metadataTag = getTag(schematic, "Metadata", CompoundTag.class);
if (metadataTag != null && metadataTag.containsKey("WEOffsetX")) {
// We appear to have WorldEdit Metadata
Map<String, Tag> metadata = metadataTag.getValue();
Map<String, Tag<?, ?>> metadata = metadataTag.getValue();
int offsetX = requireTag(metadata, "WEOffsetX", IntTag.class).getValue();
int offsetY = requireTag(metadata, "WEOffsetY", IntTag.class).getValue();
int offsetZ = requireTag(metadata, "WEOffsetZ", IntTag.class).getValue();
@ -219,7 +218,7 @@ public class SpongeSchematicReader extends NBTSchematicReader {
}
IntTag paletteMaxTag = getTag(schematic, "PaletteMax", IntTag.class);
Map<String, Tag> paletteObject = requireTag(schematic, "Palette", CompoundTag.class).getValue();
Map<String, Tag<?, ?>> paletteObject = requireTag(schematic, "Palette", CompoundTag.class).getValue();
if (paletteMaxTag != null && paletteObject.size() != paletteMaxTag.getValue()) {
throw new IOException("Block palette size does not match expected size.");
}
@ -248,21 +247,17 @@ public class SpongeSchematicReader extends NBTSchematicReader {
byte[] blocks = requireTag(schematic, "BlockData", ByteArrayTag.class).getValue();
Map<BlockVector3, Map<String, Tag>> tileEntitiesMap = new HashMap<>();
Map<BlockVector3, Map<String, Tag<?, ?>>> tileEntitiesMap = new HashMap<>();
ListTag tileEntities = getTag(schematic, "BlockEntities", ListTag.class);
if (tileEntities == null) {
tileEntities = getTag(schematic, "TileEntities", ListTag.class);
}
if (tileEntities != null) {
List<Map<String, Tag>> tileEntityTags = tileEntities.getValue().stream()
.map(tag -> (CompoundTag) tag)
.map(CompoundTag::getValue)
.collect(Collectors.toList());
for (Map<String, Tag> tileEntity : tileEntityTags) {
for (Object tileTag : tileEntities.getValue()) {
Map<String, Tag<?, ?>> tileEntity = ((CompoundTag) tileTag).getValue();
int[] pos = requireTag(tileEntity, "Pos", IntArrayTag.class).getValue();
final BlockVector3 pt = BlockVector3.at(pos[0], pos[1], pos[2]);
Map<String, Tag> values = Maps.newHashMap(tileEntity);
Map<String, Tag<?, ?>> values = Maps.newHashMap(tileEntity);
values.put("x", new IntTag(pt.x()));
values.put("y", new IntTag(pt.y()));
values.put("z", new IntTag(pt.z()));
@ -279,10 +274,10 @@ public class SpongeSchematicReader extends NBTSchematicReader {
values.remove("Id");
values.remove("Pos");
if (fixer != null) {
//FAWE start - BinaryTag
tileEntity = ((CompoundTag) AdventureNBTConverter.fromAdventure(fixer.fixUp(
//FAWE start - LinTag
tileEntity = ((CompoundTag) LinBusConverter.fromLinBus(fixer.fixUp(
DataFixer.FixTypes.BLOCK_ENTITY,
new CompoundTag(values).asBinaryTag(),
new CompoundTag(values).toLinTag(),
dataVersion
))).getValue();
//FAWE end
@ -341,7 +336,7 @@ public class SpongeSchematicReader extends NBTSchematicReader {
}
private Clipboard readVersion2(BlockArrayClipboard version1, CompoundTag schematicTag) throws IOException {
Map<String, Tag> schematic = schematicTag.getValue();
Map<String, Tag<?, ?>> schematic = schematicTag.getValue();
if (schematic.containsKey("BiomeData")) {
readBiomes(version1, schematic);
}
@ -351,7 +346,7 @@ public class SpongeSchematicReader extends NBTSchematicReader {
return version1;
}
private void readBiomes(BlockArrayClipboard clipboard, Map<String, Tag> schematic) throws IOException {
private void readBiomes(BlockArrayClipboard clipboard, Map<String, Tag<?, ?>> schematic) throws IOException {
ByteArrayTag dataTag = requireTag(schematic, "BiomeData", ByteArrayTag.class);
IntTag maxTag = requireTag(schematic, "BiomePaletteMax", IntTag.class);
CompoundTag paletteTag = requireTag(schematic, "BiomePalette", CompoundTag.class);
@ -361,7 +356,7 @@ public class SpongeSchematicReader extends NBTSchematicReader {
throw new IOException("Biome palette size does not match expected size.");
}
for (Entry<String, Tag> palettePart : paletteTag.getValue().entrySet()) {
for (Entry<String, Tag<?, ?>> palettePart : paletteTag.getValue().entrySet()) {
String key = palettePart.getKey();
if (fixer != null) {
key = fixer.fixUp(DataFixer.FixTypes.BIOME, key, dataVersion);
@ -411,7 +406,7 @@ public class SpongeSchematicReader extends NBTSchematicReader {
}
}
private void readEntities(BlockArrayClipboard clipboard, Map<String, Tag> schematic) throws IOException {
private void readEntities(BlockArrayClipboard clipboard, Map<String, Tag<?, ?>> schematic) throws IOException {
List<Tag> entList = requireTag(schematic, "Entities", ListTag.class).getValue();
if (entList.isEmpty()) {
return;
@ -421,15 +416,15 @@ public class SpongeSchematicReader extends NBTSchematicReader {
continue;
}
CompoundTag entityTag = (CompoundTag) et;
Map<String, Tag> tags = entityTag.getValue();
Map<String, Tag<?, ?>> tags = entityTag.getValue();
String id = requireTag(tags, "Id", StringTag.class).getValue();
entityTag = entityTag.createBuilder().putString("id", id).remove("Id").build();
if (fixer != null) {
//FAWE start - BinaryTag
entityTag = (CompoundTag) AdventureNBTConverter.fromAdventure(fixer.fixUp(
//FAWE start - LinTag
entityTag = (CompoundTag) LinBusConverter.fromLinBus(fixer.fixUp(
DataFixer.FixTypes.ENTITY,
entityTag.asBinaryTag(),
entityTag.toLinTag(),
dataVersion
));
//FAWE end

View File

@ -92,7 +92,7 @@ public class SpongeSchematicWriter implements ClipboardWriter {
* @param clipboard The clipboard
* @return The schematic map
*/
private Map<String, Tag> write2(Clipboard clipboard) {
private Map<String, Tag<?, ?>> write2(Clipboard clipboard) {
Region region = clipboard.getRegion();
BlockVector3 origin = clipboard.getOrigin();
BlockVector3 min = region.getMinimumPoint();
@ -111,12 +111,12 @@ public class SpongeSchematicWriter implements ClipboardWriter {
throw new IllegalArgumentException("Length of region too large for a .schematic");
}
Map<String, Tag> schematic = new HashMap<>();
Map<String, Tag<?, ?>> schematic = new HashMap<>();
schematic.put("Version", new IntTag(CURRENT_VERSION));
schematic.put("DataVersion", new IntTag(
WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).getDataVersion()));
Map<String, Tag> metadata = new HashMap<>();
Map<String, Tag<?, ?>> metadata = new HashMap<>();
metadata.put("WEOffsetX", new IntTag(offset.x()));
metadata.put("WEOffsetY", new IntTag(offset.y()));
metadata.put("WEOffsetZ", new IntTag(offset.z()));
@ -151,7 +151,7 @@ public class SpongeSchematicWriter implements ClipboardWriter {
BlockVector3 point = BlockVector3.at(x0, y0, z0);
BaseBlock block = clipboard.getFullBlock(point);
if (block.getNbtData() != null) {
Map<String, Tag> values = new HashMap<>(block.getNbtData().getValue());
Map<String, Tag<?, ?>> values = new HashMap<>(block.getNbtData().getValue());
values.remove("id"); // Remove 'id' if it exists. We want 'Id'
@ -187,7 +187,7 @@ public class SpongeSchematicWriter implements ClipboardWriter {
schematic.put("PaletteMax", new IntTag(paletteMax));
Map<String, Tag> paletteTag = new HashMap<>();
Map<String, Tag<?, ?>> paletteTag = new HashMap<>();
palette.forEach((key, value) -> paletteTag.put(key, new IntTag(value)));
schematic.put("Palette", new CompoundTag(paletteTag));
@ -206,7 +206,7 @@ public class SpongeSchematicWriter implements ClipboardWriter {
return schematic;
}
private void writeBiomes(Clipboard clipboard, Map<String, Tag> schematic) {
private void writeBiomes(Clipboard clipboard, Map<String, Tag<?, ?>> schematic) {
BlockVector3 min = clipboard.getMinimumPoint();
int width = clipboard.getRegion().getWidth();
int length = clipboard.getRegion().getLength();
@ -243,20 +243,20 @@ public class SpongeSchematicWriter implements ClipboardWriter {
schematic.put("BiomePaletteMax", new IntTag(paletteMax));
Map<String, Tag> paletteTag = new HashMap<>();
Map<String, Tag<?, ?>> paletteTag = new HashMap<>();
palette.forEach((key, value) -> paletteTag.put(key, new IntTag(value)));
schematic.put("BiomePalette", new CompoundTag(paletteTag));
schematic.put("BiomeData", new ByteArrayTag(buffer.toByteArray()));
}
private void writeEntities(Clipboard clipboard, Map<String, Tag> schematic) {
private void writeEntities(Clipboard clipboard, Map<String, Tag<?, ?>> schematic) {
List<CompoundTag> entities = clipboard.getEntities().stream().map(e -> {
BaseEntity state = e.getState();
if (state == null) {
return null;
}
Map<String, Tag> values = Maps.newHashMap();
Map<String, Tag<?, ?>> values = Maps.newHashMap();
CompoundTag rawData = state.getNbtData();
if (rawData != null) {
values.putAll(rawData.getValue());

View File

@ -19,21 +19,16 @@
package com.sk89q.worldedit.extent.clipboard.io.legacycompat;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.CompoundTagBuilder;
import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinIntTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinTagType;
public class BannerBlockCompatibilityHandler implements NBTCompatibilityHandler {
@ -55,17 +50,19 @@ public class BannerBlockCompatibilityHandler implements NBTCompatibilityHandler
}
@Override
public <B extends BlockStateHolder<B>> boolean isAffectedBlock(B block) {
return block.getBlockType() == BlockTypes.WHITE_BANNER
|| block.getBlockType() == BlockTypes.WHITE_WALL_BANNER;
}
@Override
public <B extends BlockStateHolder<B>> BlockStateHolder<?> updateNBT(B block, Map<String, Tag> values) {
Tag typeTag = values.get("Base");
if (typeTag instanceof IntTag) {
public BaseBlock updateNbt(BaseBlock block) {
var blockType = block.getBlockType();
if (blockType != BlockTypes.WHITE_BANNER && blockType != BlockTypes.WHITE_WALL_BANNER) {
return block;
}
var nbt = block.getNbt();
if (nbt == null) {
return block;
}
LinIntTag typeTag = nbt.findTag("Base", LinTagType.intTag());
if (typeTag != null) {
boolean isWall = block.getBlockType() == BlockTypes.WHITE_WALL_BANNER;
String bannerType = convertBannerType(((IntTag) typeTag).getValue(), isWall);
String bannerType = convertBannerType(typeTag.valueAsInt(), isWall);
if (bannerType != null) {
BlockType type = BlockTypes.get("minecraft:" + bannerType);
if (type != null) {
@ -79,29 +76,25 @@ public class BannerBlockCompatibilityHandler implements NBTCompatibilityHandler
state = state.with(rotationProp, block.getState(RotationProperty));
}
values.remove("Base");
var nbtBuilder = nbt.toBuilder();
nbtBuilder.remove("Base");
Tag patternsTag = values.get("Patterns");
if (patternsTag instanceof ListTag) {
List<Tag> tempList = new ArrayList<>();
for (Tag pattern : ((ListTag) patternsTag).getValue()) {
if (pattern instanceof CompoundTag) {
Map<String, Tag> patternMap = ((CompoundTag) pattern).getValue();
Tag colorTag = patternMap.get("Color");
CompoundTagBuilder builder = CompoundTagBuilder.create();
builder.putAll(patternMap);
if (colorTag instanceof IntTag) {
builder.putInt("Color", 15 - ((IntTag) colorTag).getValue());
}
tempList.add(builder.build());
var patternsTag = nbt.findListTag("Patterns", LinTagType.compoundTag());
if (patternsTag != null) {
var newPatterns = LinListTag.builder(LinTagType.compoundTag());
for (LinCompoundTag pattern : patternsTag.value()) {
LinIntTag color = pattern.findTag("Color", LinTagType.intTag());
if (color != null) {
newPatterns.add(pattern.toBuilder()
.putInt("Color", 15 - color.valueAsInt())
.build());
} else {
tempList.add(pattern);
newPatterns.add(pattern);
}
}
values.put("Patterns", new ListTag(((ListTag) patternsTag).getType(), tempList));
nbtBuilder.put("Patterns", newPatterns.build());
}
return state;
return state.toBaseBlock(nbtBuilder.build());
}
}
}
@ -109,58 +102,27 @@ public class BannerBlockCompatibilityHandler implements NBTCompatibilityHandler
}
private static String convertBannerType(int oldType, boolean isWall) {
String color;
switch (oldType) {
case 0:
color = "black";
break;
case 1:
color = "red";
break;
case 2:
color = "green";
break;
case 3:
color = "brown";
break;
case 4:
color = "blue";
break;
case 5:
color = "purple";
break;
case 6:
color = "cyan";
break;
case 7:
color = "light_gray";
break;
case 8:
color = "gray";
break;
case 9:
color = "pink";
break;
case 10:
color = "lime";
break;
case 11:
color = "yellow";
break;
case 12:
color = "light_blue";
break;
case 13:
color = "magenta";
break;
case 14:
color = "orange";
break;
case 15:
color = "white";
break;
default:
return null;
String color = switch (oldType) {
case 0 -> "black";
case 1 -> "red";
case 2 -> "green";
case 3 -> "brown";
case 4 -> "blue";
case 5 -> "purple";
case 6 -> "cyan";
case 7 -> "light_gray";
case 8 -> "gray";
case 9 -> "pink";
case 10 -> "lime";
case 11 -> "yellow";
case 12 -> "light_blue";
case 13 -> "magenta";
case 14 -> "orange";
case 15 -> "white";
default -> null;
};
if (color == null) {
return null;
}
return color + (isWall ? "_wall_banner" : "_banner");
}

View File

@ -19,18 +19,15 @@
package com.sk89q.worldedit.extent.clipboard.io.legacycompat;
import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import org.enginehub.linbus.tree.LinTagType;
import java.util.Map;
@SuppressWarnings("")
public class BedBlockCompatibilityHandler implements NBTCompatibilityHandler {
private static final Property<Direction> FACING_PROPERTY;
@ -51,92 +48,63 @@ public class BedBlockCompatibilityHandler implements NBTCompatibilityHandler {
}
@Override
public <B extends BlockStateHolder<B>> boolean isAffectedBlock(B block) {
return block.getBlockType() == BlockTypes.RED_BED;
}
@Override
public <B extends BlockStateHolder<B>> BlockStateHolder<?> updateNBT(B block, Map<String, Tag> values) {
Tag typeTag = values.get("color");
if (typeTag instanceof IntTag) {
String bedType = convertBedType(((IntTag) typeTag).getValue());
if (bedType != null) {
BlockType type = BlockTypes.get("minecraft:" + bedType);
if (type != null) {
BlockState state = type.getDefaultState();
Property<Direction> facingProp = type.getProperty("facing");
state = state.with(facingProp, block.getState(FACING_PROPERTY));
Property<Boolean> occupiedProp = type.getProperty("occupied");
state = state.with(occupiedProp, false);
Property<String> partProp = type.getProperty("part");
state = state.with(partProp, block.getState(PART_PROPERTY));
values.remove("color");
return state;
}
}
public BaseBlock updateNbt(BaseBlock block) {
if (block.getBlockType() != BlockTypes.RED_BED) {
return block;
}
return block;
var tag = block.getNbt();
if (tag == null) {
return block;
}
var typeTag = tag.findTag("color", LinTagType.intTag());
if (typeTag == null) {
return block;
}
String bedType = convertBedType(typeTag.valueAsInt());
if (bedType == null) {
return block;
}
BlockType type = BlockTypes.get("minecraft:" + bedType);
if (type == null) {
return block;
}
BlockState state = type.getDefaultState();
Property<Direction> facingProp = type.getProperty("facing");
state = state.with(facingProp, block.getState(FACING_PROPERTY));
Property<Boolean> occupiedProp = type.getProperty("occupied");
state = state.with(occupiedProp, false);
Property<String> partProp = type.getProperty("part");
state = state.with(partProp, block.getState(PART_PROPERTY));
var newTag = tag.toBuilder();
newTag.remove("color");
return state.toBaseBlock(LazyReference.computed(newTag.build()));
}
private String convertBedType(int oldType) {
String color;
switch (oldType) {
case 0:
color = "white";
break;
case 1:
color = "orange";
break;
case 2:
color = "magenta";
break;
case 3:
color = "light_blue";
break;
case 4:
color = "yellow";
break;
case 5:
color = "lime";
break;
case 6:
color = "pink";
break;
case 7:
color = "gray";
break;
case 8:
color = "light_gray";
break;
case 9:
color = "cyan";
break;
case 10:
color = "purple";
break;
case 11:
color = "blue";
break;
case 12:
color = "brown";
break;
case 13:
color = "green";
break;
case 14:
color = "red";
break;
case 15:
color = "black";
break;
default:
return null;
}
return color + "_bed";
String color = switch (oldType) {
case 0 -> "white";
case 1 -> "orange";
case 2 -> "magenta";
case 3 -> "light_blue";
case 4 -> "yellow";
case 5 -> "lime";
case 6 -> "pink";
case 7 -> "gray";
case 8 -> "light_gray";
case 9 -> "cyan";
case 10 -> "purple";
case 11 -> "blue";
case 12 -> "brown";
case 13 -> "green";
case 14 -> "red";
case 15 -> "black";
default -> null;
};
return color == null ? null : color + "_bed";
}
}

View File

@ -20,12 +20,48 @@
package com.sk89q.worldedit.extent.clipboard.io.legacycompat;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.internal.util.DeprecationUtil;
import com.sk89q.worldedit.internal.util.NonAbstractForCompatibility;
import com.sk89q.worldedit.world.entity.EntityType;
import org.enginehub.linbus.tree.LinCompoundTag;
public interface EntityNBTCompatibilityHandler {
boolean isAffectedEntity(EntityType type, CompoundTag entityTag);
/**
* Check if this is an entity affected by this handler.
*
* @deprecated this was never used, just return the same tag from
* {@link #updateNbt(EntityType, LinCompoundTag)} if it's not affected
*/
@Deprecated
default boolean isAffectedEntity(EntityType type, CompoundTag entityTag) {
var original = entityTag.toLinTag();
var updated = updateNbt(type, original);
return !original.equals(updated);
}
CompoundTag updateNBT(EntityType type, CompoundTag entityTag);
@Deprecated
default CompoundTag updateNBT(EntityType type, CompoundTag entityTag) {
return new CompoundTag(updateNbt(type, entityTag.toLinTag()));
}
/**
* Given an entity type and data, update the data if needed.
*
* @param type the entity type
* @param entityTag the entity tag
* @return the updated tag, or the same tag if no update was needed
* @apiNote This must be overridden by new subclasses. See {@link NonAbstractForCompatibility}
* for details
*/
@SuppressWarnings("deprecation")
@NonAbstractForCompatibility(
delegateName = "updateNBT",
delegateParams = { EntityType.class, CompoundTag.class }
)
default LinCompoundTag updateNbt(EntityType type, LinCompoundTag entityTag) {
DeprecationUtil.checkDelegatingOverride(getClass());
return updateNBT(type, new CompoundTag(entityTag)).toLinTag();
}
}

View File

@ -19,65 +19,50 @@
package com.sk89q.worldedit.extent.clipboard.io.legacycompat;
import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.registry.LegacyMapper;
import java.util.Map;
import org.enginehub.linbus.tree.LinTagType;
public class FlowerPotCompatibilityHandler implements NBTCompatibilityHandler {
@Override
public <B extends BlockStateHolder<B>> boolean isAffectedBlock(B block) {
return block.getBlockType() == BlockTypes.FLOWER_POT;
}
@Override
public <B extends BlockStateHolder<B>> BlockStateHolder<?> updateNBT(B block, Map<String, Tag> values) {
Tag item = values.get("Item");
if (item instanceof StringTag) {
String id = ((StringTag) item).getValue();
if (id.isEmpty()) {
return BlockTypes.FLOWER_POT.getDefaultState();
}
int data = 0;
Tag dataTag = values.get("Data");
if (dataTag instanceof IntTag) {
data = ((IntTag) dataTag).getValue();
}
BlockState newState = convertLegacyBlockType(id, data);
if (newState != null) {
values.clear();
return newState;
}
public BaseBlock updateNbt(BaseBlock block) {
if (block.getBlockType() != BlockTypes.FLOWER_POT) {
return block;
}
return block;
var tag = block.getNbt();
if (tag == null) {
return block;
}
var item = tag.findTag("Item", LinTagType.stringTag());
if (item == null) {
return block;
}
String id = item.value();
if (id.isEmpty()) {
return BlockTypes.FLOWER_POT.getDefaultState().toBaseBlock();
}
int data = 0;
var dataTag = tag.findTag("Data", LinTagType.intTag());
if (dataTag != null) {
data = dataTag.valueAsInt();
}
BlockState newState = convertLegacyBlockType(id, data);
return newState != null ? newState.toBaseBlock() : block;
}
private BlockState convertLegacyBlockType(String id, int data) {
int newId = 0;
switch (id) {
case "minecraft:red_flower":
newId = 38; // now poppy
break;
case "minecraft:yellow_flower":
newId = 37; // now dandelion
break;
case "minecraft:sapling":
newId = 6; // oak_sapling
break;
case "minecraft:deadbush":
case "minecraft:tallgrass":
newId = 31; // dead_bush with fern and grass (not 32!)
break;
default:
break;
}
int newId = switch (id) {
case "minecraft:red_flower" -> 38; // now poppy
case "minecraft:yellow_flower" -> 37; // now dandelion
case "minecraft:sapling" -> 6; // oak_sapling
case "minecraft:deadbush", "minecraft:tallgrass" ->
31; // dead_bush with fern and grass (not 32!)
default -> 0;
};
String plantedName = null;
if (newId == 0 && id.startsWith("minecraft:")) {
plantedName = id.substring(10);

View File

@ -19,15 +19,80 @@
package com.sk89q.worldedit.extent.clipboard.io.legacycompat;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.internal.util.DeprecationUtil;
import com.sk89q.worldedit.internal.util.NonAbstractForCompatibility;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import org.enginehub.linbus.tree.LinCompoundTag;
import java.util.HashMap;
import java.util.Map;
public interface NBTCompatibilityHandler {
<B extends BlockStateHolder<B>> boolean isAffectedBlock(B block);
/**
* Check if this is a block affected by this handler.
*
* @deprecated this is handled by {@link #updateNbt(BaseBlock)} now
*/
@Deprecated
default <B extends BlockStateHolder<B>> boolean isAffectedBlock(B block) {
BaseBlock state = block.toBaseBlock();
BaseBlock updated = updateNbt(state);
return state != updated;
}
<B extends BlockStateHolder<B>> BlockStateHolder<?> updateNBT(B block, Map<String, Tag> values);
@Deprecated
default <B extends BlockStateHolder<B>> BlockStateHolder<?> updateNBT(B block, Map<String, Tag<?, ?>> values) {
BaseBlock changed = updateNbt(block.toBaseBlock(LazyReference.from(() -> {
var builder = LinCompoundTag.builder();
for (var entry : values.entrySet()) {
builder.put(entry.getKey(), entry.getValue().toLinTag());
}
return builder.build();
})));
CompoundTag data = changed.getNbtData();
values.clear();
if (data != null) {
values.putAll(data.getValue());
}
return changed;
}
/**
* Given a block, update the block's NBT. The NBT may be {@code null}.
*
* @param block the block to update
* @return the updated block, or the same block if no change is necessary
* @apiNote This must be overridden by new subclasses. See {@link NonAbstractForCompatibility}
* for details
*/
@NonAbstractForCompatibility(
delegateName = "updateNBT",
delegateParams = { BlockStateHolder.class, Map.class }
)
@SuppressWarnings("deprecated")
default BaseBlock updateNbt(BaseBlock block) {
DeprecationUtil.checkDelegatingOverride(getClass());
if (!isAffectedBlock(block)) {
return block;
}
if (block.getNbt() == null) {
return block;
}
@SuppressWarnings("deprecation")
Map<String, Tag<?, ?>> values = new HashMap<>(new CompoundTag(block.getNbt()).getValue());
BlockStateHolder<?> changedBlock = updateNBT(block, values);
return changedBlock.toBaseBlock(LazyReference.from(() -> {
var builder = LinCompoundTag.builder();
for (var entry : values.entrySet()) {
builder.put(entry.getKey(), entry.getValue().toLinTag());
}
return builder.build();
}));
}
}

View File

@ -19,18 +19,15 @@
package com.sk89q.worldedit.extent.clipboard.io.legacycompat;
import com.sk89q.jnbt.ByteTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.registry.state.IntegerProperty;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.Map;
import org.enginehub.linbus.tree.LinTagType;
public class NoteBlockCompatibilityHandler implements NBTCompatibilityHandler {
private static final IntegerProperty NoteProperty;
private static final IntegerProperty NOTE_PROPERTY;
static {
IntegerProperty temp;
@ -39,27 +36,25 @@ public class NoteBlockCompatibilityHandler implements NBTCompatibilityHandler {
} catch (NullPointerException | IllegalArgumentException | ClassCastException e) {
temp = null;
}
NoteProperty = temp;
NOTE_PROPERTY = temp;
}
@Override
public <B extends BlockStateHolder<B>> boolean isAffectedBlock(B block) {
return NoteProperty != null && block.getBlockType() == BlockTypes.NOTE_BLOCK;
}
@Override
public <B extends BlockStateHolder<B>> BlockStateHolder<?> updateNBT(B block, Map<String, Tag> values) {
public BaseBlock updateNbt(BaseBlock block) {
if (NOTE_PROPERTY == null || block.getBlockType() != BlockTypes.NOTE_BLOCK) {
return block;
}
var tag = block.getNbt();
if (tag == null) {
return block;
}
// note that instrument was not stored (in state or nbt) previously.
// it will be updated to the block below when it gets set into the world for the first time
Tag noteTag = values.get("note");
if (noteTag instanceof ByteTag) {
Byte note = ((ByteTag) noteTag).getValue();
if (note != null) {
values.clear();
return block.with(NoteProperty, (int) note).toImmutableState();
}
var noteTag = tag.findTag("note", LinTagType.byteTag());
if (noteTag == null) {
return block;
}
return block;
return block.with(NOTE_PROPERTY, (int) noteTag.valueAsByte()).toBaseBlock();
}
}

View File

@ -19,41 +19,31 @@
package com.sk89q.worldedit.extent.clipboard.io.legacycompat;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.CompoundTagBuilder;
import com.sk89q.worldedit.internal.helper.MCDirections;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.world.entity.EntityType;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinNumberTag;
public class Pre13HangingCompatibilityHandler implements EntityNBTCompatibilityHandler {
@Override
public boolean isAffectedEntity(EntityType type, CompoundTag tag) {
if (!type.id().startsWith("minecraft:")) {
return false;
public LinCompoundTag updateNbt(EntityType type, LinCompoundTag tag) {
if (!type.getId().startsWith("minecraft:")) {
return tag;
}
boolean hasLegacyDirection = tag.containsKey("Dir") || tag.containsKey("Direction");
boolean hasFacing = tag.containsKey("Facing");
return hasLegacyDirection || hasFacing;
}
@Override
public CompoundTag updateNBT(EntityType type, CompoundTag tag) {
boolean hasLegacyDir = tag.containsKey("Dir");
boolean hasLegacyDirection = tag.containsKey("Direction");
boolean hasPre113Facing = tag.containsKey("Facing");
Direction newDirection;
if (hasLegacyDir) {
newDirection = MCDirections.fromPre13Hanging(MCDirections.fromLegacyHanging((byte) tag.asInt("Dir")));
} else if (hasLegacyDirection) {
newDirection = MCDirections.fromPre13Hanging(tag.asInt("Direction"));
} else if (hasPre113Facing) {
newDirection = MCDirections.fromPre13Hanging(tag.asInt("Facing"));
if (tag.value().get("Dir") instanceof LinNumberTag<?> legacyDir) {
newDirection = MCDirections.fromPre13Hanging(MCDirections.fromLegacyHanging(legacyDir.value().byteValue()));
} else if (tag.value().get("Direction") instanceof LinNumberTag<?> legacyDirection) {
newDirection = MCDirections.fromPre13Hanging(legacyDirection.value().intValue());
} else if (tag.value().get("Facing") instanceof LinNumberTag<?> legacyFacing) {
newDirection = MCDirections.fromPre13Hanging(legacyFacing.value().intValue());
} else {
return tag;
}
byte hangingByte = (byte) MCDirections.toHanging(newDirection);
CompoundTagBuilder builder = tag.createBuilder();
var builder = tag.toBuilder();
builder.putByte("Facing", hangingByte);
return builder.build();
}

View File

@ -24,50 +24,52 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.internal.util.DeprecationUtil;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import java.util.Map;
import com.sk89q.worldedit.world.block.BaseBlock;
import org.enginehub.linbus.tree.LinStringTag;
import org.enginehub.linbus.tree.LinTagType;
public class SignCompatibilityHandler implements NBTCompatibilityHandler {
@Override
public <B extends BlockStateHolder<B>> boolean isAffectedBlock(B block) {
return DeprecationUtil.isSign(block.getBlockType());
}
@Override
public <B extends BlockStateHolder<B>> BlockStateHolder<?> updateNBT(B block, Map<String, Tag> values) {
public BaseBlock updateNbt(BaseBlock block) {
if (!DeprecationUtil.isSign(block.getBlockType())) {
return block;
}
var tag = block.getNbt();
if (tag == null) {
return block;
}
var newTag = tag.toBuilder();
for (int i = 0; i < 4; ++i) {
String key = "Text" + (i + 1);
Tag value = values.get(key);
if (value instanceof StringTag) {
String storedString = ((StringTag) value).getValue();
JsonElement jsonElement = null;
if (storedString != null && storedString.startsWith("{")) {
try {
jsonElement = new JsonParser().parse(storedString);
} catch (JsonSyntaxException ex) {
// ignore: jsonElement will be null in the next check
}
}
if (jsonElement == null) {
jsonElement = new JsonPrimitive(storedString == null ? "" : storedString);
}
if (jsonElement.isJsonObject()) {
continue;
}
if (jsonElement.isJsonNull()) {
jsonElement = new JsonPrimitive("");
}
JsonObject jsonTextObject = new JsonObject();
jsonTextObject.add("text", jsonElement);
values.put("Text" + (i + 1), new StringTag(jsonTextObject.toString()));
var value = tag.findTag(key, LinTagType.stringTag());
if (value == null) {
continue;
}
String storedString = value.value();
JsonElement jsonElement = null;
if (storedString.startsWith("{")) {
try {
jsonElement = JsonParser.parseString(storedString);
} catch (JsonSyntaxException ex) {
// ignore: jsonElement will be null in the next check
}
}
if (jsonElement == null) {
jsonElement = new JsonPrimitive(storedString);
}
if (jsonElement.isJsonObject()) {
continue;
}
if (jsonElement.isJsonNull()) {
jsonElement = new JsonPrimitive("");
}
JsonObject jsonTextObject = new JsonObject();
jsonTextObject.add("text", jsonElement);
newTag.put("Text" + (i + 1), LinStringTag.of(jsonTextObject.toString()));
}
return block;
}

View File

@ -19,20 +19,17 @@
package com.sk89q.worldedit.extent.clipboard.io.legacycompat;
import com.sk89q.jnbt.ByteTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.Map;
import org.enginehub.linbus.tree.LinTagType;
public class SkullBlockCompatibilityHandler implements NBTCompatibilityHandler {
private static final Property<Direction> FacingProperty;
private static final Property<Direction> FACING_PROPERTY;
static {
Property<Direction> tempFacing;
@ -41,61 +38,70 @@ public class SkullBlockCompatibilityHandler implements NBTCompatibilityHandler {
} catch (NullPointerException | IllegalArgumentException | ClassCastException e) {
tempFacing = null;
}
FacingProperty = tempFacing;
FACING_PROPERTY = tempFacing;
}
@Override
public <B extends BlockStateHolder<B>> boolean isAffectedBlock(B block) {
return block.getBlockType() == BlockTypes.SKELETON_SKULL
|| block.getBlockType() == BlockTypes.SKELETON_WALL_SKULL;
}
@Override
public <B extends BlockStateHolder<B>> BlockStateHolder<?> updateNBT(B block, Map<String, Tag> values) {
boolean isWall = block.getBlockType() == BlockTypes.SKELETON_WALL_SKULL;
Tag typeTag = values.get("SkullType");
if (typeTag instanceof ByteTag) {
String skullType = convertSkullType(((ByteTag) typeTag).getValue(), isWall);
if (skullType != null) {
BlockType type = BlockTypes.get("minecraft:" + skullType);
if (type != null) {
BlockState state = type.getDefaultState();
if (isWall) {
Property<Direction> newProp = type.getProperty("facing");
state = state.with(newProp, block.getState(FacingProperty));
} else {
Tag rotTag = values.get("Rot");
if (rotTag instanceof ByteTag) {
Property<Integer> newProp = type.getProperty("rotation");
state = state.with(newProp, (int) ((ByteTag) rotTag).getValue());
}
}
values.remove("SkullType");
values.remove("Rot");
return state;
}
public BaseBlock updateNbt(BaseBlock block) {
var blockType = block.getBlockType();
boolean isWall = blockType == BlockTypes.SKELETON_WALL_SKULL;
if (blockType != BlockTypes.SKELETON_SKULL && !isWall) {
return block;
}
if (FACING_PROPERTY == null) {
return block;
}
var tag = block.getNbt();
if (tag == null) {
return block;
}
var typeTag = tag.findTag("SkullType", LinTagType.byteTag());
if (typeTag == null) {
return block;
}
String skullType = convertSkullType(typeTag.valueAsByte(), isWall);
if (skullType == null) {
return block;
}
BlockType type = BlockTypes.get("minecraft:" + skullType);
if (type == null) {
return block;
}
BlockState state = type.getDefaultState();
if (isWall) {
Property<Direction> newProp = type.getProperty("facing");
state = state.with(newProp, block.getState(FACING_PROPERTY));
} else {
var rotTag = tag.findTag("Rot", LinTagType.byteTag());
if (rotTag != null) {
Property<Integer> newProp = type.getProperty("rotation");
state = state.with(newProp, (int) rotTag.valueAsByte());
}
}
return block;
var newTag = tag.toBuilder()
.remove("SkullType")
.remove("Rot")
.build();
return state.toBaseBlock(newTag);
}
private String convertSkullType(Byte oldType, boolean isWall) {
switch (oldType) {
case 0:
return isWall ? "skeleton_wall_skull" : "skeleton_skull";
case 1:
return isWall ? "wither_skeleton_wall_skull" : "wither_skeleton_skull";
case 2:
return isWall ? "zombie_wall_head" : "zombie_head";
case 3:
return isWall ? "player_wall_head" : "player_head";
case 4:
return isWall ? "creeper_wall_head" : "creeper_head";
case 5:
return isWall ? "dragon_wall_head" : "dragon_head";
default:
return null;
private String convertSkullType(byte oldType, boolean isWall) {
record SkullData(String kind, String suffix) {
}
var skullData = switch (oldType) {
case 0 -> new SkullData("skeleton", "skull");
case 1 -> new SkullData("wither_skeleton", "skull");
case 2 -> new SkullData("zombie", "head");
case 3 -> new SkullData("player", "head");
case 4 -> new SkullData("creeper", "head");
case 5 -> new SkullData("dragon", "head");
default -> null;
};
if (skullData == null) {
return null;
}
return skullData.kind + (isWall ? "_wall" : "") + "_" + skullData.suffix;
}
}

View File

@ -401,7 +401,7 @@ public class BlockTransformExtent extends ResettableExtent {
);
if (newDirection != null) {
Map<String, Tag> values = new HashMap<>(tag.getValue());
Map<String, Tag<?, ?>> values = new HashMap<>(tag.getValue());
values.put("Rot", new ByteTag((byte) MCDirections.toRotation(newDirection)));
tag = new CompoundTag(values);
}

View File

@ -26,9 +26,9 @@ import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.extent.AbstractDelegateExtent;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import org.enginehub.linbus.tree.LinCompoundTag;
import java.util.Collection;
@ -115,9 +115,7 @@ public class SurvivalModeExtent extends AbstractDelegateExtent {
} else {
// Can't be an inlined check due to inconsistent generic return type
if (stripNbt) {
//FAWE start - Use CompoundBinaryTag
return super.setBlock(location, block.toBaseBlock((CompoundBinaryTag) null));
//FAWE end
return super.setBlock(location, block.toBaseBlock((LinCompoundTag) null));
} else {
return super.setBlock(location, block);
}

View File

@ -28,10 +28,9 @@ import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.math.transform.Transform;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.Direction.Flag;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.NumberBinaryTag;
import com.sk89q.worldedit.world.block.BaseBlock;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinTag;
import static com.google.common.base.Preconditions.checkNotNull;
@ -88,14 +87,13 @@ public class ExtentBlockCopy implements RegionFunction {
* @return a new state or the existing one
*/
private BaseBlock transformNbtData(BaseBlock state) {
//FAWE start - Replace CompoundTag with CompoundBinaryTag
CompoundBinaryTag tag = state.getNbt();
LinCompoundTag tag = state.getNbt();
if (tag != null) {
// Handle blocks which store their rotation in NBT
BinaryTag rotTag = tag.get("Rot");
if (rotTag instanceof NumberBinaryTag) {
int rot = ((NumberBinaryTag) rotTag).intValue();
LinTag<?> rotTag = tag.value().get("Rot");
if (rotTag.value() instanceof Number number) {
int rot = number.intValue();
Direction direction = MCDirections.fromRotation(rot);
@ -105,8 +103,9 @@ public class ExtentBlockCopy implements RegionFunction {
if (newDirection != null) {
return state.toBaseBlock(
tag.putByte("Rot", (byte) MCDirections.toRotation(newDirection))
//FAWE end
tag.toBuilder()
.putByte("Rot", (byte) MCDirections.toRotation(newDirection))
.build()
);
}
}

View File

@ -29,9 +29,9 @@ import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockTypes;
import org.enginehub.linbus.tree.LinCompoundTag;
import javax.annotation.Nullable;
@ -135,9 +135,6 @@ public class ServerCUIHandler {
Math.min(Math.min(player.getWorld().getMaxY(), posY + MAX_DISTANCE), posY + 3)
);
//FAWE start - CBT > Map<String, Tag>
CompoundBinaryTag.Builder structureTag = CompoundBinaryTag.builder();
posX -= x;
posY -= y;
posZ -= z;
@ -147,7 +144,7 @@ public class ServerCUIHandler {
return null;
}
//FAWE start - see comment of CBT
LinCompoundTag.Builder structureTag = LinCompoundTag.builder();
structureTag.putString("name", "worldedit:" + player.getName());
structureTag.putString("author", player.getName());
structureTag.putString("metadata", "");

View File

@ -19,17 +19,14 @@
package com.sk89q.worldedit.internal.wna;
import com.google.common.collect.ImmutableMap;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.IntBinaryTag;
import com.sk89q.worldedit.util.nbt.StringBinaryTag;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import org.enginehub.linbus.tree.LinCompoundTag;
import javax.annotation.Nullable;
@ -68,17 +65,15 @@ public interface WorldNativeAccess<NC, NBS, NP> {
// Create the TileEntity
if (successful || old == newState) {
if (block instanceof BaseBlock) {
BaseBlock baseBlock = (BaseBlock) block;
//FAWE start - use CompoundBinaryTag over CompoundTag
CompoundBinaryTag tag = baseBlock.getNbt();
if (block instanceof BaseBlock baseBlock) {
LinCompoundTag tag = baseBlock.getNbt();
if (tag != null) {
tag = tag.put(ImmutableMap.of(
"id", StringBinaryTag.of(baseBlock.getNbtId()),
"x", IntBinaryTag.of(position.x()),
"y", IntBinaryTag.of(position.y()),
"z", IntBinaryTag.of(position.z())
));
tag = tag.toBuilder()
.putString("id", baseBlock.getNbtId())
.putInt("x", position.getX())
.putInt("y", position.getY())
.putInt("z", position.getZ())
.build();
// update if TE changed as well
successful = updateTileEntity(pos, tag);
@ -143,7 +138,7 @@ public interface WorldNativeAccess<NC, NBS, NP> {
void updateLightingForBlock(NP position);
boolean updateTileEntity(NP position, CompoundBinaryTag tag);
boolean updateTileEntity(NP position, LinCompoundTag tag);
void notifyBlockUpdate(NC chunk, NP position, NBS oldState, NBS newState);

View File

@ -20,8 +20,7 @@
package com.sk89q.worldedit.world;
import com.google.common.annotations.Beta;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import org.enginehub.linbus.tree.LinCompoundTag;
/**
* This entire class is subject to heavy changes. Do not use this as API.
@ -41,15 +40,12 @@ public interface DataFixer {
private FixTypes() {
}
//FAWE start - BinaryTag
public static FixType<CompoundBinaryTag> CHUNK = new FixType<>();
public static FixType<CompoundBinaryTag> BLOCK_ENTITY = new FixType<>();
public static FixType<CompoundBinaryTag> ENTITY = new FixType<>();
//FAWE end
public static FixType<String> BLOCK_STATE = new FixType<>();
public static FixType<String> BIOME = new FixType<>();
public static FixType<String> ITEM_TYPE = new FixType<>();
public static final FixType<LinCompoundTag> CHUNK = new FixType<>();
public static final FixType<LinCompoundTag> BLOCK_ENTITY = new FixType<>();
public static final FixType<LinCompoundTag> ENTITY = new FixType<>();
public static final FixType<String> BLOCK_STATE = new FixType<>();
public static final FixType<String> BIOME = new FixType<>();
public static final FixType<String> ITEM_TYPE = new FixType<>();
}
default <T> T fixUp(FixType<T> type, T original) {

View File

@ -23,7 +23,7 @@ import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.internal.util.DeprecationUtil;
import com.sk89q.worldedit.internal.util.NonAbstractForCompatibility;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import org.enginehub.linbus.tree.LinCompoundTag;
import javax.annotation.Nullable;
@ -66,7 +66,7 @@ public interface NbtValued {
@Deprecated
@Nullable
default CompoundTag getNbtData() {
CompoundBinaryTag tag = getNbt();
LinCompoundTag tag = getNbt();
return tag == null ? null : new CompoundTag(tag);
}
@ -78,7 +78,7 @@ public interface NbtValued {
*/
@Deprecated
default void setNbtData(@Nullable CompoundTag nbtData) {
setNbtReference(nbtData == null ? null : LazyReference.from(nbtData::asBinaryTag));
setNbtReference(nbtData == null ? null : LazyReference.from(nbtData::toLinTag));
}
/**
@ -96,11 +96,12 @@ public interface NbtValued {
delegateParams = {}
)
@Nullable
default LazyReference<CompoundBinaryTag> getNbtReference() {
default LazyReference<LinCompoundTag> getNbtReference() {
DeprecationUtil.checkDelegatingOverride(getClass());
@SuppressWarnings("deprecation")
CompoundTag nbtData = getNbtData();
return nbtData == null ? null : LazyReference.from(nbtData::asBinaryTag);
return nbtData == null ? null : LazyReference.from(nbtData::toLinTag);
}
/**
@ -109,8 +110,8 @@ public interface NbtValued {
* @return compound tag, or null
*/
@Nullable
default CompoundBinaryTag getNbt() {
LazyReference<CompoundBinaryTag> ref = getNbtReference();
default LinCompoundTag getNbt() {
LazyReference<LinCompoundTag> ref = getNbtReference();
return ref == null ? null : ref.getValue();
}
@ -119,11 +120,12 @@ public interface NbtValued {
*
* @param nbtData NBT data, or null if no data
*/
@SuppressWarnings("deprecation")
@NonAbstractForCompatibility(
delegateName = "setNbtData",
delegateParams = {CompoundTag.class}
)
default void setNbtReference(@Nullable LazyReference<CompoundBinaryTag> nbtData) {
default void setNbtReference(@Nullable LazyReference<LinCompoundTag> nbtData) {
DeprecationUtil.checkDelegatingOverride(getClass());
setNbtData(nbtData == null ? null : new CompoundTag(nbtData.getValue()));
@ -134,7 +136,7 @@ public interface NbtValued {
*
* @param nbtData NBT data, or null if no data
*/
default void setNbt(@Nullable CompoundBinaryTag nbtData) {
default void setNbt(@Nullable LinCompoundTag nbtData) {
setNbtReference(nbtData == null ? null : LazyReference.computed(nbtData));
}
//FAWE end

View File

@ -21,7 +21,6 @@ package com.sk89q.worldedit.world.block;
import com.fastasyncworldedit.core.registry.state.PropertyKey;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.TileEntityBlock;
import com.sk89q.worldedit.extent.Extent;
@ -29,13 +28,13 @@ import com.sk89q.worldedit.extent.OutputExtent;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.TagStringIO;
import com.sk89q.worldedit.world.registry.BlockMaterial;
import com.sk89q.worldedit.world.registry.LegacyMapper;
import org.enginehub.linbus.format.snbt.LinStringIO;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinTagType;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
@ -54,7 +53,7 @@ public class BaseBlock implements BlockStateHolder<BaseBlock>, TileEntityBlock {
private final BlockState blockState;
@Nullable
private final LazyReference<CompoundBinaryTag> nbtData;
private final LazyReference<LinCompoundTag> nbtData;
//FAWE start
@ -93,7 +92,7 @@ public class BaseBlock implements BlockStateHolder<BaseBlock>, TileEntityBlock {
*/
@Deprecated
public BaseBlock(BlockState state, CompoundTag nbtData) {
this(state, LazyReference.from(checkNotNull(nbtData)::asBinaryTag));
this(state, LazyReference.from(checkNotNull(nbtData)::toLinTag));
}
//FAWE end
@ -104,7 +103,7 @@ public class BaseBlock implements BlockStateHolder<BaseBlock>, TileEntityBlock {
* @param state The block state
* @param nbtData NBT data, which must be provided
*/
protected BaseBlock(BlockState state, LazyReference<CompoundBinaryTag> nbtData) {
protected BaseBlock(BlockState state, LazyReference<LinCompoundTag> nbtData) {
checkNotNull(nbtData);
this.blockState = state;
this.nbtData = nbtData;
@ -165,21 +164,21 @@ public class BaseBlock implements BlockStateHolder<BaseBlock>, TileEntityBlock {
@Override
public String getNbtId() {
LazyReference<CompoundBinaryTag> nbtData = this.nbtData;
LazyReference<LinCompoundTag> nbtData = this.nbtData;
if (nbtData == null) {
return "";
}
return nbtData.getValue().getString("id");
return nbtData.getValue().getTag("id", LinTagType.stringTag()).value();
}
@Nullable
@Override
public LazyReference<CompoundBinaryTag> getNbtReference() {
public LazyReference<LinCompoundTag> getNbtReference() {
return this.nbtData;
}
@Override
public void setNbtReference(@Nullable LazyReference<CompoundBinaryTag> nbtData) {
public void setNbtReference(@Nullable LazyReference<LinCompoundTag> nbtData) {
throw new UnsupportedOperationException("This class is immutable.");
}
@ -244,7 +243,7 @@ public class BaseBlock implements BlockStateHolder<BaseBlock>, TileEntityBlock {
}
@Override
public BaseBlock toBaseBlock(LazyReference<CompoundBinaryTag> compoundTag) {
public BaseBlock toBaseBlock(LazyReference<LinCompoundTag> compoundTag) {
if (compoundTag == null) {
return this.blockState.toBaseBlock();
} else if (compoundTag == this.nbtData) {
@ -300,20 +299,20 @@ public class BaseBlock implements BlockStateHolder<BaseBlock>, TileEntityBlock {
@Override
public int hashCode() {
return getOrdinal();
int ret = getOrdinal() << 3;
LinCompoundTag nbtData = getNbt();
if (nbtData != null) {
ret += nbtData.hashCode();
}
return ret;
}
//FAWE end
@Override
public String toString() {
String nbtString = "";
CompoundBinaryTag nbtData = getNbt();
if (nbtData != null) {
try {
nbtString = TagStringIO.get().asString(nbtData);
} catch (IOException e) {
WorldEdit.logger.error("Failed to serialize NBT of Block", e);
}
nbtString = LinStringIO.writeToString(nbtData.getValue());
}
return blockState.getAsString() + nbtString;

View File

@ -45,8 +45,8 @@ import com.sk89q.worldedit.registry.state.AbstractProperty;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.registry.BlockMaterial;
import org.enginehub.linbus.tree.LinCompoundTag;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@ -420,7 +420,7 @@ public class BlockState implements BlockStateHolder<BlockState>, Pattern {
//FAWE end
@Override
public BaseBlock toBaseBlock(LazyReference<CompoundBinaryTag> compoundTag) {
public BaseBlock toBaseBlock(LazyReference<LinCompoundTag> compoundTag) {
if (compoundTag == null) {
return toBaseBlock();
}

View File

@ -30,8 +30,8 @@ import com.sk89q.worldedit.internal.util.NonAbstractForCompatibility;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.registry.BlockMaterial;
import org.enginehub.linbus.tree.LinCompoundTag;
import java.util.Locale;
import java.util.Map;
@ -158,7 +158,7 @@ public interface BlockStateHolder<B extends BlockStateHolder<B>> extends TileEnt
*/
@Deprecated
default BaseBlock toBaseBlock(CompoundTag compoundTag) {
return toBaseBlock(compoundTag == null ? null : LazyReference.from(compoundTag::asBinaryTag));
return toBaseBlock(compoundTag == null ? null : LazyReference.from(compoundTag::toLinTag));
}
/**
@ -169,11 +169,12 @@ public interface BlockStateHolder<B extends BlockStateHolder<B>> extends TileEnt
* This must be overridden by new subclasses. See {@link NonAbstractForCompatibility}
* for details
*/
@SuppressWarnings("deprecation")
@NonAbstractForCompatibility(
delegateName = "toBaseBlock",
delegateParams = {CompoundTag.class}
)
default BaseBlock toBaseBlock(LazyReference<CompoundBinaryTag> compoundTag) {
default BaseBlock toBaseBlock(LazyReference<LinCompoundTag> compoundTag) {
DeprecationUtil.checkDelegatingOverride(getClass());
return toBaseBlock(compoundTag == null ? null : new CompoundTag(compoundTag.getValue()));
@ -185,7 +186,7 @@ public interface BlockStateHolder<B extends BlockStateHolder<B>> extends TileEnt
* @param compoundTag The NBT Data to apply
* @return The BaseBlock
*/
default BaseBlock toBaseBlock(CompoundBinaryTag compoundTag) {
default BaseBlock toBaseBlock(LinCompoundTag compoundTag) {
return toBaseBlock(compoundTag == null ? null : LazyReference.computed(compoundTag));
}

View File

@ -19,21 +19,20 @@
package com.sk89q.worldedit.world.chunk;
import com.fastasyncworldedit.core.util.NbtUtils;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.BinaryTagTypes;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.IntBinaryTag;
import com.sk89q.worldedit.util.nbt.ListBinaryTag;
import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.registry.LegacyMapper;
import com.sk89q.worldedit.world.storage.InvalidFormatException;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinIntTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinTag;
import org.enginehub.linbus.tree.LinTagType;
import javax.annotation.Nullable;
import java.util.HashMap;
@ -41,25 +40,25 @@ import java.util.Map;
public class AnvilChunk implements Chunk {
private final CompoundBinaryTag rootTag;
private final LinCompoundTag rootTag;
private final byte[][] blocks;
private final byte[][] blocksAdd;
private final byte[][] data;
private final int rootX;
private final int rootZ;
private Map<BlockVector3, CompoundBinaryTag> tileEntities;
private Map<BlockVector3, LinCompoundTag> tileEntities;
/**
* Construct the chunk with a compound tag.
*
* @param tag the tag to read
* @throws DataException on a data error
* @deprecated Use {@link #AnvilChunk(CompoundBinaryTag)}
* @deprecated Use {@link #AnvilChunk(LinCompoundTag)}
*/
@Deprecated
public AnvilChunk(CompoundTag tag) throws DataException {
this(tag.asBinaryTag());
this(tag.toLinTag());
}
/**
@ -68,45 +67,40 @@ public class AnvilChunk implements Chunk {
* @param tag the tag to read
* @throws DataException on a data error
*/
public AnvilChunk(CompoundBinaryTag tag) throws DataException {
public AnvilChunk(LinCompoundTag tag) throws DataException {
rootTag = tag;
rootX = NbtUtils.getChildTag(rootTag, "xPos", BinaryTagTypes.INT).value();
rootZ = NbtUtils.getChildTag(rootTag, "zPos", BinaryTagTypes.INT).value();
rootX = rootTag.getTag("xPos", LinTagType.intTag()).value();
rootZ = rootTag.getTag("zPos", LinTagType.intTag()).value();
blocks = new byte[16][16 * 16 * 16];
blocksAdd = new byte[16][16 * 16 * 8];
data = new byte[16][16 * 16 * 8];
ListBinaryTag sections = NbtUtils.getChildTag(rootTag, "Sections", BinaryTagTypes.LIST);
LinListTag<LinTag<?>> sections = rootTag.getTag("Sections", LinTagType.listTag());
for (BinaryTag rawSectionTag : sections) {
if (!(rawSectionTag instanceof CompoundBinaryTag)) {
for (LinTag<?> rawSectionTag : sections.value()) {
if (!(rawSectionTag instanceof LinCompoundTag sectionTag)) {
continue;
}
CompoundBinaryTag sectionTag = (CompoundBinaryTag) rawSectionTag;
if (sectionTag.get("Y") == null) {
var sectionYTag = sectionTag.findTag("Y", LinTagType.byteTag());
if (sectionYTag == null) {
continue; // Empty section.
}
int y = NbtUtils.getChildTag(sectionTag, "Y", BinaryTagTypes.BYTE).value();
int y = sectionYTag.value();
if (y < 0 || y >= 16) {
continue;
}
blocks[y] = NbtUtils.getChildTag(sectionTag,
"Blocks", BinaryTagTypes.BYTE_ARRAY
).value();
data[y] = NbtUtils.getChildTag(sectionTag, "Data",
BinaryTagTypes.BYTE_ARRAY
).value();
blocks[y] = sectionTag.getTag("Blocks", LinTagType.byteArrayTag()).value();
data[y] = sectionTag.getTag("Data", LinTagType.byteArrayTag()).value();
// 4096 ID block support
if (sectionTag.get("Add") != null) {
blocksAdd[y] = NbtUtils.getChildTag(sectionTag,
"Add", BinaryTagTypes.BYTE_ARRAY
).value();
var addTag = sectionTag.findTag("Add", LinTagType.byteArrayTag());
if (addTag != null) {
blocksAdd[y] = addTag.value();
}
}
@ -144,17 +138,12 @@ public class AnvilChunk implements Chunk {
int index = x + (z * 16 + (yindex * 16 * 16));
try {
int addId = 0;
// The block ID is the combination of the Blocks byte array with the
// Add byte array. 'Blocks' stores the lowest 8 bits of a block's ID, and
// 'Add' stores the highest 4 bits of the ID. The first block is stored
// in the lowest nibble in the Add byte array.
if (index % 2 == 0) {
addId = (blocksAdd[section][index >> 1] & 0x0F) << 8;
} else {
addId = (blocksAdd[section][index >> 1] & 0xF0) << 4;
}
byte addByte = blocksAdd[section][index >> 1];
int addId = (index & 1) == 0 ? (addByte & 0x0F) << 8 : (addByte & 0xF0) << 4;
return (blocks[section][index] & 0xFF) + addId;
} catch (IndexOutOfBoundsException e) {
@ -175,15 +164,12 @@ public class AnvilChunk implements Chunk {
}
int index = x + (z * 16 + (yIndex * 16 * 16));
boolean shift = index % 2 == 0;
index /= 2;
boolean shift = (index & 1) != 0;
index >>= 2;
try {
if (!shift) {
return (data[section][index] & 0xF0) >> 4;
} else {
return data[section][index] & 0xF;
}
byte dataByte = data[section][index];
return shift ? (dataByte & 0xF0) >> 4 : dataByte & 0x0F;
} catch (IndexOutOfBoundsException e) {
throw new DataException("Chunk does not contain position " + position);
}
@ -192,44 +178,40 @@ public class AnvilChunk implements Chunk {
/**
* Used to load the tile entities.
*/
private void populateTileEntities() throws DataException {
ListBinaryTag tags = NbtUtils.getChildTag(rootTag, "TileEntities", BinaryTagTypes.LIST);
private void populateTileEntities() {
LinListTag<LinCompoundTag> tags = rootTag.getTag("TileEntities", LinTagType.listTag())
.asTypeChecked(LinTagType.compoundTag());
tileEntities = new HashMap<>();
for (BinaryTag tag : tags) {
if (!(tag instanceof CompoundBinaryTag)) {
throw new InvalidFormatException("CompoundTag expected in TileEntities");
}
CompoundBinaryTag t = (CompoundBinaryTag) tag;
tileEntities = new HashMap<>(tags.value().size());
for (LinCompoundTag t : tags.value()) {
int x = 0;
int y = 0;
int z = 0;
CompoundBinaryTag.Builder values = CompoundBinaryTag.builder();
LinCompoundTag.Builder values = LinCompoundTag.builder();
for (String key : t.keySet()) {
BinaryTag value = t.get(key);
for (String key : t.value().keySet()) {
LinTag<?> value = t.value().get(key);
switch (key) {
case "x":
if (value instanceof IntBinaryTag) {
x = ((IntBinaryTag) value).value();
case "x" -> {
if (value instanceof LinIntTag v) {
x = v.valueAsInt();
}
break;
case "y":
if (value instanceof IntBinaryTag) {
y = ((IntBinaryTag) value).value();
}
case "y" -> {
if (value instanceof LinIntTag v) {
y = v.valueAsInt();
}
break;
case "z":
if (value instanceof IntBinaryTag) {
z = ((IntBinaryTag) value).value();
}
case "z" -> {
if (value instanceof LinIntTag v) {
z = v.valueAsInt();
}
break;
default:
break;
}
default -> {
// Do nothing.
}
}
values.put(key, value);
@ -250,14 +232,12 @@ public class AnvilChunk implements Chunk {
* @throws DataException thrown if there is a data error
*/
@Nullable
private CompoundBinaryTag getBlockTileEntity(BlockVector3 position) throws DataException {
private LinCompoundTag getBlockTileEntity(BlockVector3 position) throws DataException {
if (tileEntities == null) {
populateTileEntities();
}
CompoundBinaryTag values = tileEntities.get(position);
return values;
return tileEntities.get(position);
}
@Override
@ -270,7 +250,7 @@ public class AnvilChunk implements Chunk {
WorldEdit.logger.warn("Unknown legacy block " + id + ":" + data + " found when loading legacy anvil chunk.");
return BlockTypes.AIR.getDefaultState().toBaseBlock();
}
CompoundBinaryTag tileEntity = getBlockTileEntity(position);
LinCompoundTag tileEntity = getBlockTileEntity(position);
if (tileEntity != null) {
return state.toBaseBlock(tileEntity);

View File

@ -19,17 +19,12 @@
package com.sk89q.worldedit.world.chunk;
import com.fastasyncworldedit.core.util.NbtUtils;
import com.google.common.collect.ImmutableMap;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.BinaryTagTypes;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.IntBinaryTag;
import com.sk89q.worldedit.util.nbt.ListBinaryTag;
import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
@ -39,10 +34,14 @@ import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.entity.EntityTypes;
import com.sk89q.worldedit.world.storage.InvalidFormatException;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinIntArrayTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinTag;
import org.enginehub.linbus.tree.LinTagType;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -51,26 +50,28 @@ import java.util.Map;
*/
public class AnvilChunk13 implements Chunk {
protected final CompoundBinaryTag rootTag;
protected final LinCompoundTag rootTag;
private final BlockState[][] blocks;
//FAWE start - biome and entity restore
protected BiomeType[] biomes;
//FAWE end
private Map<BlockVector3, CompoundBinaryTag> tileEntities;
//FAWE start - biome and entity restore
private List<BaseEntity> entities;
//FAWE end
private Map<BlockVector3, LinCompoundTag> tileEntities;
private final int rootX;
private final int rootZ;
/**
* Construct the chunk with a compound tag.
*
* @param tag the tag to read
* @throws DataException on a data error
* @deprecated Use {@link #AnvilChunk13(CompoundBinaryTag)}
* @deprecated Use {@link #AnvilChunk13(LinCompoundTag)}
*/
@Deprecated
public AnvilChunk13(CompoundTag tag) throws DataException {
this(tag.asBinaryTag());
this(tag.toLinTag());
}
/**
@ -79,53 +80,58 @@ public class AnvilChunk13 implements Chunk {
* @param tag the tag to read
* @throws DataException on a data error
*/
public AnvilChunk13(CompoundBinaryTag tag) throws DataException {
public AnvilChunk13(LinCompoundTag tag) throws DataException {
rootTag = tag;
rootX = rootTag.getTag("xPos", LinTagType.intTag()).valueAsInt();
rootZ = rootTag.getTag("zPos", LinTagType.intTag()).valueAsInt();
blocks = new BlockState[16][];
ListBinaryTag sections = NbtUtils.getChildTag(rootTag, "Sections", BinaryTagTypes.LIST);
LinListTag<LinTag<?>> sections = rootTag.getTag("Sections", LinTagType.listTag());
for (BinaryTag rawSectionTag : sections) {
if (!(rawSectionTag instanceof CompoundBinaryTag)) {
for (LinTag<?> rawSectionTag : sections.value()) {
if (!(rawSectionTag instanceof LinCompoundTag sectionTag)) {
continue;
}
CompoundBinaryTag sectionTag = (CompoundBinaryTag) rawSectionTag;
if (sectionTag.get("Y") == null) {
var sectionYTag = sectionTag.findTag("Y", LinTagType.byteTag());
if (sectionYTag == null) {
continue; // Empty section.
}
int y = NbtUtils.getChildTag(sectionTag, "Y", BinaryTagTypes.BYTE).value();
int y = sectionYTag.value();
if (y < 0 || y >= 16) {
continue;
}
// parse palette
ListBinaryTag paletteEntries = sectionTag.getList("Palette", BinaryTagTypes.COMPOUND);
int paletteSize = paletteEntries.size();
LinListTag<LinCompoundTag> paletteEntries = sectionTag.getTag(
"Palette", LinTagType.listTag()
).asTypeChecked(LinTagType.compoundTag());
int paletteSize = paletteEntries.value().size();
if (paletteSize == 0) {
continue;
}
BlockState[] palette = new BlockState[paletteSize];
for (int paletteEntryId = 0; paletteEntryId < paletteSize; paletteEntryId++) {
CompoundBinaryTag paletteEntry = (CompoundBinaryTag) paletteEntries.get(paletteEntryId);
BlockType type = BlockTypes.get(paletteEntry.getString("Name"));
LinCompoundTag paletteEntry = paletteEntries.get(paletteEntryId);
String blockType = paletteEntry.getTag("Name", LinTagType.stringTag()).value();
BlockType type = BlockTypes.get(blockType);
if (type == null) {
throw new InvalidFormatException("Invalid block type: " + paletteEntry.getString("Name"));
throw new InvalidFormatException("Invalid block type: " + blockType);
}
BlockState blockState = type.getDefaultState();
if (paletteEntry.get("Properties") != null) {
CompoundBinaryTag properties = NbtUtils.getChildTag(paletteEntry, "Properties", BinaryTagTypes.COMPOUND);
var propertiesTag = paletteEntry.findTag("Properties", LinTagType.compoundTag());
if (propertiesTag != null) {
for (Property<?> property : blockState.getStates().keySet()) {
if (properties.get(property.getName()) != null) {
String value = properties.getString(property.getName());
var propertyName = propertiesTag.findTag(property.getName(), LinTagType.stringTag());
if (propertyName != null) {
String value = propertyName.value();
try {
blockState = getBlockStateWith(blockState, property, value);
} catch (IllegalArgumentException e) {
throw new InvalidFormatException("Invalid block state for " + blockState
.getBlockType()
.id() + ", " + property.getName() + ": " + value);
throw new InvalidFormatException("Invalid block state for " + blockState.getBlockType().id() + ", " + property.getName() + ": " + value);
}
}
}
@ -134,7 +140,7 @@ public class AnvilChunk13 implements Chunk {
}
// parse block states
long[] blockStatesSerialized = NbtUtils.getChildTag(sectionTag, "BlockStates", BinaryTagTypes.LONG_ARRAY).value();
long[] blockStatesSerialized = sectionTag.getTag("BlockStates", LinTagType.longArrayTag()).value();
BlockState[] chunkSectionBlocks = new BlockState[16 * 16 * 16];
blocks[y] = chunkSectionBlocks;
@ -143,8 +149,7 @@ public class AnvilChunk13 implements Chunk {
}
}
protected void readBlockStates(BlockState[] palette, long[] blockStatesSerialized, BlockState[] chunkSectionBlocks) throws
InvalidFormatException {
protected void readBlockStates(BlockState[] palette, long[] blockStatesSerialized, BlockState[] chunkSectionBlocks) throws InvalidFormatException {
int paletteBits = 4;
while ((1 << paletteBits) < palette.length) {
++paletteBits;
@ -163,7 +168,7 @@ public class AnvilChunk13 implements Chunk {
throw new InvalidFormatException("Too short block state table");
}
currentSerializedValue = blockStatesSerialized[nextSerializedItem++];
localBlockId |= (int) ((currentSerializedValue & ((1 << bitsNextLong) - 1)) << remainingBits);
localBlockId |= (int) (currentSerializedValue & ((1L << bitsNextLong) - 1)) << remainingBits;
currentSerializedValue >>>= bitsNextLong;
remainingBits = 64 - bitsNextLong;
} else {
@ -185,27 +190,23 @@ public class AnvilChunk13 implements Chunk {
/**
* Used to load the tile entities.
*/
private void populateTileEntities() throws DataException {
tileEntities = new HashMap<>();
if (rootTag.get("TileEntities") == null) {
return;
private Map<BlockVector3, LinCompoundTag> populateTileEntities() {
LinListTag<LinCompoundTag> tags = rootTag.findListTag(
"TileEntities", LinTagType.compoundTag()
);
if (tags == null) {
return ImmutableMap.of();
}
ListBinaryTag tags = NbtUtils.getChildTag(rootTag, "TileEntities", BinaryTagTypes.LIST);
for (BinaryTag tag : tags) {
if (!(tag instanceof CompoundBinaryTag)) {
throw new InvalidFormatException("CompoundTag expected in TileEntities");
}
CompoundBinaryTag t = (CompoundBinaryTag) tag;
int x = ((IntBinaryTag) t.get("x")).value();
int y = ((IntBinaryTag) t.get("y")).value();
int z = ((IntBinaryTag) t.get("z")).value();
var tileEntities = ImmutableMap.<BlockVector3, LinCompoundTag>builderWithExpectedSize(tags.value().size());
for (LinCompoundTag tag : tags.value()) {
int x = tag.getTag("x", LinTagType.intTag()).valueAsInt();
int y = tag.getTag("y", LinTagType.intTag()).valueAsInt();
int z = tag.getTag("z", LinTagType.intTag()).valueAsInt();
BlockVector3 vec = BlockVector3.at(x, y, z);
tileEntities.put(vec, t);
tileEntities.put(vec, tag);
}
return tileEntities.build();
}
/**
@ -215,26 +216,21 @@ public class AnvilChunk13 implements Chunk {
*
* @param position the position
* @return the compound tag for that position, which may be null
* @throws DataException thrown if there is a data error
*/
@Nullable
private CompoundBinaryTag getBlockTileEntity(BlockVector3 position) throws DataException {
private LinCompoundTag getBlockTileEntity(BlockVector3 position) {
if (tileEntities == null) {
populateTileEntities();
this.tileEntities = populateTileEntities();
}
CompoundBinaryTag values = tileEntities.get(position);
return values;
return tileEntities.get(position);
}
@Override
public BaseBlock getBlock(BlockVector3 position) throws DataException {
//FAWE start - simplified
int x = position.x() & 15;
int x = position.x() - rootX * 16;
int y = position.y();
int z = position.z() & 15;
//FAWE end
int z = position.z() - rootZ * 16;
int section = y >> 4;
int yIndex = y & 0x0F;
@ -246,15 +242,10 @@ public class AnvilChunk13 implements Chunk {
BlockState[] sectionBlocks = blocks[section];
BlockState state = sectionBlocks != null ? sectionBlocks[(yIndex << 8) | (z << 4) | x] : BlockTypes.AIR.getDefaultState();
CompoundBinaryTag tileEntity = getBlockTileEntity(position);
LinCompoundTag tileEntity = getBlockTileEntity(position);
if (tileEntity != null) {
return state.toBaseBlock(tileEntity);
}
return state.toBaseBlock();
}
//FAWE start - biome and entity restore
return state.toBaseBlock(tileEntity);
} //FAWE start - biome and entity restore
@Override
public BiomeType getBiome(final BlockVector3 position) throws DataException {
@ -277,21 +268,20 @@ public class AnvilChunk13 implements Chunk {
/**
* Used to load the biomes.
*/
private void populateEntities() throws DataException {
private void populateEntities() {
entities = new ArrayList<>();
if (rootTag.get("Entities") == null) {
LinListTag<LinCompoundTag> tags = rootTag.findListTag(
"Entities", LinTagType.compoundTag()
);
if (tags == null) {
return;
}
ListBinaryTag tags = NbtUtils.getChildTag(rootTag, "Entities", BinaryTagTypes.LIST);
for (BinaryTag tag : tags) {
if (!(tag instanceof CompoundBinaryTag)) {
throw new InvalidFormatException("CompoundTag expected in Entities");
}
CompoundBinaryTag t = (CompoundBinaryTag) tag;
entities.add(new BaseEntity(EntityTypes.get(t.getString("id")), LazyReference.computed(t)));
for (LinCompoundTag tag : tags.value()) {
entities.add(new BaseEntity(
EntityTypes.get(tag.getTag("id", LinTagType.stringTag()).value()),
LazyReference.computed(tag)
));
}
}
@ -299,12 +289,13 @@ public class AnvilChunk13 implements Chunk {
/**
* Used to load the biomes.
*/
private void populateBiomes() throws DataException {
private void populateBiomes() {
biomes = new BiomeType[256];
if (rootTag.get("Biomes") == null) {
LinIntArrayTag biomeTag = rootTag.findTag("Biomes", LinTagType.intArrayTag());
if (biomeTag == null) {
return;
}
int[] stored = NbtUtils.getChildTag(rootTag, "Biomes", BinaryTagTypes.INT_ARRAY).value();
int[] stored = biomeTag.value();
for (int i = 0; i < 256; i++) {
biomes[i] = BiomeTypes.getLegacy(stored[i]);
}

View File

@ -19,14 +19,14 @@
package com.sk89q.worldedit.world.chunk;
import com.fastasyncworldedit.core.util.NbtUtils;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.nbt.BinaryTagTypes;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinIntArrayTag;
import org.enginehub.linbus.tree.LinTagType;
/**
* The chunk format for Minecraft 1.15 and newer
@ -38,7 +38,7 @@ public class AnvilChunk15 extends AnvilChunk13 {
*
* @param tag the tag to read
* @throws DataException on a data error
* @deprecated Use {@link #AnvilChunk15(CompoundBinaryTag)}
* @deprecated Use {@link #AnvilChunk15(LinCompoundTag)}
*/
@Deprecated
public AnvilChunk15(CompoundTag tag) throws DataException {
@ -51,7 +51,7 @@ public class AnvilChunk15 extends AnvilChunk13 {
* @param tag the tag to read
* @throws DataException on a data error
*/
public AnvilChunk15(CompoundBinaryTag tag) throws DataException {
public AnvilChunk15(LinCompoundTag tag) throws DataException {
super(tag);
}
@ -68,10 +68,11 @@ public class AnvilChunk15 extends AnvilChunk13 {
private void populateBiomes() throws DataException {
biomes = new BiomeType[1024];
if (rootTag.get("Biomes") == null) {
LinIntArrayTag biomeTag = rootTag.findTag("Biomes", LinTagType.intArrayTag());
if (biomeTag == null) {
return;
}
int[] stored = NbtUtils.getChildTag(rootTag, "Biomes", BinaryTagTypes.INT_ARRAY).value();
int[] stored = biomeTag.value();
for (int i = 0; i < 1024; i++) {
biomes[i] = BiomeTypes.getLegacy(stored[i]);
}

View File

@ -20,10 +20,10 @@
package com.sk89q.worldedit.world.chunk;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.storage.InvalidFormatException;
import org.enginehub.linbus.tree.LinCompoundTag;
/**
* The chunk format for Minecraft 1.16 and 1.17
@ -35,7 +35,7 @@ public class AnvilChunk16 extends AnvilChunk15 {
*
* @param tag the tag to read
* @throws DataException on a data error
* @deprecated Use {@link #AnvilChunk16(CompoundBinaryTag)}
* @deprecated Use {@link #AnvilChunk16(LinCompoundTag)}
*/
@Deprecated
public AnvilChunk16(CompoundTag tag) throws DataException {
@ -48,7 +48,7 @@ public class AnvilChunk16 extends AnvilChunk15 {
* @param tag the tag to read
* @throws DataException on a data error
*/
public AnvilChunk16(CompoundBinaryTag tag) throws DataException {
public AnvilChunk16(LinCompoundTag tag) throws DataException {
super(tag);
}

View File

@ -20,16 +20,12 @@
package com.sk89q.worldedit.world.chunk;
import com.fastasyncworldedit.core.util.NbtUtils;
import com.google.common.collect.ImmutableMap;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.BinaryTagTypes;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.IntBinaryTag;
import com.sk89q.worldedit.util.nbt.ListBinaryTag;
import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
@ -39,10 +35,15 @@ import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.entity.EntityTypes;
import com.sk89q.worldedit.world.storage.InvalidFormatException;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinIntArrayTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinStringTag;
import org.enginehub.linbus.tree.LinTag;
import org.enginehub.linbus.tree.LinTagType;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
@ -52,11 +53,11 @@ import java.util.function.Supplier;
*/
public class AnvilChunk17 implements Chunk {
private final CompoundBinaryTag rootTag;
private final Supplier<CompoundBinaryTag> entityTagSupplier;
private final LinCompoundTag rootTag;
private final Supplier<LinCompoundTag> entityTagSupplier;
private BiomeType[] biomes;
private BlockState[][] blocks;
private Map<BlockVector3, CompoundBinaryTag> tileEntities;
private Map<BlockVector3, LinCompoundTag> tileEntities;
private List<BaseEntity> entities;
// initialise with default values
private int minSectionPosition = 0;
@ -68,16 +69,16 @@ public class AnvilChunk17 implements Chunk {
*
* @param tag the tag to read
* @throws DataException on a data error
* @deprecated Use {@link #AnvilChunk17(CompoundBinaryTag, Supplier)}
* @deprecated Use {@link #AnvilChunk17(LinCompoundTag, Supplier)}
*/
@Deprecated
public AnvilChunk17(CompoundTag tag, Supplier<CompoundTag> entitiesTag) throws DataException {
this(tag.asBinaryTag(), () -> {
this(tag.toLinTag(), () -> {
CompoundTag compoundTag = entitiesTag.get();
if (compoundTag == null) {
return null;
}
return compoundTag.asBinaryTag();
return compoundTag.toLinTag();
});
}
@ -89,20 +90,21 @@ public class AnvilChunk17 implements Chunk {
* {@link #getEntities()} is called
* @throws DataException on a data error
*/
public AnvilChunk17(CompoundBinaryTag tag, Supplier<CompoundBinaryTag> entityTag) throws DataException {
public AnvilChunk17(LinCompoundTag tag, Supplier<LinCompoundTag> entityTag) throws DataException {
rootTag = tag;
entityTagSupplier = entityTag;
blocks = new BlockState[16][]; // initialise with default length
ListBinaryTag sections = rootTag.getList("Sections");
LinListTag<LinTag<?>> sections = rootTag.getTag("Sections", LinTagType.listTag());
for (BinaryTag rawSectionTag : sections) {
if (!(rawSectionTag instanceof CompoundBinaryTag sectionTag)) {
for (LinTag<?> rawSectionTag : sections.value()) {
if (!(rawSectionTag instanceof LinCompoundTag sectionTag)) {
continue;
}
if (sectionTag.get("Y") == null || sectionTag.get("BlockStates") == null) {
var sectionYTag = sectionTag.findTag("Y", LinTagType.byteTag());
if (sectionYTag == null) {
continue; // Empty section.
}
@ -110,30 +112,32 @@ public class AnvilChunk17 implements Chunk {
updateSectionIndexRange(y);
// parse palette
ListBinaryTag paletteEntries = sectionTag.getList("Palette", BinaryTagTypes.COMPOUND);
int paletteSize = paletteEntries.size();
LinListTag paletteEntries = sectionTag.getListTag("Palette", LinTagType.compoundTag());
int paletteSize = paletteEntries.value().size();
if (paletteSize == 0) {
continue;
}
BlockState[] palette = new BlockState[paletteSize];
for (int paletteEntryId = 0; paletteEntryId < paletteSize; paletteEntryId++) {
CompoundBinaryTag paletteEntry = (CompoundBinaryTag) paletteEntries.get(paletteEntryId);
BlockType type = BlockTypes.get(paletteEntry.getString("Name"));
LinCompoundTag paletteEntry = (LinCompoundTag) paletteEntries.get(paletteEntryId);
BlockType type = BlockTypes.get(paletteEntry.getTag("Name", LinTagType.stringTag()).value());
if (type == null) {
throw new InvalidFormatException("Invalid block type: " + paletteEntry.getString("Name"));
throw new InvalidFormatException("Invalid block type: " + paletteEntry
.getTag("Name", LinTagType.stringTag())
.value());
}
BlockState blockState = type.getDefaultState();
if (paletteEntry.get("Properties") != null) {
CompoundBinaryTag properties = NbtUtils.getChildTag(paletteEntry, "Properties", BinaryTagTypes.COMPOUND);
LinCompoundTag properties = paletteEntry.findTag("Properties", LinTagType.compoundTag());
if (properties != null) {
for (Property<?> property : blockState.getStates().keySet()) {
if (properties.get(property.getName()) != null) {
String value = properties.getString(property.getName());
LinStringTag stringTag = properties.findTag(property.getName(), LinTagType.stringTag());
if (stringTag != null) {
try {
blockState = getBlockStateWith(blockState, property, value);
blockState = getBlockStateWith(blockState, property, stringTag.value());
} catch (IllegalArgumentException e) {
throw new InvalidFormatException("Invalid block state for " + blockState
.getBlockType()
.id() + ", " + property.getName() + ": " + value);
.id() + ", " + property.getName() + ": " + stringTag.value());
}
}
}
@ -142,7 +146,7 @@ public class AnvilChunk17 implements Chunk {
}
// parse block states
long[] blockStatesSerialized = sectionTag.getLongArray("BlockStates");
long[] blockStatesSerialized = sectionTag.getTag("BlockStates", LinTagType.longArrayTag()).value();
BlockState[] chunkSectionBlocks = new BlockState[4096];
blocks[y - minSectionPosition] = chunkSectionBlocks;
@ -191,27 +195,24 @@ public class AnvilChunk17 implements Chunk {
/**
* Used to load the tile entities.
*/
private void populateTileEntities() throws DataException {
tileEntities = new HashMap<>();
if (rootTag.get("TileEntities") == null) {
private void populateTileEntities() {
LinListTag<LinCompoundTag> tags = rootTag.findListTag(
"TileEntities", LinTagType.compoundTag()
);
if (tags == null) {
tileEntities = ImmutableMap.of();
return;
}
ListBinaryTag tags = rootTag.getList("TileEntities");
for (BinaryTag tag : tags) {
if (!(tag instanceof CompoundBinaryTag)) {
throw new InvalidFormatException("CompoundTag expected in TileEntities");
}
CompoundBinaryTag t = (CompoundBinaryTag) tag;
int x = ((IntBinaryTag) t.get("x")).value();
int y = ((IntBinaryTag) t.get("y")).value();
int z = ((IntBinaryTag) t.get("z")).value();
var tileEntitiesBuilder = ImmutableMap.<BlockVector3, LinCompoundTag>builderWithExpectedSize(tags.value().size());
for (LinCompoundTag tag : tags.value()) {
int x = tag.getTag("x", LinTagType.intTag()).valueAsInt();
int y = tag.getTag("y", LinTagType.intTag()).valueAsInt();
int z = tag.getTag("z", LinTagType.intTag()).valueAsInt();
BlockVector3 vec = BlockVector3.at(x, y, z);
tileEntities.put(vec, t);
tileEntities.put(vec, tag);
}
tileEntities = tileEntitiesBuilder.build();
}
/**
@ -224,7 +225,7 @@ public class AnvilChunk17 implements Chunk {
* @throws DataException thrown if there is a data error
*/
@Nullable
private CompoundBinaryTag getBlockTileEntity(BlockVector3 position) throws DataException {
private LinCompoundTag getBlockTileEntity(BlockVector3 position) throws DataException {
if (tileEntities == null) {
populateTileEntities();
}
@ -248,7 +249,7 @@ public class AnvilChunk17 implements Chunk {
BlockState[] sectionBlocks = blocks[section - minSectionPosition];
BlockState state = sectionBlocks != null ? sectionBlocks[(yIndex << 8) | (z << 4) | x] : BlockTypes.AIR.getDefaultState();
CompoundBinaryTag tileEntity = getBlockTileEntity(position);
LinCompoundTag tileEntity = getBlockTileEntity(position);
if (tileEntity != null) {
return state.toBaseBlock(tileEntity);
@ -270,10 +271,11 @@ public class AnvilChunk17 implements Chunk {
private void populateBiomes() throws DataException {
biomes = new BiomeType[64 * blocks.length];
if (rootTag.get("Biomes") == null) {
LinIntArrayTag biomeTag = rootTag.findTag("Biomes", LinTagType.intArrayTag());
if (biomeTag == null) {
return;
}
int[] stored = rootTag.getIntArray("Biomes");
int[] stored = biomeTag.value();
for (int i = 0; i < 1024; i++) {
biomes[i] = BiomeTypes.getLegacy(stored[i]);
}
@ -290,22 +292,21 @@ public class AnvilChunk17 implements Chunk {
/**
* Used to load the biomes.
*/
private void populateEntities() throws DataException {
private void populateEntities() {
entities = new ArrayList<>();
CompoundBinaryTag entityTag;
if (entityTagSupplier == null || (entityTag = entityTagSupplier.get()) == null) {
LinListTag<LinCompoundTag> tags = rootTag.findListTag(
"Entities", LinTagType.compoundTag()
);
if (tags == null) {
return;
}
ListBinaryTag tags = entityTag.getList("Entities");
for (BinaryTag tag : tags) {
if (!(tag instanceof CompoundBinaryTag)) {
throw new InvalidFormatException("CompoundTag expected in Entities");
}
for (LinCompoundTag tag : tags.value()) {
CompoundBinaryTag t = (CompoundBinaryTag) tag;
entities.add(new BaseEntity(EntityTypes.get(t.getString("id")), LazyReference.computed(t)));
entities.add(new BaseEntity(
EntityTypes.get(tag.getTag("id", LinTagType.stringTag()).value()),
LazyReference.computed(tag)
));
}
}

View File

@ -19,134 +19,93 @@
package com.sk89q.worldedit.world.chunk;
import com.fastasyncworldedit.core.util.NbtUtils;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.LongArrayTag;
import com.sk89q.jnbt.NBTUtils;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.BinaryTagTypes;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.ListBinaryTag;
import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.entity.EntityTypes;
import com.sk89q.worldedit.world.storage.InvalidFormatException;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
/**
* The chunk format for Minecraft 1.18 and newer
*/
public class AnvilChunk18 implements Chunk {
//FAWE start - CBT
private final CompoundBinaryTag rootTag;
//FAWE end
private final CompoundTag rootTag;
private final Int2ObjectOpenHashMap<BlockState[]> blocks;
//FAWE start - entity and biome restore
private final int sectionCount;
private final Supplier<CompoundBinaryTag> entityTagSupplier;
private Int2ObjectOpenHashMap<BiomeType[]> biomes = null;
private List<BaseEntity> entities;
private Map<BlockVector3, CompoundBinaryTag> tileEntities;
//FAWE end
private final int rootX;
private final int rootZ;
private Map<BlockVector3, Map<String, Tag<?, ?>>> tileEntities;
/**
* Construct the chunk with a compound tag.
*
* @param tag the tag to read
* @throws DataException on a data error
* @deprecated Use {@link AnvilChunk18#AnvilChunk18(CompoundBinaryTag, Supplier)}
*/
@Deprecated
public AnvilChunk18(CompoundTag tag) throws DataException {
//FAWE start - CBT
this(tag.asBinaryTag(), () -> null);
}
/**
* Construct the chunk with a compound tag.
*
* @param tag the tag to read
* @throws DataException on a data error
* @deprecated Use {@link AnvilChunk18#AnvilChunk18(CompoundBinaryTag, Supplier)}
* @since 2.1.0
*/
@Deprecated
public AnvilChunk18(CompoundTag tag, Supplier<CompoundTag> entitiesTag) throws DataException {
//FAWE start - CBT
this(tag.asBinaryTag(), () -> {
CompoundTag compoundTag = entitiesTag.get();
return compoundTag == null ? null : compoundTag.asBinaryTag();
});
}
/**
* Construct the chunk with a compound tag.
*
* @param tag the tag to read
* @throws DataException on a data error
* @since 2.1.0
*/
public AnvilChunk18(CompoundBinaryTag tag, Supplier<CompoundBinaryTag> entityTag) throws DataException {
//FAWE end
rootTag = tag;
entityTagSupplier = entityTag;
//FAWE start - CBT
ListBinaryTag sections = rootTag.getList("sections");
this.sectionCount = sections.size();
rootX = NBTUtils.getChildTag(rootTag.getValue(), "xPos", IntTag.class).getValue();
rootZ = NBTUtils.getChildTag(rootTag.getValue(), "zPos", IntTag.class).getValue();
List<Tag> sections = NBTUtils.getChildTag(rootTag.getValue(), "sections", ListTag.class).getValue();
blocks = new Int2ObjectOpenHashMap<>(sections.size());
for (BinaryTag rawSectionTag : sections) {
if (!(rawSectionTag instanceof CompoundBinaryTag sectionTag)) {
for (Tag rawSectionTag : sections) {
if (!(rawSectionTag instanceof CompoundTag)) {
continue;
}
int y = NbtUtils.getInt(sectionTag, "Y"); // sometimes a byte, sometimes an int
CompoundTag sectionTag = (CompoundTag) rawSectionTag;
Object yValue = sectionTag.getValue().get("Y").getValue(); // sometimes a byte, sometimes an int
if (!(yValue instanceof Number)) {
throw new InvalidFormatException("Y is not numeric: " + yValue);
}
int y = ((Number) yValue).intValue();
BinaryTag rawBlockStatesTag = sectionTag.get("block_states"); // null for sections outside of the world limits
if (rawBlockStatesTag instanceof CompoundBinaryTag blockStatesTag) {
Tag rawBlockStatesTag = sectionTag.getValue().get("block_states"); // null for sections outside of the world limits
if (rawBlockStatesTag instanceof CompoundTag) {
CompoundTag blockStatesTag = (CompoundTag) rawBlockStatesTag;
// parse palette
ListBinaryTag paletteEntries = blockStatesTag.getList("palette");
List<CompoundTag> paletteEntries = blockStatesTag.getList("palette", CompoundTag.class);
int paletteSize = paletteEntries.size();
if (paletteSize == 0) {
continue;
}
BlockState[] palette = new BlockState[paletteSize];
for (int paletteEntryId = 0; paletteEntryId < paletteSize; paletteEntryId++) {
CompoundBinaryTag paletteEntry = (CompoundBinaryTag) paletteEntries.get(paletteEntryId);
CompoundTag paletteEntry = paletteEntries.get(paletteEntryId);
BlockType type = BlockTypes.get(paletteEntry.getString("Name"));
if (type == null) {
throw new InvalidFormatException("Invalid block type: " + paletteEntry.getString("Name"));
}
BlockState blockState = type.getDefaultState();
BinaryTag propertiesTag = paletteEntry.get("Properties");
if (propertiesTag instanceof CompoundBinaryTag properties) {
if (paletteEntry.containsKey("Properties")) {
CompoundTag properties = NBTUtils.getChildTag(paletteEntry.getValue(), "Properties", CompoundTag.class);
for (Property<?> property : blockState.getStates().keySet()) {
String value;
if (!(value = properties.getString(property.getName())).isEmpty()) {
if (properties.containsKey(property.getName())) {
String value = properties.getString(property.getName());
try {
blockState = getBlockStateWith(blockState, property, value);
} catch (IllegalArgumentException e) {
throw new InvalidFormatException("Invalid block state for " + blockState
.getBlockType()
.id() + ", " + property.getName() + ": " + value);
throw new InvalidFormatException("Invalid block state for " + blockState.getBlockType().getId() + ", " + property.getName() + ": " + value);
}
}
}
@ -160,7 +119,7 @@ public class AnvilChunk18 implements Chunk {
}
// parse block states
long[] blockStatesSerialized = blockStatesTag.getLongArray("data");
long[] blockStatesSerialized = NBTUtils.getChildTag(blockStatesTag.getValue(), "data", LongArrayTag.class).getValue();
BlockState[] chunkSectionBlocks = new BlockState[16 * 16 * 16];
blocks.put(y, chunkSectionBlocks);
@ -168,7 +127,6 @@ public class AnvilChunk18 implements Chunk {
readBlockStates(palette, blockStatesSerialized, chunkSectionBlocks);
}
}
//FAWE end
}
protected void readBlockStates(BlockState[] palette, long[] blockStatesSerialized, BlockState[] chunkSectionBlocks) throws InvalidFormatException {
@ -190,24 +148,28 @@ public class AnvilChunk18 implements Chunk {
* Used to load the tile entities.
*/
private void populateTileEntities() throws DataException {
//FAWE start - CBT
tileEntities = new HashMap<>();
if (!(rootTag.get("block_entities") instanceof ListBinaryTag tags)) {
if (!rootTag.getValue().containsKey("block_entities")) {
return;
}
for (BinaryTag tag : tags) {
if (!(tag instanceof CompoundBinaryTag t)) {
List<Tag> tags = NBTUtils.getChildTag(rootTag.getValue(),
"block_entities", ListTag.class).getValue();
for (Tag tag : tags) {
if (!(tag instanceof CompoundTag)) {
throw new InvalidFormatException("CompoundTag expected in block_entities");
}
int x = t.getInt("x");
int y = t.getInt("y");
int z = t.getInt("z");
CompoundTag t = (CompoundTag) tag;
Map<String, Tag<?, ?>> values = new HashMap<>(t.getValue());
int x = ((IntTag) values.get("x")).getValue();
int y = ((IntTag) values.get("y")).getValue();
int z = ((IntTag) values.get("z")).getValue();
BlockVector3 vec = BlockVector3.at(x, y, z);
tileEntities.put(vec, t);
tileEntities.put(vec, values);
}
//FAWE end
}
/**
@ -220,21 +182,24 @@ public class AnvilChunk18 implements Chunk {
* @throws DataException thrown if there is a data error
*/
@Nullable
private CompoundBinaryTag getBlockTileEntity(BlockVector3 position) throws DataException {
//FAWE start - CBT
private CompoundTag getBlockTileEntity(BlockVector3 position) throws DataException {
if (tileEntities == null) {
populateTileEntities();
}
return tileEntities.get(position);
//FAWE end
Map<String, Tag<?, ?>> values = tileEntities.get(position);
if (values == null) {
return null;
}
return new CompoundTag(values);
}
@Override
public BaseBlock getBlock(BlockVector3 position) throws DataException {
int x = position.x() & 15;
int y = position.y();
int z = position.z() & 15;
int x = position.getX() - rootX * 16;
int y = position.getY();
int z = position.getZ() - rootZ * 16;
int section = y >> 4;
int yIndex = y & 0x0F;
@ -245,7 +210,7 @@ public class AnvilChunk18 implements Chunk {
}
BlockState state = sectionBlocks[sectionBlocks.length == 1 ? 0 : ((yIndex << 8) | (z << 4) | x)];
CompoundBinaryTag tileEntity = getBlockTileEntity(position);
CompoundTag tileEntity = getBlockTileEntity(position);
if (tileEntity != null) {
return state.toBaseBlock(tileEntity);
@ -254,110 +219,4 @@ public class AnvilChunk18 implements Chunk {
return state.toBaseBlock();
}
@Override
public BiomeType getBiome(final BlockVector3 position) throws DataException {
if (biomes == null) {
populateBiomes();
}
int x = (position.x() & 15) >> 2;
int y = (position.y() & 15) >> 2;
int z = (position.z() & 15) >> 2;
int section = position.y() >> 4;
BiomeType[] sectionBiomes = biomes.get(section);
if (sectionBiomes.length == 1) {
return sectionBiomes[0];
}
return biomes.get(section)[y << 4 | z << 2 | x];
}
private void populateBiomes() throws DataException {
biomes = new Int2ObjectOpenHashMap<>(sectionCount);
ListBinaryTag sections = rootTag.getList("sections");
for (BinaryTag rawSectionTag : sections) {
if (!(rawSectionTag instanceof CompoundBinaryTag sectionTag)) {
continue;
}
int y = NbtUtils.getInt(sectionTag, "Y"); // sometimes a byte, sometimes an int
BinaryTag rawBlockStatesTag = sectionTag.get("biomes"); // null for sections outside of the world limits
if (rawBlockStatesTag instanceof CompoundBinaryTag biomeTypesTag) {
// parse palette
ListBinaryTag paletteEntries = biomeTypesTag.getList("palette");
int paletteSize = paletteEntries.size();
if (paletteSize == 0) {
continue;
}
BiomeType[] palette = new BiomeType[paletteSize];
for (int paletteEntryId = 0; paletteEntryId < paletteSize; paletteEntryId++) {
String paletteEntry = paletteEntries.getString(paletteEntryId);
BiomeType type = BiomeType.REGISTRY.get(paletteEntry);
if (type == null) {
throw new InvalidFormatException("Invalid biome type: " + paletteEntry);
}
palette[paletteEntryId] = type;
}
if (paletteSize == 1) {
// the same block everywhere
biomes.put(y, palette);
continue;
}
// parse block states
long[] biomesSerialized = biomeTypesTag.getLongArray("data");
if (biomesSerialized.length == 0) {
throw new InvalidFormatException("Biome data not present.");
}
BiomeType[] chunkSectionBiomes = new BiomeType[64];
biomes.put(y, chunkSectionBiomes);
readBiomes(palette, biomesSerialized, chunkSectionBiomes);
}
}
}
protected void readBiomes(BiomeType[] palette, long[] biomesSerialized, BiomeType[] chunkSectionBiomes) throws
InvalidFormatException {
PackedIntArrayReader reader = new PackedIntArrayReader(biomesSerialized, 64);
for (int biomePos = 0; biomePos < chunkSectionBiomes.length; biomePos++) {
int index = reader.get(biomePos);
if (index >= palette.length) {
throw new InvalidFormatException("Invalid biome table entry: " + index);
}
chunkSectionBiomes[biomePos] = palette[index];
}
}
@Override
public List<BaseEntity> getEntities() throws DataException {
if (entities == null) {
populateEntities();
}
return entities;
}
/**
* Used to load the biomes.
*/
private void populateEntities() throws DataException {
entities = new ArrayList<>();
CompoundBinaryTag entityTag;
if (entityTagSupplier == null || (entityTag = entityTagSupplier.get()) == null) {
return;
}
ListBinaryTag tags = NbtUtils.getChildTag(entityTag, "Entities", BinaryTagTypes.LIST);
for (BinaryTag tag : tags) {
if (!(tag instanceof CompoundBinaryTag t)) {
throw new InvalidFormatException("CompoundTag expected in Entities");
}
entities.add(new BaseEntity(EntityTypes.get(t.getString("id")), LazyReference.computed(t)));
}
}
}

View File

@ -19,21 +19,19 @@
package com.sk89q.worldedit.world.chunk;
import com.fastasyncworldedit.core.util.NbtUtils;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.BinaryTagTypes;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.IntBinaryTag;
import com.sk89q.worldedit.util.nbt.ListBinaryTag;
import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.registry.LegacyMapper;
import com.sk89q.worldedit.world.storage.InvalidFormatException;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinIntTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinTagType;
import java.util.HashMap;
import java.util.Map;
@ -43,24 +41,24 @@ import java.util.Map;
*/
public class OldChunk implements Chunk {
private final CompoundBinaryTag rootTag;
private final LinCompoundTag rootTag;
private final byte[] blocks;
private final byte[] data;
private final int rootX;
private final int rootZ;
private Map<BlockVector3, CompoundBinaryTag> tileEntities;
private Map<BlockVector3, LinCompoundTag> tileEntities;
/**
* Construct the chunk with a compound tag.
*
* @param tag the tag
* @throws DataException if there is an error getting the chunk data
* @deprecated Use {@link #OldChunk(CompoundBinaryTag)}
* @deprecated Use {@link #OldChunk(LinCompoundTag)}
*/
@Deprecated
public OldChunk(CompoundTag tag) throws DataException {
this(tag.asBinaryTag());
this(tag.toLinTag());
}
/**
@ -69,13 +67,13 @@ public class OldChunk implements Chunk {
* @param tag the tag
* @throws DataException if there is an error getting the chunk data
*/
public OldChunk(CompoundBinaryTag tag) throws DataException {
public OldChunk(LinCompoundTag tag) throws DataException {
rootTag = tag;
blocks = NbtUtils.getChildTag(rootTag, "Blocks", BinaryTagTypes.BYTE_ARRAY).value();
data = NbtUtils.getChildTag(rootTag, "Data", BinaryTagTypes.BYTE_ARRAY).value();
rootX = NbtUtils.getChildTag(rootTag, "xPos", BinaryTagTypes.INT).value();
rootZ = NbtUtils.getChildTag(rootTag, "zPos", BinaryTagTypes.INT).value();
blocks = rootTag.getTag("Blocks", LinTagType.byteArrayTag()).value();
data = rootTag.getTag("Data", LinTagType.byteArrayTag()).value();
rootX = rootTag.getTag("xPos", LinTagType.intTag()).value();
rootZ = rootTag.getTag("zPos", LinTagType.intTag()).value();
int size = 16 * 16 * 128;
if (blocks.length != size) {
@ -95,43 +93,39 @@ public class OldChunk implements Chunk {
* @throws DataException if there is an error getting the chunk data
*/
private void populateTileEntities() throws DataException {
ListBinaryTag tags = NbtUtils.getChildTag(rootTag, "TileEntities", BinaryTagTypes.LIST);
LinListTag<LinCompoundTag> tags = rootTag.getTag("TileEntities", LinTagType.listTag())
.asTypeChecked(LinTagType.compoundTag());
tileEntities = new HashMap<>();
for (BinaryTag tag : tags) {
if (!(tag instanceof CompoundBinaryTag)) {
throw new InvalidFormatException("CompoundTag expected in TileEntities");
}
CompoundBinaryTag t = (CompoundBinaryTag) tag;
for (LinCompoundTag t : tags.value()) {
int x = 0;
int y = 0;
int z = 0;
CompoundBinaryTag.Builder values = CompoundBinaryTag.builder();
LinCompoundTag.Builder values = LinCompoundTag.builder();
for (String key : t.keySet()) {
BinaryTag value = t.get(key);
for (String key : t.value().keySet()) {
var value = t.value().get(key);
switch (key) {
case "x":
if (value instanceof IntBinaryTag) {
x = ((IntBinaryTag) value).value();
case "x" -> {
if (value instanceof LinIntTag v) {
x = v.valueAsInt();
}
break;
case "y":
if (value instanceof IntBinaryTag) {
y = ((IntBinaryTag) value).value();
}
case "y" -> {
if (value instanceof LinIntTag v) {
y = v.valueAsInt();
}
break;
case "z":
if (value instanceof IntBinaryTag) {
z = ((IntBinaryTag) value).value();
}
case "z" -> {
if (value instanceof LinIntTag v) {
z = v.valueAsInt();
}
break;
default:
break;
}
default -> {
// Do nothing.
}
}
values.put(key, value);
@ -151,13 +145,12 @@ public class OldChunk implements Chunk {
* @return a tag
* @throws DataException if there is an error getting the chunk data
*/
private CompoundBinaryTag getBlockTileEntity(BlockVector3 position) throws DataException {
private LinCompoundTag getBlockTileEntity(BlockVector3 position) throws DataException {
if (tileEntities == null) {
populateTileEntities();
}
CompoundBinaryTag values = tileEntities.get(position);
return values;
return tileEntities.get(position);
}
@Override
@ -197,13 +190,9 @@ public class OldChunk implements Chunk {
return BlockTypes.AIR.getDefaultState().toBaseBlock();
}
CompoundBinaryTag tileEntity = getBlockTileEntity(position);
LinCompoundTag tileEntity = getBlockTileEntity(position);
if (tileEntity != null) {
return state.toBaseBlock(tileEntity);
}
return state.toBaseBlock();
return state.toBaseBlock(tileEntity);
}
}

View File

@ -28,12 +28,15 @@ import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.ListBinaryTag;
import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.chunk.Chunk;
import com.sk89q.worldedit.world.storage.ChunkStore;
import com.sk89q.worldedit.world.storage.MissingChunkException;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinDoubleTag;
import org.enginehub.linbus.tree.LinFloatTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinTagType;
import java.io.IOException;
import java.util.ArrayList;
@ -197,14 +200,14 @@ public class SnapshotRestore {
if (restoreEntities) {
try {
for (BaseEntity entity : chunk.getEntities()) {
CompoundBinaryTag tag = entity.getNbtReference().getValue();
ListBinaryTag pos = tag.getList("Pos");
ListBinaryTag rotation = tag.getList("Rotation");
double x = pos.getDouble(0);
double y = pos.getDouble(1);
double z = pos.getDouble(2);
float yRot = rotation.getFloat(0);
float xRot = rotation.getFloat(1);
LinCompoundTag tag = entity.getNbtReference().getValue();
LinListTag<LinDoubleTag> pos = tag.getListTag("Pos", LinTagType.doubleTag());
LinListTag<LinFloatTag> rotation = tag.getListTag("Rotation", LinTagType.floatTag());
double x = pos.get(0).value();
double y = pos.get(1).value();
double z = pos.get(2).value();
float yRot = rotation.get(0).value();
float xRot = rotation.get(1).value();
Location location = new Location(editSession.getWorld(), x, y, z, yRot, xRot);
BlockVector3 blockVector3 = BlockVector3.at(x, y, z);
if (region.contains(blockVector3) && (editSession.getMask() == null

View File

@ -27,13 +27,15 @@ import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.nbt.BinaryTagTypes;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.ListBinaryTag;
import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.chunk.Chunk;
import com.sk89q.worldedit.world.storage.ChunkStore;
import com.sk89q.worldedit.world.storage.MissingChunkException;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinDoubleTag;
import org.enginehub.linbus.tree.LinFloatTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinTagType;
import java.io.IOException;
import java.util.ArrayList;
@ -193,14 +195,14 @@ public class SnapshotRestore {
if (restoreEntities) {
try {
for (BaseEntity entity : chunk.getEntities()) {
CompoundBinaryTag tag = entity.getNbtReference().getValue();
ListBinaryTag pos = tag.getList("Pos", BinaryTagTypes.LIST);
ListBinaryTag rotation = tag.getList("Rotation", BinaryTagTypes.LIST);
double x = pos.getDouble(0);
double y = pos.getDouble(1);
double z = pos.getDouble(2);
float yRot = rotation.getFloat(0);
float xRot = rotation.getFloat(1);
LinCompoundTag tag = entity.getNbtReference().getValue();
LinListTag<LinDoubleTag> pos = tag.getListTag("Pos", LinTagType.doubleTag());
LinListTag<LinFloatTag> rotation = tag.getListTag("Rotation", LinTagType.floatTag());
double x = pos.get(0).value();
double y = pos.get(1).value();
double z = pos.get(2).value();
float yRot = rotation.get(0).value();
float xRot = rotation.get(1).value();
Location location = new Location(editSession.getWorld(), x, y, z, yRot, xRot);
editSession.createEntity(location, entity);
}

View File

@ -19,7 +19,6 @@
package com.sk89q.worldedit.world.storage;
import com.sk89q.jnbt.AdventureNBTConverter;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.NBTInputStream;
import com.sk89q.jnbt.Tag;
@ -54,7 +53,7 @@ public class ChunkStoreHelper {
public static CompoundTag readCompoundTag(ChunkDataInputSupplier input) throws DataException, IOException {
try (InputStream stream = input.openInputStream();
NBTInputStream nbt = new NBTInputStream(stream)) {
NBTInputStream nbt = new NBTInputStream(stream)) {
Tag tag = nbt.readNamedTag().getTag();
if (!(tag instanceof CompoundTag)) {
throw new ChunkStoreException("CompoundTag expected for chunk; got "
@ -99,23 +98,20 @@ public class ChunkStoreHelper {
if ((dataVersion > 0 || hasLevelSections(rootTag)) && dataVersion < currentDataVersion) { // only fix up MCA format, DFU doesn't support MCR chunks
final DataFixer dataFixer = platform.getDataFixer();
if (dataFixer != null) {
//FAWE start - CBT
rootTag = (CompoundTag) AdventureNBTConverter.fromAdventure(dataFixer.fixUp(DataFixer.FixTypes.CHUNK,
rootTag.asBinaryTag(), dataVersion));
//FAWE end
rootTag = new CompoundTag(dataFixer.fixUp(DataFixer.FixTypes.CHUNK, rootTag.toLinTag(), dataVersion));
dataVersion = currentDataVersion;
}
}
if (dataVersion >= Constants.DATA_VERSION_MC_1_18) {
return new AnvilChunk18(rootTag, entitiesTag);
return new AnvilChunk18(rootTag);
}
Map<String, Tag> children = rootTag.getValue();
Map<String, Tag<?, ?>> children = rootTag.getValue();
CompoundTag tag = null;
// Find Level tag
for (Map.Entry<String, Tag> entry : children.entrySet()) {
for (Map.Entry<String, Tag<?, ?>> entry : children.entrySet()) {
if (entry.getKey().equals("Level")) {
if (entry.getValue() instanceof CompoundTag) {
tag = (CompoundTag) entry.getValue();
@ -150,7 +146,7 @@ public class ChunkStoreHelper {
return new AnvilChunk13(tag);
}
Map<String, Tag> tags = tag.getValue();
Map<String, Tag<?, ?>> tags = tag.getValue();
if (tags.containsKey("Sections")) {
return new AnvilChunk(tag);
}
@ -159,8 +155,8 @@ public class ChunkStoreHelper {
}
private static boolean hasLevelSections(CompoundTag rootTag) {
Map<String, Tag> children = rootTag.getValue();
Tag levelTag = children.get("Level");
Map<String, Tag<?, ?>> children = rootTag.getValue();
Tag<?, ?> levelTag = children.get("Level");
if (levelTag instanceof CompoundTag) {
return ((CompoundTag) levelTag).getValue().containsKey("Sections");
}

View File

@ -22,6 +22,9 @@ package com.sk89q.worldedit.world.storage;
import com.sk89q.jnbt.ListTag;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.util.Location;
import org.enginehub.linbus.tree.LinDoubleTag;
import org.enginehub.linbus.tree.LinFloatTag;
import org.enginehub.linbus.tree.LinListTag;
import static com.google.common.base.Preconditions.checkNotNull;
@ -44,15 +47,41 @@ public final class NBTConversions {
* @param positionTag the position tag
* @param directionTag the direction tag
* @return a location
* @deprecated Use {@link #toLocation(Extent, LinListTag, LinListTag)} instead.
*/
@Deprecated
public static Location toLocation(Extent extent, ListTag positionTag, ListTag directionTag) {
checkNotNull(extent);
checkNotNull(positionTag);
checkNotNull(directionTag);
return new Location(
extent,
positionTag.asDouble(0), positionTag.asDouble(1), positionTag.asDouble(2),
directionTag.getFloat(0), directionTag.getFloat(1)
extent,
positionTag.asDouble(0), positionTag.asDouble(1), positionTag.asDouble(2),
directionTag.getFloat(0), directionTag.getFloat(1));
}
/**
* Read a {@code Location} from two list tags, the first of which contains
* three numbers for the X, Y, and Z components, and the second of
* which contains two numbers, the yaw and pitch in degrees.
*
* <p>For values that are unavailable, their values will be 0.</p>
*
* @param extent the extent
* @param positionTag the position tag
* @param rotationTag the rotation tag
* @return a location
*/
public static Location toLocation(Extent extent, LinListTag<LinDoubleTag> positionTag, LinListTag<LinFloatTag> rotationTag) {
int posTagSize = positionTag.value().size();
int rotTagSize = rotationTag.value().size();
return new Location(
extent,
posTagSize > 0 ? positionTag.get(0).valueAsDouble() : 0,
posTagSize > 1 ? positionTag.get(1).valueAsDouble() : 0,
posTagSize > 2 ? positionTag.get(2).valueAsDouble() : 0,
rotTagSize > 0 ? rotationTag.get(0).valueAsFloat() : 0,
rotTagSize > 1 ? rotationTag.get(1).valueAsFloat() : 0
);
}