3
0
Mirror von https://github.com/IntellectualSites/FastAsyncWorldEdit.git synchronisiert 2024-11-19 17:30:08 +01:00

chore: update schematic and clipboard logic for linbus changes

Dieser Commit ist enthalten in:
Pierre Maurice Schwang 2024-06-26 22:59:44 +02:00
Ursprung e4faefe7e0
Commit b1e791a81a
Es konnte kein GPG-Schlüssel zu dieser Signatur gefunden werden
GPG-Schlüssel-ID: 37E613079F3E5BB9
10 geänderte Dateien mit 544 neuen und 681 gelöschten Zeilen

Datei anzeigen

@ -27,13 +27,10 @@ import com.fastasyncworldedit.core.extent.clipboard.io.schematic.MinecraftStruct
import com.fastasyncworldedit.core.extent.clipboard.io.schematic.PNGWriter; import com.fastasyncworldedit.core.extent.clipboard.io.schematic.PNGWriter;
import com.fastasyncworldedit.core.internal.io.ResettableFileInputStream; import com.fastasyncworldedit.core.internal.io.ResettableFileInputStream;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.NBTConstants; import com.sk89q.jnbt.NBTConstants;
import com.sk89q.jnbt.NBTInputStream; import com.sk89q.jnbt.NBTInputStream;
import com.sk89q.jnbt.NBTOutputStream; import com.sk89q.jnbt.NBTOutputStream;
import com.sk89q.jnbt.NamedTag; import com.sk89q.jnbt.NamedTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.extent.clipboard.io.sponge.SpongeSchematicV1Reader; import com.sk89q.worldedit.extent.clipboard.io.sponge.SpongeSchematicV1Reader;
import com.sk89q.worldedit.extent.clipboard.io.sponge.SpongeSchematicV2Reader; import com.sk89q.worldedit.extent.clipboard.io.sponge.SpongeSchematicV2Reader;
import com.sk89q.worldedit.extent.clipboard.io.sponge.SpongeSchematicV2Writer; import com.sk89q.worldedit.extent.clipboard.io.sponge.SpongeSchematicV2Writer;
@ -41,18 +38,19 @@ import com.sk89q.worldedit.extent.clipboard.io.sponge.SpongeSchematicV3Reader;
import com.sk89q.worldedit.extent.clipboard.io.sponge.SpongeSchematicV3Writer; import com.sk89q.worldedit.extent.clipboard.io.sponge.SpongeSchematicV3Writer;
import it.unimi.dsi.fastutil.io.FastBufferedInputStream; import it.unimi.dsi.fastutil.io.FastBufferedInputStream;
import org.anarres.parallelgzip.ParallelGZIPOutputStream; import org.anarres.parallelgzip.ParallelGZIPOutputStream;
import org.enginehub.linbus.stream.LinBinaryIO;
import org.enginehub.linbus.tree.LinRootEntry;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Locale; import java.util.Locale;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
@ -65,7 +63,6 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
//FAWE start - register fast clipboard io //FAWE start - register fast clipboard io
FAST_V3("fast", "fawe", "schem") { FAST_V3("fast", "fawe", "schem") {
@Override @Override
public ClipboardReader getReader(InputStream inputStream) throws IOException { public ClipboardReader getReader(InputStream inputStream) throws IOException {
return new FastSchematicReaderV3(inputStream); return new FastSchematicReaderV3(inputStream);
@ -85,9 +82,8 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
} }
@Override @Override
public boolean isFormat(final File file) { public boolean isFormat(final InputStream inputStream) {
try (final DataInputStream stream = new DataInputStream(new FastBufferedInputStream(new GZIPInputStream(Files.newInputStream( try (final DataInputStream stream = new DataInputStream(new FastBufferedInputStream(new GZIPInputStream(inputStream)));
file.toPath()))));
final NBTInputStream nbt = new NBTInputStream(stream)) { final NBTInputStream nbt = new NBTInputStream(stream)) {
if (stream.readByte() != NBTConstants.TYPE_COMPOUND) { if (stream.readByte() != NBTConstants.TYPE_COMPOUND) {
return false; return false;
@ -151,31 +147,8 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
} }
@Override @Override
public boolean isFormat(File file) { public boolean isFormat(InputStream inputStream) {
try (final DataInputStream stream = return detectOldSpongeSchematic(inputStream, FastSchematicWriterV2.CURRENT_VERSION);
new DataInputStream(new FastBufferedInputStream(new GZIPInputStream(Files.newInputStream(file.toPath()))));
final NBTInputStream nbt = new NBTInputStream(stream)) {
if (stream.readByte() != NBTConstants.TYPE_COMPOUND) {
return false;
}
stream.skipNBytes(2); // TAG name length ("Schematic" = 9)
stream.skipNBytes(9); // "Schematic"
// We can't guarantee the specific order of nbt data, so scan and skip, if required
do {
byte type = stream.readByte();
String name = stream.readUTF();
if (type == NBTConstants.TYPE_END) {
return false;
}
if (type == NBTConstants.TYPE_INT && name.equals("Version")) {
return stream.readInt() == FastSchematicWriterV2.CURRENT_VERSION;
}
nbt.readTagPayloadLazy(type, 0);
} while (true);
} catch (IOException ignored) {
}
return false;
} }
}, },
@ -205,9 +178,18 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
} }
@Override @Override
public boolean isFormat(File file) { public boolean isFormat(InputStream inputStream) {
String name = file.getName().toLowerCase(Locale.ROOT); LinRootEntry rootEntry;
return name.endsWith(".schematic") || name.endsWith(".mcedit") || name.endsWith(".mce"); try {
DataInputStream stream = new DataInputStream(new GZIPInputStream(inputStream));
rootEntry = LinBinaryIO.readUsing(stream, LinRootEntry::readFrom);
} catch (Exception e) {
return false;
}
if (!rootEntry.name().equals("Schematic")) {
return false;
}
return rootEntry.value().value().containsKey("Materials");
} }
}, },
SPONGE_V1_SCHEMATIC("sponge.1") { SPONGE_V1_SCHEMATIC("sponge.1") {
@ -218,8 +200,7 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
@Override @Override
public ClipboardReader getReader(InputStream inputStream) throws IOException { public ClipboardReader getReader(InputStream inputStream) throws IOException {
NBTInputStream nbtStream = new NBTInputStream(new GZIPInputStream(inputStream)); return new SpongeSchematicV1Reader(LinBinaryIO.read(new DataInputStream(new GZIPInputStream(inputStream))));
return new SpongeSchematicV1Reader(nbtStream);
} }
@Override @Override
@ -228,25 +209,8 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
} }
@Override @Override
public boolean isFormat(File file) { public boolean isFormat(InputStream inputStream) {
try (NBTInputStream str = new NBTInputStream(new GZIPInputStream(new FileInputStream(file)))) { return detectOldSpongeSchematic(inputStream, 1);
NamedTag rootTag = str.readNamedTag();
if (!rootTag.getName().equals("Schematic")) {
return false;
}
CompoundTag schematicTag = (CompoundTag) rootTag.getTag();
// Check
Map<String, Tag> schematic = schematicTag.getValue();
Tag versionTag = schematic.get("Version");
if (!(versionTag instanceof IntTag) || ((IntTag) versionTag).getValue() != 1) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
} }
}, },
@ -256,7 +220,8 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
* Avoid using with any large schematics/clipboards for reading/writing. * Avoid using with any large schematics/clipboards for reading/writing.
*/ */
@Deprecated @Deprecated
SPONGE_V2_SCHEMATIC("slow.2", "safe.2", "sponge.2") { SPONGE_V2_SCHEMATIC("slow.2", "safe.2", "sponge.2") { // FAWE - edit aliases for fast
@Override @Override
public String getPrimaryFileExtension() { public String getPrimaryFileExtension() {
return "schem"; return "schem";
@ -264,38 +229,21 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
@Override @Override
public ClipboardReader getReader(InputStream inputStream) throws IOException { public ClipboardReader getReader(InputStream inputStream) throws IOException {
NBTInputStream nbtStream = new NBTInputStream(new GZIPInputStream(inputStream)); return new SpongeSchematicV2Reader(LinBinaryIO.read(new DataInputStream(new GZIPInputStream(inputStream))));
return new SpongeSchematicV2Reader(nbtStream);
} }
@Override @Override
public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { public ClipboardWriter getWriter(OutputStream outputStream) throws IOException {
NBTOutputStream nbtStream = new NBTOutputStream(new GZIPOutputStream(outputStream)); return new SpongeSchematicV2Writer(new DataOutputStream(new GZIPOutputStream(outputStream)));
return new SpongeSchematicV2Writer(nbtStream);
} }
@Override @Override
public boolean isFormat(File file) { public boolean isFormat(InputStream inputStream) {
try (NBTInputStream str = new NBTInputStream(new GZIPInputStream(new FileInputStream(file)))) { return detectOldSpongeSchematic(inputStream, 2);
NamedTag rootTag = str.readNamedTag();
if (!rootTag.getName().equals("Schematic")) {
return false;
}
CompoundTag schematicTag = (CompoundTag) rootTag.getTag();
// Check
Map<String, Tag<?, ?>> schematic = schematicTag.getValue();
if (!schematic.containsKey("Version")) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
} }
}, },
SPONGE_V3_SCHEMATIC("sponge.3", "slow", "safe") { // FAWE edit aliases for fast SPONGE_V3_SCHEMATIC("sponge.3", "slow", "safe") { // FAWE - edit aliases for fast
@Override @Override
public String getPrimaryFileExtension() { public String getPrimaryFileExtension() {
return "schem"; return "schem";
@ -303,41 +251,19 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
@Override @Override
public ClipboardReader getReader(InputStream inputStream) throws IOException { public ClipboardReader getReader(InputStream inputStream) throws IOException {
NBTInputStream nbtStream = new NBTInputStream(new GZIPInputStream(inputStream)); return new SpongeSchematicV3Reader(LinBinaryIO.read(new DataInputStream(new GZIPInputStream(inputStream))));
return new SpongeSchematicV3Reader(nbtStream);
} }
@Override @Override
public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { public ClipboardWriter getWriter(OutputStream outputStream) throws IOException {
NBTOutputStream nbtStream = new NBTOutputStream(new GZIPOutputStream(outputStream)); return new SpongeSchematicV3Writer(new DataOutputStream(new GZIPOutputStream(outputStream)));
return new SpongeSchematicV3Writer(nbtStream);
} }
@Override @Override
public boolean isFormat(File file) { public boolean isFormat(File file) {
try (NBTInputStream str = new NBTInputStream(new GZIPInputStream(new FileInputStream(file)))) { //FAWE start - delegate to stream-based isFormat approach of fast impl
NamedTag rootTag = str.readNamedTag(); return FAST_V3.isFormat(file);
CompoundTag rootCompoundTag = (CompoundTag) rootTag.getTag(); //FAWE end
if (!rootCompoundTag.containsKey("Schematic")) {
return false;
}
Tag schematicTag = rootCompoundTag.getValue()
.get("Schematic");
if (!(schematicTag instanceof CompoundTag)) {
return false;
}
// Check
Map<String, Tag> schematic = ((CompoundTag) schematicTag).getValue();
Tag versionTag = schematic.get("Version");
if (!(versionTag instanceof IntTag) || ((IntTag) versionTag).getValue() != 3) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
} }
}, },
//FAWE start - recover schematics with bad entity data & register other clipboard formats //FAWE start - recover schematics with bad entity data & register other clipboard formats
@ -407,9 +333,37 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
} }
@Override @Override
public boolean isFormat(File file) { public boolean isFormat(InputStream inputStream) {
String name = file.getName().toLowerCase(Locale.ROOT); try (final DataInputStream stream = new DataInputStream(new FastBufferedInputStream(new GZIPInputStream(inputStream)));
return name.endsWith(".nbt"); final NBTInputStream nbt = new NBTInputStream(stream)) {
if (stream.readByte() != NBTConstants.TYPE_COMPOUND) {
return false;
}
NamedTag namedTag = nbt.readNamedTag();
if (!namedTag.getName().isEmpty()) {
return false;
}
// We can't guarantee the specific order of nbt data, so scan and skip, if required
do {
byte type = stream.readByte();
String name = stream.readUTF();
if (type == NBTConstants.TYPE_END) {
return false;
}
if (type == NBTConstants.TYPE_LIST && name.equals("size")) {
return true;
}
nbt.readTagPayloadLazy(type, 0);
} while (true);
} catch (IOException ignored) {
}
return false;
}
@Override
public boolean isFormat(final File file) {
return file.getName().toLowerCase(Locale.ROOT).endsWith(".nbt") && super.isFormat(file);
} }
}, },
@ -440,6 +394,33 @@ public enum BuiltInClipboardFormat implements ClipboardFormat {
}; };
//FAWE end //FAWE end
private static boolean detectOldSpongeSchematic(InputStream inputStream, int version) {
//FAWE start - dont utilize linbus - WorldEdit approach is not really streamed
try (final DataInputStream stream = new DataInputStream(new FastBufferedInputStream(new GZIPInputStream(inputStream)));
final NBTInputStream nbt = new NBTInputStream(stream)) {
if (stream.readByte() != NBTConstants.TYPE_COMPOUND) {
return false;
}
stream.skipNBytes(2); // TAG name length ("Schematic" = 9)
stream.skipNBytes(9); // "Schematic"
// We can't guarantee the specific order of nbt data, so scan and skip, if required
do {
byte type = stream.readByte();
String name = stream.readUTF();
if (type == NBTConstants.TYPE_END) {
return false;
}
if (type == NBTConstants.TYPE_INT && name.equals("Version")) {
return stream.readInt() == version;
}
nbt.readTagPayloadLazy(type, 0);
} while (true);
} catch (IOException ignored) {
}
return false;
}
/** /**
* For backwards compatibility, this points to the Sponge Schematic Specification (Version 2) * For backwards compatibility, this points to the Sponge Schematic Specification (Version 2)
* format. This should not be used going forwards. * format. This should not be used going forwards.

Datei anzeigen

@ -35,6 +35,7 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.URI; import java.net.URI;
import java.net.URL; import java.net.URL;
import java.nio.file.Files;
import java.util.Set; import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
@ -82,7 +83,29 @@ public interface ClipboardFormat {
* @param file the file * @param file the file
* @return true if the given file is of this format * @return true if the given file is of this format
*/ */
boolean isFormat(File file); default boolean isFormat(File file) {
try (InputStream stream = Files.newInputStream(file.toPath())) {
return isFormat(stream);
} catch (IOException e) {
return false;
}
}
/**
* Return whether the given stream is of this format.
*
* @apiNote The caller is responsible for the following:
* <ul>
* <li>Closing the input stream</li>
* </ul>
*
* @param inputStream The stream
* @return true if the given stream is of this format
* @since TODO
*/
default boolean isFormat(InputStream inputStream) {
return false;
}
/** /**
* Get the file extension this format primarily uses. * Get the file extension this format primarily uses.

Datei anzeigen

@ -20,6 +20,7 @@
package com.sk89q.worldedit.extent.clipboard.io; package com.sk89q.worldedit.extent.clipboard.io;
import com.sk89q.jnbt.Tag; import com.sk89q.jnbt.Tag;
import org.enginehub.linbus.tree.LinCompoundTag;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.io.IOException; import java.io.IOException;
@ -27,7 +28,10 @@ import java.util.Map;
/** /**
* Base class for NBT schematic readers. * Base class for NBT schematic readers.
*
* @deprecated These utility methods are provided by {@link LinCompoundTag} now.
*/ */
@Deprecated
public abstract class NBTSchematicReader implements ClipboardReader { 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 {

Datei anzeigen

@ -19,14 +19,7 @@
package com.sk89q.worldedit.extent.clipboard.io.sponge; package com.sk89q.worldedit.extent.clipboard.io.sponge;
import com.sk89q.jnbt.AdventureNBTConverter;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.CompoundTagBuilder;
import com.sk89q.jnbt.IntArrayTag;
import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.BaseEntity;
@ -39,25 +32,31 @@ import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.internal.util.VarIntIterator; import com.sk89q.worldedit.internal.util.VarIntIterator;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.world.DataFixer; import com.sk89q.worldedit.world.DataFixer;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.entity.EntityTypes; import com.sk89q.worldedit.world.entity.EntityTypes;
import com.sk89q.worldedit.world.storage.NBTConversions; import com.sk89q.worldedit.world.storage.NBTConversions;
import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinIntArrayTag;
import org.enginehub.linbus.tree.LinIntTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinTagType;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.sk89q.worldedit.extent.clipboard.io.SchematicNbtUtil.getTag;
import static com.sk89q.worldedit.extent.clipboard.io.SchematicNbtUtil.requireTag;
/** /**
* Common code shared between schematic readers. * Common code shared between schematic readers.
@ -66,9 +65,8 @@ public class ReaderUtil { //FAWE - make public
private static final Logger LOGGER = LogManagerCompat.getLogger(); private static final Logger LOGGER = LogManagerCompat.getLogger();
static void checkSchematicVersion(int version, CompoundTag schematicTag) throws IOException { static void checkSchematicVersion(int version, LinCompoundTag schematicTag) throws IOException {
int schematicVersion = requireTag(schematicTag.getValue(), "Version", IntTag.class) int schematicVersion = getSchematicVersion(schematicTag);
.getValue();
checkState( checkState(
version == schematicVersion, version == schematicVersion,
@ -76,12 +74,19 @@ public class ReaderUtil { //FAWE - make public
); );
} }
public static int getSchematicVersion(LinCompoundTag schematicTag) throws IOException {
return schematicTag.getTag("Version", LinTagType.intTag()).valueAsInt();
}
static VersionedDataFixer getVersionedDataFixer( static VersionedDataFixer getVersionedDataFixer(
Map<String, Tag> schematic, Platform platform, LinCompoundTag schematic, Platform platform,
int liveDataVersion int liveDataVersion
) throws IOException { ) {
//FAWE - delegate to new method //FAWE start - call fawe method without NBT component requirement
return getVersionedDataFixer(requireTag(schematic, "DataVersion", IntTag.class).getValue(), platform, liveDataVersion); return getVersionedDataFixer(schematic.getTag("DataVersion", LinTagType.intTag()).valueAsInt(), platform,
liveDataVersion
);
//FAWE end
} }
//FAWE start - make getVersionedDataFixer without schematic compound + public //FAWE start - make getVersionedDataFixer without schematic compound + public
@ -119,7 +124,7 @@ public class ReaderUtil { //FAWE - make public
//FAWE end //FAWE end
static Map<Integer, BlockState> decodePalette( static Map<Integer, BlockState> decodePalette(
Map<String, Tag> paletteObject, VersionedDataFixer fixer LinCompoundTag paletteObject, VersionedDataFixer fixer
) throws IOException { ) throws IOException {
Map<Integer, BlockState> palette = new HashMap<>(); Map<Integer, BlockState> palette = new HashMap<>();
@ -128,12 +133,15 @@ public class ReaderUtil { //FAWE - make public
parserContext.setTryLegacy(false); parserContext.setTryLegacy(false);
parserContext.setPreferringWildcard(false); parserContext.setPreferringWildcard(false);
for (String palettePart : paletteObject.keySet()) { for (var palettePart : paletteObject.value().entrySet()) {
int id = requireTag(paletteObject, palettePart, IntTag.class).getValue(); if (!(palettePart.getValue() instanceof LinIntTag idTag)) {
palettePart = fixer.fixUp(DataFixer.FixTypes.BLOCK_STATE, palettePart); throw new IOException("Invalid palette entry: " + palettePart);
}
int id = idTag.valueAsInt();
String paletteName = fixer.fixUp(DataFixer.FixTypes.BLOCK_STATE, palettePart.getKey());
BlockState state; BlockState state;
try { try {
state = WorldEdit.getInstance().getBlockFactory().parseFromInput(palettePart, parserContext).toImmutableState(); state = WorldEdit.getInstance().getBlockFactory().parseFromInput(paletteName, parserContext).toImmutableState();
} catch (InputParseException e) { } catch (InputParseException e) {
LOGGER.warn("Invalid BlockState in palette: " + palettePart + ". Block will be replaced with air."); LOGGER.warn("Invalid BlockState in palette: " + palettePart + ". Block will be replaced with air.");
state = BlockTypes.AIR.getDefaultState(); state = BlockTypes.AIR.getDefaultState();
@ -144,43 +152,24 @@ public class ReaderUtil { //FAWE - make public
} }
static void initializeClipboardFromBlocks( static void initializeClipboardFromBlocks(
Clipboard clipboard, Map<Integer, BlockState> palette, byte[] blocks, ListTag tileEntities, Clipboard clipboard, Map<Integer, BlockState> palette, byte[] blocks, LinListTag<LinCompoundTag> tileEntities,
VersionedDataFixer fixer, boolean dataIsNested VersionedDataFixer fixer, boolean dataIsNested
) throws IOException { ) throws IOException {
Map<BlockVector3, Map<String, Tag>> tileEntitiesMap = new HashMap<>(); Map<BlockVector3, LinCompoundTag> tileEntitiesMap = new HashMap<>();
if (tileEntities != null) { if (tileEntities != null) {
List<Map<String, Tag>> tileEntityTags = tileEntities.getValue().stream() for (LinCompoundTag tileEntity : tileEntities.value()) {
.map(tag -> (CompoundTag) tag) final BlockVector3 pt = clipboard.getMinimumPoint().add(
.map(CompoundTag::getValue) decodeBlockVector3(tileEntity.getTag("Pos", LinTagType.intArrayTag()))
.collect(Collectors.toList()); );
LinCompoundTag.Builder values = extractData(dataIsNested, tileEntity);
for (Map<String, Tag> tileEntity : tileEntityTags) { values.putInt("x", pt.x());
int[] pos = requireTag(tileEntity, "Pos", IntArrayTag.class).getValue(); values.putInt("y", pt.y());
final BlockVector3 pt = clipboard.getMinimumPoint().add(pos[0], pos[1], pos[2]); values.putInt("z", pt.z());
Map<String, Tag> values; values.put("id", tileEntity.value().get("Id"));
if (dataIsNested) {
CompoundTag dataTag = getTag(tileEntity, "Data", CompoundTag.class);
if (dataTag != null) {
values = new LinkedHashMap<>(dataTag.getValue());
} else {
values = new LinkedHashMap<>();
}
} else {
values = new LinkedHashMap<>(tileEntity);
values.remove("Id");
values.remove("Pos");
}
values.put("x", new IntTag(pt.getBlockX()));
values.put("y", new IntTag(pt.getBlockY()));
values.put("z", new IntTag(pt.getBlockZ()));
values.put("id", tileEntity.get("Id"));
if (fixer.isActive()) { if (fixer.isActive()) {
tileEntity = ((CompoundTag) AdventureNBTConverter.fromAdventure(fixer.fixUp( tileEntity = fixer.fixUp(DataFixer.FixTypes.BLOCK_ENTITY, values.build());
DataFixer.FixTypes.BLOCK_ENTITY,
new CompoundTag(values).asBinaryTag()
))).getValue();
} else { } else {
tileEntity = values; tileEntity = values.build();
} }
tileEntitiesMap.put(pt, tileEntity); tileEntitiesMap.put(pt, tileEntity);
} }
@ -196,20 +185,26 @@ public class ReaderUtil { //FAWE - make public
BlockVector3 rawPos = decodePositionFromDataIndex(width, length, index); BlockVector3 rawPos = decodePositionFromDataIndex(width, length, index);
try { try {
BlockVector3 offsetPos = clipboard.getMinimumPoint().add(rawPos); BlockVector3 offsetPos = clipboard.getMinimumPoint().add(rawPos);
Map<String, Tag> tileEntity = tileEntitiesMap.get(offsetPos); LinCompoundTag tileEntity = tileEntitiesMap.get(offsetPos);
if (tileEntity != null) { clipboard.setBlock(offsetPos, state.toBaseBlock(tileEntity));
clipboard.setBlock(
offsetPos, state.toBaseBlock(new CompoundTag(tileEntity))
);
} else {
clipboard.setBlock(offsetPos, state);
}
} catch (WorldEditException e) { } catch (WorldEditException e) {
throw new IOException("Failed to load a block in the schematic", e); throw new IOException("Failed to load a block in the schematic", e);
} }
} }
} }
private static LinCompoundTag.Builder extractData(boolean dataIsNested, LinCompoundTag tag) {
if (dataIsNested) {
LinCompoundTag dataTag = tag.findTag("Data", LinTagType.compoundTag());
return dataTag != null ? dataTag.toBuilder() : LinCompoundTag.builder();
} else {
LinCompoundTag.Builder values = tag.toBuilder();
values.remove("Id");
values.remove("Pos");
return values;
}
}
static BlockVector3 decodePositionFromDataIndex(int width, int length, int index) { static BlockVector3 decodePositionFromDataIndex(int width, int length, int index) {
// index = (y * width * length) + (z * width) + x // index = (y * width * length) + (z * width) + x
int y = index / (width * length); int y = index / (width * length);
@ -219,11 +214,11 @@ public class ReaderUtil { //FAWE - make public
return BlockVector3.at(x, y, z); return BlockVector3.at(x, y, z);
} }
static BlockVector3 decodeBlockVector3(@Nullable IntArrayTag tag) throws IOException { static BlockVector3 decodeBlockVector3(@Nullable LinIntArrayTag tag) throws IOException {
if (tag == null) { if (tag == null) {
return BlockVector3.ZERO; return BlockVector3.ZERO;
} }
int[] parts = tag.getValue(); int[] parts = tag.value();
if (parts.length != 3) { if (parts.length != 3) {
throw new IOException("Invalid block vector specified in schematic."); throw new IOException("Invalid block vector specified in schematic.");
} }
@ -231,46 +226,26 @@ public class ReaderUtil { //FAWE - make public
} }
static void readEntities( static void readEntities(
BlockArrayClipboard clipboard, List<Tag> entList, BlockArrayClipboard clipboard, List<? extends LinCompoundTag> entList,
VersionedDataFixer fixer, boolean positionIsRelative VersionedDataFixer fixer, boolean positionIsRelative
) throws IOException { ) {
if (entList.isEmpty()) { if (entList.isEmpty()) {
return; return;
} }
for (Tag et : entList) { for (LinCompoundTag entityTag : entList) {
if (!(et instanceof CompoundTag)) { String id = entityTag.getTag("Id", LinTagType.stringTag()).value();
continue; LinCompoundTag.Builder values = extractData(positionIsRelative, entityTag);
} LinCompoundTag dataTag = values.putString("id", id).build();
CompoundTag entityTag = (CompoundTag) et; dataTag = fixer.fixUp(DataFixer.FixTypes.ENTITY, dataTag);
Map<String, Tag> tags = entityTag.getValue();
String id = requireTag(tags, "Id", StringTag.class).getValue();
CompoundTagBuilder dataTagBuilder = CompoundTagBuilder.create();
if (positionIsRelative) {
// then we're in version 3
CompoundTag subTag = getTag(entityTag.getValue(), "Data", CompoundTag.class);
if (subTag != null) {
dataTagBuilder.putAll(subTag.getValue());
}
} else {
// version 2
dataTagBuilder.putAll(tags);
dataTagBuilder.remove("Id");
dataTagBuilder.remove("Pos");
}
CompoundTag dataTag = dataTagBuilder.putString("id", id).build();
dataTag = ((CompoundTag) AdventureNBTConverter.fromAdventure(fixer.fixUp(
DataFixer.FixTypes.ENTITY,
dataTag.asBinaryTag()
)));
EntityType entityType = EntityTypes.get(id); EntityType entityType = EntityTypes.get(id);
if (entityType != null) { if (entityType != null) {
Location location = NBTConversions.toLocation( Location location = NBTConversions.toLocation(
clipboard, clipboard,
requireTag(tags, "Pos", ListTag.class), entityTag.getListTag("Pos", LinTagType.doubleTag()),
requireTag(dataTag.getValue(), "Rotation", ListTag.class) dataTag.getListTag("Rotation", LinTagType.floatTag())
); );
BaseEntity state = new BaseEntity(entityType, dataTag); BaseEntity state = new BaseEntity(entityType, LazyReference.computed(dataTag));
if (positionIsRelative) { if (positionIsRelative) {
location = location.setPosition( location = location.setPosition(
location.toVector().add(clipboard.getMinimumPoint().toVector3()) location.toVector().add(clipboard.getMinimumPoint().toVector3())
@ -283,6 +258,25 @@ public class ReaderUtil { //FAWE - make public
} }
} }
static Int2ObjectMap<BiomeType> readBiomePalette(VersionedDataFixer fixer, LinCompoundTag paletteTag, Logger logger) throws
IOException {
Int2ObjectMap<BiomeType> palette = new Int2ObjectLinkedOpenHashMap<>(paletteTag.value().size());
for (var palettePart : paletteTag.value().entrySet()) {
String key = palettePart.getKey();
key = fixer.fixUp(DataFixer.FixTypes.BIOME, key);
BiomeType biome = BiomeTypes.get(key);
if (biome == null) {
logger.warn("Unknown biome type :" + key
+ " in palette. Are you missing a mod or using a schematic made in a newer version of Minecraft?");
}
if (!(palettePart.getValue() instanceof LinIntTag idTag)) {
throw new IOException("Biome mapped to non-Int tag.");
}
palette.put(idTag.valueAsInt(), biome);
}
return palette;
}
private ReaderUtil() { private ReaderUtil() {
} }

Datei anzeigen

@ -19,63 +19,54 @@
package com.sk89q.worldedit.extent.clipboard.io.sponge; package com.sk89q.worldedit.extent.clipboard.io.sponge;
import com.sk89q.jnbt.ByteArrayTag;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.IntArrayTag;
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.Tag;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.NBTSchematicReader; import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader;
import com.sk89q.worldedit.internal.Constants; import com.sk89q.worldedit.internal.Constants;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import org.enginehub.linbus.stream.LinStream;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinIntTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinRootEntry;
import org.enginehub.linbus.tree.LinTagType;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
import java.util.OptionalInt; import java.util.OptionalInt;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Reads schematic files using the Sponge Schematic Specification (Version 1). * Reads schematic files using the Sponge Schematic Specification (Version 1).
*/ */
public class SpongeSchematicV1Reader extends NBTSchematicReader { public class SpongeSchematicV1Reader implements ClipboardReader {
private final NBTInputStream inputStream; private final LinStream rootStream;
/** public SpongeSchematicV1Reader(LinStream rootStream) {
* Create a new instance. this.rootStream = rootStream;
*
* @param inputStream the input stream to read from
*/
public SpongeSchematicV1Reader(NBTInputStream inputStream) {
checkNotNull(inputStream);
this.inputStream = inputStream;
} }
@Override @Override
public Clipboard read() throws IOException { public Clipboard read() throws IOException {
CompoundTag schematicTag = getBaseTag(); LinCompoundTag schematicTag = getBaseTag();
ReaderUtil.checkSchematicVersion(1, getBaseTag()); ReaderUtil.checkSchematicVersion(1, schematicTag);
final Platform platform = WorldEdit.getInstance().getPlatformManager() return doRead(schematicTag);
.queryCapability(Capability.WORLD_EDITING); }
// For legacy SpongeSchematicReader, can be inlined in WorldEdit 8
public static BlockArrayClipboard doRead(LinCompoundTag schematicTag) throws IOException {
final Platform platform = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING);
// this is a relatively safe assumption unless someone imports a schematic from 1.12 // this is a relatively safe assumption unless someone imports a schematic from 1.12
// e.g. sponge 7.1- // e.g. sponge 7.1-
VersionedDataFixer fixer = new VersionedDataFixer( VersionedDataFixer fixer = new VersionedDataFixer(Constants.DATA_VERSION_MC_1_13_2, platform.getDataFixer());
Constants.DATA_VERSION_MC_1_13_2, platform.getDataFixer()
);
return readVersion1(schematicTag, fixer); return readVersion1(schematicTag, fixer);
} }
@ -90,64 +81,54 @@ public class SpongeSchematicV1Reader extends NBTSchematicReader {
} }
} }
private CompoundTag getBaseTag() throws IOException { private LinCompoundTag getBaseTag() throws IOException {
NamedTag rootTag = inputStream.readNamedTag(); return LinRootEntry.readFrom(rootStream).value();
return (CompoundTag) rootTag.getTag();
} }
static BlockArrayClipboard readVersion1(CompoundTag schematicTag, VersionedDataFixer fixer) throws IOException { static BlockArrayClipboard readVersion1(LinCompoundTag schematicTag, VersionedDataFixer fixer) throws IOException {
Map<String, Tag> schematic = schematicTag.getValue(); int width = schematicTag.getTag("Width", LinTagType.shortTag()).valueAsShort() & 0xFFFF;
int height = schematicTag.getTag("Height", LinTagType.shortTag()).valueAsShort() & 0xFFFF;
int length = schematicTag.getTag("Length", LinTagType.shortTag()).valueAsShort() & 0xFFFF;
int width = requireTag(schematic, "Width", ShortTag.class).getValue() & 0xFFFF; BlockVector3 min = ReaderUtil.decodeBlockVector3(schematicTag.findTag("Offset", LinTagType.intArrayTag()));
int height = requireTag(schematic, "Height", ShortTag.class).getValue() & 0xFFFF;
int length = requireTag(schematic, "Length", ShortTag.class).getValue() & 0xFFFF;
BlockVector3 min = ReaderUtil.decodeBlockVector3(
getTag(schematic, "Offset", IntArrayTag.class)
);
BlockVector3 offset = BlockVector3.ZERO; BlockVector3 offset = BlockVector3.ZERO;
CompoundTag metadataTag = getTag(schematic, "Metadata", CompoundTag.class); LinCompoundTag metadataTag = schematicTag.findTag("Metadata", LinTagType.compoundTag());
if (metadataTag != null && metadataTag.containsKey("WEOffsetX")) { if (metadataTag != null) {
// We appear to have WorldEdit Metadata LinIntTag offsetX = metadataTag.findTag("WEOffsetX", LinTagType.intTag());
Map<String, Tag> metadata = metadataTag.getValue(); if (offsetX != null) {
int offsetX = requireTag(metadata, "WEOffsetX", IntTag.class).getValue(); int offsetY = metadataTag.getTag("WEOffsetY", LinTagType.intTag()).valueAsInt();
int offsetY = requireTag(metadata, "WEOffsetY", IntTag.class).getValue(); int offsetZ = metadataTag.getTag("WEOffsetZ", LinTagType.intTag()).valueAsInt();
int offsetZ = requireTag(metadata, "WEOffsetZ", IntTag.class).getValue(); offset = BlockVector3.at(offsetX.valueAsInt(), offsetY, offsetZ);
offset = BlockVector3.at(offsetX, offsetY, offsetZ); }
} }
BlockVector3 origin = min.subtract(offset); BlockVector3 origin = min.subtract(offset);
Region region = new CuboidRegion(min, min.add(width, height, length).subtract(BlockVector3.ONE)); Region region = new CuboidRegion(min, min.add(width, height, length).subtract(BlockVector3.ONE));
IntTag paletteMaxTag = getTag(schematic, "PaletteMax", IntTag.class); LinIntTag paletteMaxTag = schematicTag.findTag("PaletteMax", LinTagType.intTag());
Map<String, Tag> paletteObject = requireTag(schematic, "Palette", CompoundTag.class).getValue(); LinCompoundTag paletteObject = schematicTag.getTag("Palette", LinTagType.compoundTag());
if (paletteMaxTag != null && paletteObject.size() != paletteMaxTag.getValue()) { if (paletteMaxTag != null && paletteObject.value().size() != paletteMaxTag.valueAsInt()) {
throw new IOException("Block palette size does not match expected size."); throw new IOException("Block palette size does not match expected size.");
} }
Map<Integer, BlockState> palette = ReaderUtil.decodePalette( Map<Integer, BlockState> palette = ReaderUtil.decodePalette(paletteObject, fixer);
paletteObject, fixer
);
byte[] blocks = requireTag(schematic, "BlockData", ByteArrayTag.class).getValue(); byte[] blocks = schematicTag.getTag("BlockData", LinTagType.byteArrayTag()).value();
ListTag tileEntities = getTag(schematic, "BlockEntities", ListTag.class); LinListTag<LinCompoundTag> tileEntities = schematicTag.findListTag("BlockEntities", LinTagType.compoundTag());
if (tileEntities == null) { if (tileEntities == null) {
tileEntities = getTag(schematic, "TileEntities", ListTag.class); tileEntities = schematicTag.findListTag("TileEntities", LinTagType.compoundTag());
} }
BlockArrayClipboard clipboard = new BlockArrayClipboard(region); BlockArrayClipboard clipboard = new BlockArrayClipboard(region);
clipboard.setOrigin(origin); clipboard.setOrigin(origin);
ReaderUtil.initializeClipboardFromBlocks( ReaderUtil.initializeClipboardFromBlocks(clipboard, palette, blocks, tileEntities, fixer, false);
clipboard, palette, blocks, tileEntities, fixer, false
);
return clipboard; return clipboard;
} }
@Override @Override
public void close() throws IOException { public void close() throws IOException {
inputStream.close();
} }
} }

Datei anzeigen

@ -19,66 +19,56 @@
package com.sk89q.worldedit.extent.clipboard.io.sponge; package com.sk89q.worldedit.extent.clipboard.io.sponge;
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.Tag;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.NBTSchematicReader; import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader;
import com.sk89q.worldedit.internal.util.LogManagerCompat; import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.internal.util.VarIntIterator; import com.sk89q.worldedit.internal.util.VarIntIterator;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.DataFixer;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes; import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.enginehub.linbus.stream.LinStream;
import org.enginehub.linbus.tree.LinByteArrayTag;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinIntTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinRootEntry;
import org.enginehub.linbus.tree.LinTagType;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.OptionalInt; import java.util.OptionalInt;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Reads schematic files using the Sponge Schematic Specification (Version 2). * Reads schematic files using the Sponge Schematic Specification (Version 2).
*/ */
public class SpongeSchematicV2Reader extends NBTSchematicReader { public class SpongeSchematicV2Reader implements ClipboardReader {
private static final Logger LOGGER = LogManagerCompat.getLogger(); private static final Logger LOGGER = LogManagerCompat.getLogger();
private final NBTInputStream inputStream; private final LinStream rootStream;
/** public SpongeSchematicV2Reader(LinStream rootStream) {
* Create a new instance. this.rootStream = rootStream;
*
* @param inputStream the input stream to read from
*/
public SpongeSchematicV2Reader(NBTInputStream inputStream) {
checkNotNull(inputStream);
this.inputStream = inputStream;
} }
@Override @Override
public Clipboard read() throws IOException { public Clipboard read() throws IOException {
CompoundTag schematicTag = getBaseTag(); LinCompoundTag schematicTag = getBaseTag();
ReaderUtil.checkSchematicVersion(2, schematicTag); ReaderUtil.checkSchematicVersion(2, schematicTag);
final Platform platform = WorldEdit.getInstance().getPlatformManager() return doRead(schematicTag);
.queryCapability(Capability.WORLD_EDITING); }
// For legacy SpongeSchematicReader, can be inlined in WorldEdit 8
public static Clipboard doRead(LinCompoundTag schematicTag) throws IOException {
final Platform platform = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING);
int liveDataVersion = platform.getDataVersion(); int liveDataVersion = platform.getDataVersion();
VersionedDataFixer fixer = ReaderUtil.getVersionedDataFixer( VersionedDataFixer fixer = ReaderUtil.getVersionedDataFixer(schematicTag, platform, liveDataVersion);
schematicTag.getValue(), platform, liveDataVersion
);
BlockArrayClipboard clip = SpongeSchematicV1Reader.readVersion1(schematicTag, fixer); BlockArrayClipboard clip = SpongeSchematicV1Reader.readVersion1(schematicTag, fixer);
return readVersion2(clip, schematicTag, fixer); return readVersion2(clip, schematicTag, fixer);
} }
@ -86,11 +76,10 @@ public class SpongeSchematicV2Reader extends NBTSchematicReader {
@Override @Override
public OptionalInt getDataVersion() { public OptionalInt getDataVersion() {
try { try {
CompoundTag schematicTag = getBaseTag(); LinCompoundTag schematicTag = getBaseTag();
ReaderUtil.checkSchematicVersion(2, schematicTag); ReaderUtil.checkSchematicVersion(2, schematicTag);
int dataVersion = requireTag(schematicTag.getValue(), "DataVersion", IntTag.class) int dataVersion = schematicTag.getTag("DataVersion", LinTagType.intTag()).valueAsInt();
.getValue();
if (dataVersion < 0) { if (dataVersion < 0) {
return OptionalInt.empty(); return OptionalInt.empty();
} }
@ -100,67 +89,48 @@ public class SpongeSchematicV2Reader extends NBTSchematicReader {
} }
} }
private CompoundTag getBaseTag() throws IOException { private LinCompoundTag getBaseTag() throws IOException {
NamedTag rootTag = inputStream.readNamedTag(); return LinRootEntry.readFrom(rootStream).value();
return (CompoundTag) rootTag.getTag();
} }
private Clipboard readVersion2(BlockArrayClipboard version1, CompoundTag schematicTag, private static Clipboard readVersion2(
VersionedDataFixer fixer) throws IOException { BlockArrayClipboard version1, LinCompoundTag schematicTag, VersionedDataFixer fixer
Map<String, Tag> schematic = schematicTag.getValue(); ) throws IOException {
if (schematic.containsKey("BiomeData")) { if (schematicTag.value().containsKey("BiomeData")) {
readBiomes2(version1, schematic, fixer); readBiomes2(version1, schematicTag, fixer);
} }
ListTag entities = getTag(schematic, "Entities", ListTag.class); LinListTag<LinCompoundTag> entities = schematicTag.findListTag("Entities", LinTagType.compoundTag());
if (entities != null) { if (entities != null) {
ReaderUtil.readEntities( ReaderUtil.readEntities(version1, entities.value(), fixer, false);
version1, entities.getValue(), fixer, false
);
} }
return version1; return version1;
} }
private void readBiomes2(BlockArrayClipboard clipboard, Map<String, Tag> schematic, private static void readBiomes2(
VersionedDataFixer fixer) throws IOException { BlockArrayClipboard clipboard, LinCompoundTag schematic, VersionedDataFixer fixer
ByteArrayTag dataTag = requireTag(schematic, "BiomeData", ByteArrayTag.class); ) throws IOException {
IntTag maxTag = requireTag(schematic, "BiomePaletteMax", IntTag.class); LinByteArrayTag dataTag = schematic.getTag("BiomeData", LinTagType.byteArrayTag());
CompoundTag paletteTag = requireTag(schematic, "BiomePalette", CompoundTag.class); LinIntTag maxTag = schematic.getTag("BiomePaletteMax", LinTagType.intTag());
LinCompoundTag paletteTag = schematic.getTag("BiomePalette", LinTagType.compoundTag());
Map<Integer, BiomeType> palette = new HashMap<>(); if (maxTag.valueAsInt() != paletteTag.value().size()) {
if (maxTag.getValue() != paletteTag.getValue().size()) {
throw new IOException("Biome palette size does not match expected size."); throw new IOException("Biome palette size does not match expected size.");
} }
for (Entry<String, Tag> palettePart : paletteTag.getValue().entrySet()) { Int2ObjectMap<BiomeType> palette = ReaderUtil.readBiomePalette(fixer, paletteTag, LOGGER);
String key = palettePart.getKey();
key = fixer.fixUp(DataFixer.FixTypes.BIOME, key);
BiomeType biome = BiomeTypes.get(key);
if (biome == null) {
LOGGER.warn("Unknown biome type :" + key
+ " in palette. Are you missing a mod or using a schematic made in a newer version of Minecraft?");
}
Tag idTag = palettePart.getValue();
if (!(idTag instanceof IntTag)) {
throw new IOException("Biome mapped to non-Int tag.");
}
palette.put(((IntTag) idTag).getValue(), biome);
}
int width = clipboard.getDimensions().getX(); int width = clipboard.getDimensions().x();
byte[] biomes = dataTag.getValue(); byte[] biomes = dataTag.value();
BlockVector3 min = clipboard.getMinimumPoint(); BlockVector3 min = clipboard.getMinimumPoint();
int index = 0; int index = 0;
for (VarIntIterator iter = new VarIntIterator(biomes); iter.hasNext(); index++) { for (VarIntIterator iter = new VarIntIterator(biomes); iter.hasNext(); index++) {
int nextBiomeId = iter.nextInt(); int nextBiomeId = iter.nextInt();
BiomeType type = palette.get(nextBiomeId); BiomeType type = palette.get(nextBiomeId);
// hack -- the x and y values from the 3d decode with length == 1 are equivalent // hack -- the x and y values from the 3d decode with length == 1 are equivalent
BlockVector3 hackDecode = ReaderUtil.decodePositionFromDataIndex( BlockVector3 hackDecode = ReaderUtil.decodePositionFromDataIndex(width, 1, index);
width, 1, index int x = hackDecode.x();
); int z = hackDecode.y();
int x = hackDecode.getX();
int z = hackDecode.getY();
for (int y = 0; y < clipboard.getRegion().getHeight(); y++) { for (int y = 0; y < clipboard.getRegion().getHeight(); y++) {
clipboard.setBiome(min.add(x, y, z), type); clipboard.setBiome(min.add(x, y, z), type);
} }
@ -169,6 +139,6 @@ public class SpongeSchematicV2Reader extends NBTSchematicReader {
@Override @Override
public void close() throws IOException { public void close() throws IOException {
inputStream.close();
} }
} }

Datei anzeigen

@ -19,18 +19,6 @@
package com.sk89q.worldedit.extent.clipboard.io.sponge; package com.sk89q.worldedit.extent.clipboard.io.sponge;
import com.fastasyncworldedit.core.Fawe;
import com.fastasyncworldedit.core.extent.clipboard.io.FastSchematicWriterV2;
import com.google.common.collect.ImmutableMap;
import com.sk89q.jnbt.ByteArrayTag;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.IntArrayTag;
import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.NBTOutputStream;
import com.sk89q.jnbt.ShortTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
@ -40,38 +28,30 @@ import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntMaps;
import org.enginehub.linbus.stream.LinBinaryIO;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinRootEntry;
import org.enginehub.linbus.tree.LinTagType;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Writes schematic files using the Sponge Schematic Specification (Version 2). * Writes schematic files using the Sponge Schematic Specification (Version 2).
*
* @deprecated Slow, resource intensive, but sometimes safer than using the recommended
* {@link FastSchematicWriterV2}.
* Avoid using large clipboards to create schematics with this writer.
*/ */
@Deprecated
public class SpongeSchematicV2Writer implements ClipboardWriter { public class SpongeSchematicV2Writer implements ClipboardWriter {
private static final int CURRENT_VERSION = 2; private static final int CURRENT_VERSION = 2;
private static final int MAX_SIZE = Short.MAX_VALUE - Short.MIN_VALUE; private static final int MAX_SIZE = Short.MAX_VALUE - Short.MIN_VALUE;
private final NBTOutputStream outputStream; private final DataOutputStream outputStream;
/** public SpongeSchematicV2Writer(DataOutputStream outputStream) {
* Create a new schematic writer.
*
* @param outputStream the output stream to write to
*/
public SpongeSchematicV2Writer(NBTOutputStream outputStream) {
checkNotNull(outputStream);
this.outputStream = outputStream; this.outputStream = outputStream;
} }
@ -81,17 +61,16 @@ public class SpongeSchematicV2Writer implements ClipboardWriter {
// between upstream and FAWE // between upstream and FAWE
clipboard.flush(); clipboard.flush();
//FAWE end //FAWE end
// For now always write the latest version. Maybe provide support for earlier if more appear. LinBinaryIO.write(outputStream, new LinRootEntry("Schematic", write2(clipboard)));
outputStream.writeNamedTag("Schematic", new CompoundTag(write2(clipboard)));
} }
/** /**
* Writes a version 2 schematic file. * Writes a version 2 schematic file.
* *
* @param clipboard The clipboard * @param clipboard The clipboard
* @return The schematic map * @return the schematic tag
*/ */
private Map<String, Tag> write2(Clipboard clipboard) { private LinCompoundTag write2(Clipboard clipboard) {
Region region = clipboard.getRegion(); Region region = clipboard.getRegion();
BlockVector3 origin = clipboard.getOrigin(); BlockVector3 origin = clipboard.getOrigin();
BlockVector3 min = region.getMinimumPoint(); BlockVector3 min = region.getMinimumPoint();
@ -110,52 +89,49 @@ public class SpongeSchematicV2Writer implements ClipboardWriter {
throw new IllegalArgumentException("Length of region too large for a .schematic"); throw new IllegalArgumentException("Length of region too large for a .schematic");
} }
Map<String, Tag> schematic = new HashMap<>(); LinCompoundTag.Builder schematic = LinCompoundTag.builder();
schematic.put("Version", new IntTag(CURRENT_VERSION)); schematic.putInt("Version", CURRENT_VERSION);
schematic.put("DataVersion", new IntTag( schematic.putInt("DataVersion",
WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).getDataVersion())); WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).getDataVersion()
);
Map<String, Tag> metadata = new HashMap<>(); LinCompoundTag.Builder metadata = LinCompoundTag.builder();
metadata.put("WEOffsetX", new IntTag(offset.x())); metadata.putInt("WEOffsetX", offset.x());
metadata.put("WEOffsetY", new IntTag(offset.y())); metadata.putInt("WEOffsetY", offset.y());
metadata.put("WEOffsetZ", new IntTag(offset.z())); metadata.putInt("WEOffsetZ", offset.z());
metadata.put("FAWEVersion", new IntTag(Fawe.instance().getVersion().build));
Map<String, Tag> worldEditSection = new HashMap<>(); LinCompoundTag.Builder worldEditSection = LinCompoundTag.builder();
worldEditSection.put("Version", new StringTag(WorldEdit.getVersion())); worldEditSection.putString("Version", WorldEdit.getVersion());
worldEditSection.put("EditingPlatform", new StringTag(WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).getId())); worldEditSection.putString("EditingPlatform",
worldEditSection.put("Offset", new IntArrayTag(new int[] { WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).id()
offset.getBlockX(), offset.getBlockY(), offset.getBlockZ() );
})); worldEditSection.putIntArray("Offset", new int[]{offset.x(), offset.y(), offset.z()});
Map<String, Tag> platformsSection = new HashMap<>(); LinCompoundTag.Builder platformsSection = LinCompoundTag.builder();
for (Platform platform : WorldEdit.getInstance().getPlatformManager().getPlatforms()) { for (Platform platform : WorldEdit.getInstance().getPlatformManager().getPlatforms()) {
platformsSection.put(platform.getId(), new CompoundTag(ImmutableMap.of( platformsSection.put(platform.id(), LinCompoundTag
"Name", new StringTag(platform.getPlatformName()), .builder()
"Version", new StringTag(platform.getPlatformVersion()) .putString("Name", platform.getPlatformName())
))); .putString("Version", platform.getPlatformVersion())
.build());
} }
worldEditSection.put("Platforms", new CompoundTag(platformsSection)); worldEditSection.put("Platforms", platformsSection.build());
metadata.put("WorldEdit", new CompoundTag(worldEditSection)); metadata.put("WorldEdit", worldEditSection.build());
schematic.put("Metadata", new CompoundTag(metadata)); schematic.put("Metadata", metadata.build());
schematic.put("Width", new ShortTag((short) width)); schematic.putShort("Width", (short) width);
schematic.put("Height", new ShortTag((short) height)); schematic.putShort("Height", (short) height);
schematic.put("Length", new ShortTag((short) length)); schematic.putShort("Length", (short) length);
// The Sponge format Offset refers to the 'min' points location in the world. That's our 'Origin' // The Sponge format Offset refers to the 'min' points location in the world. That's our 'Origin'
schematic.put("Offset", new IntArrayTag(new int[]{ schematic.putIntArray("Offset", new int[]{min.x(), min.y(), min.z(),});
min.x(),
min.y(),
min.z(),
}));
int paletteMax = 0; int paletteMax = 0;
Map<String, Integer> palette = new HashMap<>(); Object2IntMap<String> palette = new Object2IntLinkedOpenHashMap<>();
List<CompoundTag> tileEntities = new ArrayList<>(); LinListTag.Builder<LinCompoundTag> tileEntities = LinListTag.builder(LinTagType.compoundTag());
ByteArrayOutputStream buffer = new ByteArrayOutputStream(width * height * length); ByteArrayOutputStream buffer = new ByteArrayOutputStream(width * height * length);
@ -167,8 +143,9 @@ public class SpongeSchematicV2Writer implements ClipboardWriter {
int x0 = min.x() + x; int x0 = min.x() + x;
BlockVector3 point = BlockVector3.at(x0, y0, z0); BlockVector3 point = BlockVector3.at(x0, y0, z0);
BaseBlock block = clipboard.getFullBlock(point); BaseBlock block = clipboard.getFullBlock(point);
if (block.getNbtData() != null) { LinCompoundTag nbt = block.getNbt();
Map<String, Tag> values = new HashMap<>(block.getNbtData().getValue()); if (nbt != null) {
LinCompoundTag.Builder values = nbt.toBuilder();
values.remove("id"); // Remove 'id' if it exists. We want 'Id' values.remove("id"); // Remove 'id' if it exists. We want 'Id'
@ -177,16 +154,16 @@ public class SpongeSchematicV2Writer implements ClipboardWriter {
values.remove("y"); values.remove("y");
values.remove("z"); values.remove("z");
values.put("Id", new StringTag(block.getNbtId())); values.putString("Id", block.getNbtId());
values.put("Pos", new IntArrayTag(new int[]{x, y, z})); values.putIntArray("Pos", new int[]{x, y, z});
tileEntities.add(new CompoundTag(values)); tileEntities.add(values.build());
} }
String blockKey = block.toImmutableState().getAsString(); String blockKey = block.toImmutableState().getAsString();
int blockId; int blockId;
if (palette.containsKey(blockKey)) { if (palette.containsKey(blockKey)) {
blockId = palette.get(blockKey); blockId = palette.getInt(blockKey);
} else { } else {
blockId = paletteMax; blockId = paletteMax;
palette.put(blockKey, blockId); palette.put(blockKey, blockId);
@ -202,14 +179,14 @@ public class SpongeSchematicV2Writer implements ClipboardWriter {
} }
} }
schematic.put("PaletteMax", new IntTag(paletteMax)); schematic.putInt("PaletteMax", paletteMax);
Map<String, Tag> paletteTag = new HashMap<>(); LinCompoundTag.Builder paletteTag = LinCompoundTag.builder();
palette.forEach((key, value) -> paletteTag.put(key, new IntTag(value))); Object2IntMaps.fastForEach(palette, e -> paletteTag.putInt(e.getKey(), e.getIntValue()));
schematic.put("Palette", new CompoundTag(paletteTag)); schematic.put("Palette", paletteTag.build());
schematic.put("BlockData", new ByteArrayTag(buffer.toByteArray())); schematic.putByteArray("BlockData", buffer.toByteArray());
schematic.put("BlockEntities", new ListTag(CompoundTag.class, tileEntities)); schematic.put("BlockEntities", tileEntities.build());
// version 2 stuff // version 2 stuff
if (clipboard.hasBiomes()) { if (clipboard.hasBiomes()) {
@ -217,16 +194,16 @@ public class SpongeSchematicV2Writer implements ClipboardWriter {
} }
if (!clipboard.getEntities().isEmpty()) { if (!clipboard.getEntities().isEmpty()) {
ListTag value = WriterUtil.encodeEntities(clipboard, false); LinListTag<LinCompoundTag> value = WriterUtil.encodeEntities(clipboard, false);
if (value != null) { if (value != null) {
schematic.put("Entities", value); schematic.put("Entities", value);
} }
} }
return schematic; return schematic.build();
} }
private void writeBiomes(Clipboard clipboard, Map<String, Tag> schematic) { private void writeBiomes(Clipboard clipboard, LinCompoundTag.Builder schematic) {
BlockVector3 min = clipboard.getMinimumPoint(); BlockVector3 min = clipboard.getMinimumPoint();
int width = clipboard.getRegion().getWidth(); int width = clipboard.getRegion().getWidth();
int length = clipboard.getRegion().getLength(); int length = clipboard.getRegion().getLength();
@ -234,7 +211,7 @@ public class SpongeSchematicV2Writer implements ClipboardWriter {
ByteArrayOutputStream buffer = new ByteArrayOutputStream(width * length); ByteArrayOutputStream buffer = new ByteArrayOutputStream(width * length);
int paletteMax = 0; int paletteMax = 0;
Map<String, Integer> palette = new HashMap<>(); Object2IntMap<String> palette = new Object2IntLinkedOpenHashMap<>();
for (int z = 0; z < length; z++) { for (int z = 0; z < length; z++) {
int z0 = min.z() + z; int z0 = min.z() + z;
@ -246,7 +223,7 @@ public class SpongeSchematicV2Writer implements ClipboardWriter {
String biomeKey = biome.id(); String biomeKey = biome.id();
int biomeId; int biomeId;
if (palette.containsKey(biomeKey)) { if (palette.containsKey(biomeKey)) {
biomeId = palette.get(biomeKey); biomeId = palette.getInt(biomeKey);
} else { } else {
biomeId = paletteMax; biomeId = paletteMax;
palette.put(biomeKey, biomeId); palette.put(biomeKey, biomeId);
@ -261,13 +238,13 @@ public class SpongeSchematicV2Writer implements ClipboardWriter {
} }
} }
schematic.put("BiomePaletteMax", new IntTag(paletteMax)); schematic.putInt("BiomePaletteMax", paletteMax);
Map<String, Tag> paletteTag = new HashMap<>(); LinCompoundTag.Builder paletteTag = LinCompoundTag.builder();
palette.forEach((key, value) -> paletteTag.put(key, new IntTag(value))); Object2IntMaps.fastForEach(palette, e -> paletteTag.putInt(e.getKey(), e.getIntValue()));
schematic.put("BiomePalette", new CompoundTag(paletteTag)); schematic.put("BiomePalette", paletteTag.build());
schematic.put("BiomeData", new ByteArrayTag(buffer.toByteArray())); schematic.putByteArray("BiomeData", buffer.toByteArray());
} }
@Override @Override

Datei anzeigen

@ -19,82 +19,62 @@
package com.sk89q.worldedit.extent.clipboard.io.sponge; package com.sk89q.worldedit.extent.clipboard.io.sponge;
import com.sk89q.jnbt.ByteArrayTag;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.IntArrayTag;
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.Tag;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.NBTSchematicReader; import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader;
import com.sk89q.worldedit.extent.clipboard.io.SchematicNbtUtil;
import com.sk89q.worldedit.internal.util.LogManagerCompat; import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.internal.util.VarIntIterator; import com.sk89q.worldedit.internal.util.VarIntIterator;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.DataFixer;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.enginehub.linbus.stream.LinStream;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinRootEntry;
import org.enginehub.linbus.tree.LinTagType;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.OptionalInt; import java.util.OptionalInt;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Reads schematic files using the Sponge Schematic Specification. * Reads schematic files using the Sponge Schematic Specification.
*/ */
public class SpongeSchematicV3Reader extends NBTSchematicReader { public class SpongeSchematicV3Reader implements ClipboardReader {
private static final Logger LOGGER = LogManagerCompat.getLogger(); private static final Logger LOGGER = LogManagerCompat.getLogger();
private final NBTInputStream inputStream; private final LinStream rootStream;
/** public SpongeSchematicV3Reader(LinStream rootStream) {
* Create a new instance. this.rootStream = rootStream;
*
* @param inputStream the input stream to read from
*/
public SpongeSchematicV3Reader(NBTInputStream inputStream) {
checkNotNull(inputStream);
this.inputStream = inputStream;
} }
@Override @Override
public Clipboard read() throws IOException { public Clipboard read() throws IOException {
CompoundTag schematicTag = getBaseTag(); LinCompoundTag schematicTag = getBaseTag();
ReaderUtil.checkSchematicVersion(3, schematicTag); ReaderUtil.checkSchematicVersion(3, schematicTag);
final Platform platform = WorldEdit.getInstance().getPlatformManager() final Platform platform = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING);
.queryCapability(Capability.WORLD_EDITING);
int liveDataVersion = platform.getDataVersion(); int liveDataVersion = platform.getDataVersion();
VersionedDataFixer fixer = ReaderUtil.getVersionedDataFixer( VersionedDataFixer fixer = ReaderUtil.getVersionedDataFixer(schematicTag, platform, liveDataVersion);
schematicTag.getValue(), platform, liveDataVersion
);
return readVersion3(schematicTag, fixer); return readVersion3(schematicTag, fixer);
} }
@Override @Override
public OptionalInt getDataVersion() { public OptionalInt getDataVersion() {
try { try {
CompoundTag schematicTag = getBaseTag(); LinCompoundTag schematicTag = getBaseTag();
ReaderUtil.checkSchematicVersion(3, schematicTag); ReaderUtil.checkSchematicVersion(3, schematicTag);
int dataVersion = requireTag(schematicTag.getValue(), "DataVersion", IntTag.class) int dataVersion = schematicTag.getTag("DataVersion", LinTagType.intTag()).valueAsInt();
.getValue();
if (dataVersion < 0) { if (dataVersion < 0) {
return OptionalInt.empty(); return OptionalInt.empty();
} }
@ -104,112 +84,85 @@ public class SpongeSchematicV3Reader extends NBTSchematicReader {
} }
} }
private CompoundTag getBaseTag() throws IOException { private LinCompoundTag getBaseTag() throws IOException {
NamedTag rootTag = inputStream.readNamedTag(); return LinRootEntry.readFrom(rootStream).value().getTag("Schematic", LinTagType.compoundTag());
CompoundTag schematicTag = (CompoundTag) rootTag.getTag();
// Nested inside the root tag
return requireTag(schematicTag.getValue(), "Schematic", CompoundTag.class);
} }
private Clipboard readVersion3(CompoundTag schematicTag, VersionedDataFixer fixer) throws IOException { private Clipboard readVersion3(LinCompoundTag schematicTag, VersionedDataFixer fixer) throws IOException {
Map<String, Tag> schematic = schematicTag.getValue(); int width = schematicTag.getTag("Width", LinTagType.shortTag()).valueAsShort() & 0xFFFF;
int height = schematicTag.getTag("Height", LinTagType.shortTag()).valueAsShort() & 0xFFFF;
int length = schematicTag.getTag("Length", LinTagType.shortTag()).valueAsShort() & 0xFFFF;
int width = requireTag(schematic, "Width", ShortTag.class).getValue() & 0xFFFF; BlockVector3 offset = ReaderUtil.decodeBlockVector3(schematicTag.findTag("Offset", LinTagType.intArrayTag()));
int height = requireTag(schematic, "Height", ShortTag.class).getValue() & 0xFFFF;
int length = requireTag(schematic, "Length", ShortTag.class).getValue() & 0xFFFF;
BlockVector3 offset = ReaderUtil.decodeBlockVector3(
SchematicNbtUtil.getTag(schematic, "Offset", IntArrayTag.class)
);
BlockVector3 origin = BlockVector3.ZERO; BlockVector3 origin = BlockVector3.ZERO;
CompoundTag metadataTag = getTag(schematic, "Metadata", CompoundTag.class); LinCompoundTag metadataTag = schematicTag.findTag("Metadata", LinTagType.compoundTag());
if (metadataTag != null && metadataTag.containsKey("WorldEdit")) { if (metadataTag != null) {
// We appear to have WorldEdit Metadata LinCompoundTag worldeditMeta = metadataTag.findTag("WorldEdit", LinTagType.compoundTag());
Map<String, Tag> worldedit = if (worldeditMeta != null) {
requireTag(metadataTag.getValue(), "WorldEdit", CompoundTag.class).getValue(); origin = ReaderUtil.decodeBlockVector3(worldeditMeta.findTag("Origin", LinTagType.intArrayTag()));
origin = ReaderUtil.decodeBlockVector3( }
SchematicNbtUtil.getTag(worldedit, "Origin", IntArrayTag.class)
);
} }
BlockVector3 min = offset.add(origin); BlockVector3 min = offset.add(origin);
BlockArrayClipboard clipboard = new BlockArrayClipboard( BlockArrayClipboard clipboard = new BlockArrayClipboard(new CuboidRegion(
new CuboidRegion(min, min.add(width, height, length).subtract(BlockVector3.ONE)) min,
); min.add(width, height, length).subtract(BlockVector3.ONE)
));
clipboard.setOrigin(origin); clipboard.setOrigin(origin);
decodeBlocksIntoClipboard(fixer, schematic, clipboard); decodeBlocksIntoClipboard(fixer, schematicTag, clipboard);
CompoundTag biomeContainer = getTag(schematic, "Biomes", CompoundTag.class); LinCompoundTag biomeContainer = schematicTag.findTag("Biomes", LinTagType.compoundTag());
if (biomeContainer != null) { if (biomeContainer != null) {
readBiomes3(clipboard, biomeContainer.getValue(), fixer); readBiomes3(clipboard, biomeContainer, fixer);
} }
ListTag entities = getTag(schematic, "Entities", ListTag.class); LinListTag<LinCompoundTag> entities = schematicTag.findListTag("Entities", LinTagType.compoundTag());
if (entities != null) { if (entities != null) {
ReaderUtil.readEntities(clipboard, entities.getValue(), fixer, true); ReaderUtil.readEntities(clipboard, entities.value(), fixer, true);
} }
return clipboard; return clipboard;
} }
private void decodeBlocksIntoClipboard(VersionedDataFixer fixer, Map<String, Tag> schematic, private void decodeBlocksIntoClipboard(
BlockArrayClipboard clipboard) throws IOException { VersionedDataFixer fixer, LinCompoundTag schematic, BlockArrayClipboard clipboard
Map<String, Tag> blockContainer = requireTag(schematic, "Blocks", CompoundTag.class).getValue(); ) throws IOException {
LinCompoundTag blockContainer = schematic.getTag("Blocks", LinTagType.compoundTag());
Map<String, Tag> paletteObject = requireTag(blockContainer, "Palette", CompoundTag.class).getValue(); LinCompoundTag paletteObject = blockContainer.getTag("Palette", LinTagType.compoundTag());
Map<Integer, BlockState> palette = ReaderUtil.decodePalette( Map<Integer, BlockState> palette = ReaderUtil.decodePalette(paletteObject, fixer);
paletteObject, fixer
);
byte[] blocks = requireTag(blockContainer, "Data", ByteArrayTag.class).getValue(); byte[] blocks = blockContainer.getTag("Data", LinTagType.byteArrayTag()).value();
ListTag tileEntities = getTag(blockContainer, "BlockEntities", ListTag.class); LinListTag<LinCompoundTag> blockEntities = blockContainer.getListTag("BlockEntities", LinTagType.compoundTag());
ReaderUtil.initializeClipboardFromBlocks( ReaderUtil.initializeClipboardFromBlocks(clipboard, palette, blocks, blockEntities, fixer, true);
clipboard, palette, blocks, tileEntities, fixer, true
);
} }
private void readBiomes3(BlockArrayClipboard clipboard, Map<String, Tag> biomeContainer, private void readBiomes3(
VersionedDataFixer fixer) throws IOException { BlockArrayClipboard clipboard, LinCompoundTag biomeContainer, VersionedDataFixer fixer
CompoundTag paletteTag = requireTag(biomeContainer, "Palette", CompoundTag.class); ) throws IOException {
LinCompoundTag paletteTag = biomeContainer.getTag("Palette", LinTagType.compoundTag());
Map<Integer, BiomeType> palette = new HashMap<>(); Int2ObjectMap<BiomeType> palette = ReaderUtil.readBiomePalette(fixer, paletteTag, LOGGER);
for (Entry<String, Tag> palettePart : paletteTag.getValue().entrySet()) {
String key = palettePart.getKey();
key = fixer.fixUp(DataFixer.FixTypes.BIOME, key);
BiomeType biome = BiomeTypes.get(key);
if (biome == null) {
LOGGER.warn("Unknown biome type `" + key + "` in palette."
+ " Are you missing a mod or using a schematic made in a newer version of Minecraft?");
}
Tag idTag = palettePart.getValue();
if (!(idTag instanceof IntTag)) {
throw new IOException("Biome mapped to non-Int tag.");
}
palette.put(((IntTag) idTag).getValue(), biome);
}
int width = clipboard.getRegion().getWidth(); int width = clipboard.getRegion().getWidth();
int length = clipboard.getRegion().getLength(); int length = clipboard.getRegion().getLength();
byte[] biomes = requireTag(biomeContainer, "Data", ByteArrayTag.class).getValue(); byte[] biomes = biomeContainer.getTag("Data", LinTagType.byteArrayTag()).value();
BlockVector3 min = clipboard.getMinimumPoint(); BlockVector3 min = clipboard.getMinimumPoint();
int index = 0; int index = 0;
for (VarIntIterator iter = new VarIntIterator(biomes); iter.hasNext(); index++) { for (VarIntIterator iter = new VarIntIterator(biomes); iter.hasNext(); index++) {
int nextBiomeId = iter.nextInt(); int nextBiomeId = iter.nextInt();
BiomeType type = palette.get(nextBiomeId); BiomeType type = palette.get(nextBiomeId);
BlockVector3 pos = ReaderUtil.decodePositionFromDataIndex( BlockVector3 pos = ReaderUtil.decodePositionFromDataIndex(width, length, index);
width, length, index
);
clipboard.setBiome(min.add(pos), type); clipboard.setBiome(min.add(pos), type);
} }
} }
@Override @Override
public void close() throws IOException { public void close() throws IOException {
inputStream.close();
} }
} }

Datei anzeigen

@ -19,19 +19,6 @@
package com.sk89q.worldedit.extent.clipboard.io.sponge; package com.sk89q.worldedit.extent.clipboard.io.sponge;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.sk89q.jnbt.ByteArrayTag;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.CompoundTagBuilder;
import com.sk89q.jnbt.IntArrayTag;
import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.LongTag;
import com.sk89q.jnbt.NBTOutputStream;
import com.sk89q.jnbt.ShortTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
@ -40,18 +27,20 @@ import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntMaps;
import org.enginehub.linbus.stream.LinBinaryIO;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinRootEntry;
import org.enginehub.linbus.tree.LinTagType;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Writes schematic files using the Sponge Schematic Specification (Version 3). * Writes schematic files using the Sponge Schematic Specification (Version 3).
*/ */
@ -60,15 +49,9 @@ public class SpongeSchematicV3Writer implements ClipboardWriter {
private static final int CURRENT_VERSION = 3; private static final int CURRENT_VERSION = 3;
private static final int MAX_SIZE = Short.MAX_VALUE - Short.MIN_VALUE; private static final int MAX_SIZE = Short.MAX_VALUE - Short.MIN_VALUE;
private final NBTOutputStream outputStream; private final DataOutputStream outputStream;
/** public SpongeSchematicV3Writer(DataOutputStream outputStream) {
* Create a new schematic writer.
*
* @param outputStream the output stream to write to
*/
public SpongeSchematicV3Writer(NBTOutputStream outputStream) {
checkNotNull(outputStream);
this.outputStream = outputStream; this.outputStream = outputStream;
} }
@ -78,9 +61,8 @@ public class SpongeSchematicV3Writer implements ClipboardWriter {
// between upstream and FAWE // between upstream and FAWE
clipboard.flush(); clipboard.flush();
//FAWE end //FAWE end
// For now always write the latest version. Maybe provide support for earlier if more appear. LinBinaryIO.write(outputStream,
outputStream.writeNamedTag("", new LinRootEntry("", LinCompoundTag.builder().put("Schematic", write3(clipboard)).build())
new CompoundTag(ImmutableMap.of("Schematic", new CompoundTag(write3(clipboard))))
); );
} }
@ -90,7 +72,7 @@ public class SpongeSchematicV3Writer implements ClipboardWriter {
* @param clipboard The clipboard * @param clipboard The clipboard
* @return The schematic map * @return The schematic map
*/ */
private Map<String, Tag> write3(Clipboard clipboard) { private LinCompoundTag write3(Clipboard clipboard) {
Region region = clipboard.getRegion(); Region region = clipboard.getRegion();
BlockVector3 origin = clipboard.getOrigin(); BlockVector3 origin = clipboard.getOrigin();
BlockVector3 min = region.getMinimumPoint(); BlockVector3 min = region.getMinimumPoint();
@ -109,43 +91,41 @@ public class SpongeSchematicV3Writer implements ClipboardWriter {
throw new IllegalArgumentException("Length of region too large for a .schematic"); throw new IllegalArgumentException("Length of region too large for a .schematic");
} }
Map<String, Tag> schematic = new HashMap<>(); LinCompoundTag.Builder schematic = LinCompoundTag.builder();
schematic.put("Version", new IntTag(CURRENT_VERSION)); schematic.putInt("Version", CURRENT_VERSION);
schematic.put("DataVersion", new IntTag( schematic.putInt("DataVersion",
WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).getDataVersion())); WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).getDataVersion()
);
Map<String, Tag> metadata = new HashMap<>(); LinCompoundTag.Builder metadata = LinCompoundTag.builder();
metadata.put("Date", new LongTag(System.currentTimeMillis())); metadata.putLong("Date", System.currentTimeMillis());
Map<String, Tag> worldEditSection = new HashMap<>(); LinCompoundTag.Builder worldEditSection = LinCompoundTag.builder();
worldEditSection.put("Version", new StringTag(WorldEdit.getVersion())); worldEditSection.putString("Version", WorldEdit.getVersion());
worldEditSection.put("EditingPlatform", new StringTag(WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).getId())); worldEditSection.putString("EditingPlatform",
worldEditSection.put("Origin", new IntArrayTag(new int[] { WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).id()
origin.getBlockX(), origin.getBlockY(), origin.getBlockZ() );
})); worldEditSection.putIntArray("Origin", new int[]{origin.x(), origin.y(), origin.z()});
Map<String, Tag> platformsSection = new HashMap<>(); LinCompoundTag.Builder platformsSection = LinCompoundTag.builder();
for (Platform platform : WorldEdit.getInstance().getPlatformManager().getPlatforms()) { for (Platform platform : WorldEdit.getInstance().getPlatformManager().getPlatforms()) {
platformsSection.put(platform.getId(), new CompoundTag(ImmutableMap.of( platformsSection.put(platform.id(), LinCompoundTag
"Name", new StringTag(platform.getPlatformName()), .builder()
"Version", new StringTag(platform.getPlatformVersion()) .putString("Name", platform.getPlatformName())
))); .putString("Version", platform.getPlatformVersion())
.build());
} }
worldEditSection.put("Platforms", new CompoundTag(platformsSection)); worldEditSection.put("Platforms", platformsSection.build());
metadata.put("WorldEdit", new CompoundTag(worldEditSection)); metadata.put("WorldEdit", worldEditSection.build());
schematic.put("Metadata", new CompoundTag(metadata)); schematic.put("Metadata", metadata.build());
schematic.put("Width", new ShortTag((short) width)); schematic.putShort("Width", (short) width);
schematic.put("Height", new ShortTag((short) height)); schematic.putShort("Height", (short) height);
schematic.put("Length", new ShortTag((short) length)); schematic.putShort("Length", (short) length);
schematic.put("Offset", new IntArrayTag(new int[] { schematic.putIntArray("Offset", new int[]{offset.x(), offset.y(), offset.z(),});
offset.getBlockX(),
offset.getBlockY(),
offset.getBlockZ(),
}));
schematic.put("Blocks", encodeBlocks(clipboard)); schematic.put("Blocks", encodeBlocks(clipboard));
@ -154,22 +134,23 @@ public class SpongeSchematicV3Writer implements ClipboardWriter {
} }
if (!clipboard.getEntities().isEmpty()) { if (!clipboard.getEntities().isEmpty()) {
ListTag value = WriterUtil.encodeEntities(clipboard, true); LinListTag<LinCompoundTag> value = WriterUtil.encodeEntities(clipboard, true);
if (value != null) { if (value != null) {
schematic.put("Entities", value); schematic.put("Entities", value);
} }
} }
return schematic; return schematic.build();
} }
private static final class PaletteMap { private static final class PaletteMap {
private final Map<String, Integer> contents = new LinkedHashMap<>();
private final Object2IntMap<String> contents = new Object2IntLinkedOpenHashMap<>();
private int nextId = 0; private int nextId = 0;
public int getId(String key) { public int getId(String key) {
Integer result = contents.get(key); int result = contents.getOrDefault(key, -1);
if (result != null) { if (result != -1) {
return result; return result;
} }
int newValue = nextId; int newValue = nextId;
@ -178,46 +159,43 @@ public class SpongeSchematicV3Writer implements ClipboardWriter {
return newValue; return newValue;
} }
public CompoundTag toNbt() { public LinCompoundTag toNbt() {
return new CompoundTag(ImmutableMap.copyOf(Maps.transformValues( LinCompoundTag.Builder result = LinCompoundTag.builder();
contents, IntTag::new Object2IntMaps.fastForEach(contents, e -> result.putInt(e.getKey(), e.getIntValue()));
))); return result.build();
} }
} }
private CompoundTag encodeBlocks(Clipboard clipboard) { private LinCompoundTag encodeBlocks(Clipboard clipboard) {
List<CompoundTag> blockEntities = new ArrayList<>(); LinListTag.Builder<LinCompoundTag> blockEntities = LinListTag.builder(LinTagType.compoundTag());
CompoundTag result = encodePalettedData(clipboard, point -> { LinCompoundTag.Builder result = encodePalettedData(clipboard, point -> {
BaseBlock block = clipboard.getFullBlock(point); BaseBlock block = clipboard.getFullBlock(point);
// Also compute block entity side-effect here // Also compute block entity side-effect here
if (block.getNbtData() != null) { LinCompoundTag nbt = block.getNbt();
CompoundTagBuilder builder = CompoundTagBuilder.create(); if (nbt != null) {
LinCompoundTag.Builder builder = LinCompoundTag.builder();
builder.putString("Id", block.getNbtId()); builder.putString("Id", block.getNbtId());
BlockVector3 adjustedPos = point.subtract(clipboard.getMinimumPoint()); BlockVector3 adjustedPos = point.subtract(clipboard.getMinimumPoint());
builder.putIntArray("Pos", new int[] { builder.putIntArray("Pos", new int[]{adjustedPos.x(), adjustedPos.y(), adjustedPos.z()});
adjustedPos.getBlockX(), builder.put("Data", nbt);
adjustedPos.getBlockY(),
adjustedPos.getBlockZ()
});
builder.put("Data", block.getNbtData());
blockEntities.add(builder.build()); blockEntities.add(builder.build());
} }
return block.toImmutableState().getAsString(); return block.toImmutableState().getAsString();
}); });
return result.createBuilder() return result.put("BlockEntities", blockEntities.build()).build();
.put("BlockEntities", new ListTag(CompoundTag.class, blockEntities))
.build();
} }
private CompoundTag encodeBiomes(Clipboard clipboard) { private LinCompoundTag encodeBiomes(Clipboard clipboard) {
return encodePalettedData(clipboard, point -> clipboard.getBiome(point).getId()); return encodePalettedData(clipboard, point -> clipboard.getBiome(point).id()).build();
} }
private CompoundTag encodePalettedData(Clipboard clipboard, private LinCompoundTag.Builder encodePalettedData(
Function<BlockVector3, String> keyFunction) { Clipboard clipboard, Function<BlockVector3, String> keyFunction
) {
BlockVector3 min = clipboard.getMinimumPoint(); BlockVector3 min = clipboard.getMinimumPoint();
int width = clipboard.getRegion().getWidth(); int width = clipboard.getRegion().getWidth();
int height = clipboard.getRegion().getHeight(); int height = clipboard.getRegion().getHeight();
@ -244,14 +222,12 @@ public class SpongeSchematicV3Writer implements ClipboardWriter {
} }
} }
return new CompoundTag(ImmutableMap.of( return LinCompoundTag.builder().put("Palette", paletteMap.toNbt()).putByteArray("Data", buffer.toByteArray());
"Palette", paletteMap.toNbt(),
"Data", new ByteArrayTag(buffer.toByteArray())
));
} }
@Override @Override
public void close() throws IOException { public void close() throws IOException {
outputStream.close(); outputStream.close();
} }
} }

Datei anzeigen

@ -19,69 +19,73 @@
package com.sk89q.worldedit.extent.clipboard.io.sponge; package com.sk89q.worldedit.extent.clipboard.io.sponge;
import com.google.common.collect.ImmutableList;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.CompoundTagBuilder;
import com.sk89q.jnbt.DoubleTag;
import com.sk89q.jnbt.FloatTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import org.enginehub.linbus.tree.LinCompoundTag;
import java.util.List; import org.enginehub.linbus.tree.LinDoubleTag;
import java.util.Objects; import org.enginehub.linbus.tree.LinFloatTag;
import java.util.stream.Collectors; import org.enginehub.linbus.tree.LinListTag;
import org.enginehub.linbus.tree.LinTagType;
class WriterUtil { class WriterUtil {
static ListTag encodeEntities(Clipboard clipboard, boolean positionIsRelative) {
List<CompoundTag> entities = clipboard.getEntities().stream().map(e -> {
BaseEntity state = e.getState();
if (state == null) {
return null;
}
CompoundTagBuilder fullTagBuilder = CompoundTagBuilder.create();
CompoundTagBuilder dataTagBuilder = CompoundTagBuilder.create();
CompoundTag rawData = state.getNbtData();
if (rawData != null) {
dataTagBuilder.putAll(rawData.getValue());
dataTagBuilder.remove("id");
}
final Location location = e.getLocation();
Vector3 pos = location.toVector();
dataTagBuilder.put("Rotation", encodeRotation(location));
if (positionIsRelative) {
pos = pos.subtract(clipboard.getMinimumPoint().toVector3());
fullTagBuilder.put("Data", dataTagBuilder.build()); static LinListTag<LinCompoundTag> encodeEntities(Clipboard clipboard, boolean positionIsRelative) {
} else { LinListTag.Builder<LinCompoundTag> entities = LinListTag.builder(LinTagType.compoundTag());
fullTagBuilder.putAll(dataTagBuilder.build().getValue()); for (Entity entity : clipboard.getEntities()) {
LinCompoundTag encoded = encodeEntity(clipboard, positionIsRelative, entity);
if (encoded != null) {
entities.add(encoded);
} }
fullTagBuilder.putString("Id", state.getType().getId()); }
fullTagBuilder.put("Pos", encodeVector(pos)); var result = entities.build();
if (result.value().isEmpty()) {
return fullTagBuilder.build();
}).filter(Objects::nonNull).collect(Collectors.toList());
if (entities.isEmpty()) {
return null; return null;
} }
return new ListTag(CompoundTag.class, entities); return result;
} }
static Tag encodeVector(Vector3 vector) { private static LinCompoundTag encodeEntity(Clipboard clipboard, boolean positionIsRelative, Entity e) {
return new ListTag(DoubleTag.class, ImmutableList.of( BaseEntity state = e.getState();
new DoubleTag(vector.getX()), if (state == null) {
new DoubleTag(vector.getY()), return null;
new DoubleTag(vector.getZ()) }
)); LinCompoundTag.Builder fullTagBuilder = LinCompoundTag.builder();
LinCompoundTag.Builder dataTagBuilder = LinCompoundTag.builder();
LinCompoundTag rawData = state.getNbt();
if (rawData != null) {
dataTagBuilder.putAll(rawData.value());
dataTagBuilder.remove("id");
}
final Location location = e.getLocation();
Vector3 pos = location.toVector();
dataTagBuilder.put("Rotation", encodeRotation(location));
if (positionIsRelative) {
pos = pos.subtract(clipboard.getMinimumPoint().toVector3());
fullTagBuilder.put("Data", dataTagBuilder.build());
} else {
fullTagBuilder.putAll(dataTagBuilder.build().value());
}
fullTagBuilder.putString("Id", state.getType().id());
fullTagBuilder.put("Pos", encodeVector(pos));
return fullTagBuilder.build();
} }
static Tag encodeRotation(Location location) { static LinListTag<LinDoubleTag> encodeVector(Vector3 vector) {
return new ListTag(FloatTag.class, ImmutableList.of( return LinListTag.builder(LinTagType.doubleTag()).add(LinDoubleTag.of(vector.x())).add(LinDoubleTag.of(vector.y())).add(
new FloatTag(location.getYaw()), LinDoubleTag.of(vector.z())).build();
new FloatTag(location.getPitch())
));
} }
static LinListTag<LinFloatTag> encodeRotation(Location location) {
return LinListTag
.builder(LinTagType.floatTag())
.add(LinFloatTag.of(location.getYaw()))
.add(LinFloatTag.of(location.getPitch()))
.build();
}
} }