Search in sources :

Example 81 with DataView

use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.

the class UserIO method save.

public static void save(Path dataFolder, AbstractUser player) throws IOException {
    final String fileName = player.getUniqueId().toString() + ".dat";
    final DataContainer dataContainer = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
    final ObjectStore<AbstractUser> objectStore = ObjectStoreRegistry.get().get(AbstractUser.class).get();
    objectStore.serialize(player, dataContainer);
    final Optional<DataView> optSpongeData = dataContainer.getView(DataQueries.EXTENDED_SPONGE_DATA);
    dataContainer.remove(DataQueries.EXTENDED_SPONGE_DATA);
    Path dataFolder0 = dataFolder.resolve(PLAYER_DATA_FOLDER);
    if (!Files.exists(dataFolder0)) {
        Files.createDirectories(dataFolder0);
    }
    Path dataFile = dataFolder0.resolve(fileName);
    NbtStreamUtils.write(dataContainer, Files.newOutputStream(dataFile), true);
    dataFolder0 = dataFolder.resolve(SPONGE_PLAYER_DATA_FOLDER);
    if (!Files.exists(dataFolder0)) {
        Files.createDirectories(dataFolder0);
    }
    dataFile = dataFolder0.resolve(fileName);
    if (optSpongeData.isPresent()) {
        final DataView spongeData = optSpongeData.get();
        spongeData.set(NAME, player.getName());
        NbtStreamUtils.write(spongeData, Files.newOutputStream(dataFile), true);
    } else {
        Files.deleteIfExists(dataFile);
    }
    final Path statisticsFile = dataFolder.resolve(STATISTICS_FOLDER).resolve(player.getUniqueId().toString() + ".json");
    player.getStatisticMap().save(statisticsFile);
}
Also used : Path(java.nio.file.Path) DataView(org.spongepowered.api.data.DataView) DataContainer(org.spongepowered.api.data.DataContainer) AbstractUser(org.lanternpowered.server.entity.living.player.AbstractUser)

Example 82 with DataView

use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.

the class DataHelper method serializeRawRegisteredKeyData.

public static void serializeRawRegisteredKeyData(DataView dataView, IValueContainer valueContainer, Set<Key> ignoredKeys) {
    DataView view = null;
    final ValueCollection valueCollection = valueContainer.getValueCollection();
    final LanternDataManager dataManager = Lantern.getGame().getDataManager();
    final DataTypeSerializerContext context = dataManager.getTypeSerializerContext();
    for (KeyRegistration<?, ?> registration : valueCollection.getAll()) {
        final Key<?> key = registration.getKey();
        if (!(registration instanceof Element) || ignoredKeys.contains(key) || key == LanternKeys.FAILED_DATA_MANIPULATORS || key == LanternKeys.FAILED_DATA_VALUES) {
            continue;
        }
        final Element element = (Element) registration;
        final TypeToken<?> typeToken = key.getElementToken();
        final DataTypeSerializer typeSerializer = dataManager.getTypeSerializer(typeToken).orElseThrow(() -> new IllegalStateException("Wasn't able to find a type serializer for the element type: " + typeToken.toString()));
        final Object object = element.get();
        if (object == null) {
            continue;
        }
        final Object value = typeSerializer.serialize(typeToken, context, object);
        if (view == null) {
            view = dataView.createView(DataQueries.DATA_VALUES);
        }
        view.set(key.getQuery(), value);
    }
    Element<DataView> holder = valueCollection.getElement(LanternKeys.FAILED_DATA_VALUES).orElse(null);
    if (holder != null) {
        if (view == null) {
            view = dataView.createView(DataQueries.DATA_VALUES);
        }
        for (Map.Entry<DataQuery, Object> entry : holder.get().getValues(false).entrySet()) {
            if (!view.contains(entry.getKey())) {
                view.set(entry.getKey(), entry.getValue());
            }
        }
    }
}
Also used : DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) Element(org.lanternpowered.server.data.element.Element) DataView(org.spongepowered.api.data.DataView) DataQuery(org.spongepowered.api.data.DataQuery) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) Map(java.util.Map)

Example 83 with DataView

use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.

the class DataHelper method deserializeRawRegisteredKeyData.

public static void deserializeRawRegisteredKeyData(DataView dataView, IValueContainer valueContainer) throws InvalidDataException {
    dataView = dataView.getView(DataQueries.DATA_VALUES).orElse(null);
    if (dataView == null) {
        return;
    }
    final ValueCollection valueCollection = valueContainer.getValueCollection();
    final LanternDataManager dataManager = Lantern.getGame().getDataManager();
    final DataTypeSerializerContext context = dataManager.getTypeSerializerContext();
    for (KeyRegistration<?, ?> registration : valueCollection.getAll()) {
        final Key<?> key = registration.getKey();
        if (!(registration instanceof Element) || key == LanternKeys.FAILED_DATA_MANIPULATORS || key == LanternKeys.FAILED_DATA_VALUES) {
            continue;
        }
        final Optional<Object> data = dataView.get(key.getQuery());
        if (!data.isPresent()) {
            continue;
        }
        dataView.remove(key.getQuery());
        final TypeToken<?> typeToken = key.getElementToken();
        final DataTypeSerializer typeSerializer = dataManager.getTypeSerializer(typeToken).orElseThrow(() -> new IllegalStateException("Wasn't able to find a type serializer for the element type: " + typeToken.toString()));
        ((Element) registration).set(typeSerializer.deserialize(typeToken, context, data.get()));
    }
    if (valueContainer instanceof CompositeValueStore) {
        final CompositeValueStore store = (CompositeValueStore) valueContainer;
        for (Map.Entry<DataQuery, Object> entry : dataView.getValues(false).entrySet()) {
            final Key<?> key = KeyRegistryModule.get().getByQuery(entry.getKey()).orElse(null);
            if (key == null) {
                continue;
            }
            final TypeToken<?> typeToken = key.getElementToken();
            final DataTypeSerializer typeSerializer = dataManager.getTypeSerializer(typeToken).orElseThrow(() -> new IllegalStateException("Wasn't able to find a type serializer for the element type: " + typeToken.toString()));
            store.offer(key, typeSerializer.deserialize(typeToken, context, entry.getValue()));
            dataView.remove(entry.getKey());
        }
    }
    if (!dataView.isEmpty()) {
        // Should be safe to cast, at least if nobody touches this key
        Element<DataView> holder = valueCollection.getElement(LanternKeys.FAILED_DATA_VALUES).orElse(null);
        if (holder == null) {
            holder = valueCollection.register(LanternKeys.FAILED_DATA_VALUES, null);
        }
        holder.set(dataView);
    }
}
Also used : DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) Element(org.lanternpowered.server.data.element.Element) DataView(org.spongepowered.api.data.DataView) DataQuery(org.spongepowered.api.data.DataQuery) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) CompositeValueStore(org.spongepowered.api.data.value.mutable.CompositeValueStore) Map(java.util.Map)

Example 84 with DataView

use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.

the class DataHelper method deserializeRawContainerData.

public static void deserializeRawContainerData(DataView dataView, IValueContainer valueContainer, DataQuery query) throws InvalidDataException {
    final List<DataView> dataViews = dataView.getViewList(query).orElse(null);
    if (dataViews == null) {
        return;
    }
    if (!(valueContainer instanceof AdditionalContainerHolder)) {
        getLogger().warn("{} is not a AdditionalContainerHolder, but data manipulators were found.", valueContainer);
        return;
    }
    final ValueCollection valueCollection = valueContainer.getValueCollection();
    final AdditionalContainerCollection<ValueContainer<?>> containers = ((AdditionalContainerHolder) valueContainer).getAdditionalContainers();
    final List<DataView> failedData = new ArrayList<>();
    final LanternDataManager dataManager = Lantern.getGame().getDataManager();
    for (DataView view : dataViews) {
        Optional<DataRegistration> optRegistration;
        String id;
        if (view.contains(DataQueries.MANIPULATOR_ID)) {
            id = view.getString(DataQueries.MANIPULATOR_ID).get();
            optRegistration = DataManipulatorRegistryModule.get().getById(id);
        } else if (view.contains(DATA_CLASS)) {
            id = view.getString(DATA_CLASS).get();
            optRegistration = dataManager.getLegacyRegistration(id);
        } else {
            getLogger().warn("Manipulator with missing id.");
            continue;
        }
        final Optional<DataView> manipulatorView = view.getView(DataQueries.MANIPULATOR_DATA);
        if (manipulatorView.isPresent()) {
            getLogger().warn("Missing manipulator data for id: {}", id);
        }
        if (optRegistration.isPresent()) {
            try {
                final Optional<DataManipulator> optManipulator = optRegistration.get().getDataManipulatorBuilder().build(manipulatorView.get());
                if (optManipulator.isPresent()) {
                    containers.offer(optManipulator.get());
                }
            } catch (InvalidDataException e) {
                getLogger().error("Could not deserialize " + id + "! Don't worry though, we'll try to deserialize the rest of the data.", e);
            }
        } else {
            getLogger().warn("Missing DataRegistration for ID: " + id + ". Don't worry, the data will be kept safe.");
            failedData.add(view);
        }
    }
    if (!failedData.isEmpty()) {
        // Should be safe to cast, at least if nobody touches this key
        Element<List<DataView>> holder = valueCollection.getElement(LanternKeys.FAILED_DATA_MANIPULATORS).orElse(null);
        if (holder == null) {
            holder = valueCollection.register(LanternKeys.FAILED_DATA_MANIPULATORS, null);
        }
        holder.set(failedData);
    }
}
Also used : IDataManipulator(org.lanternpowered.server.data.manipulator.mutable.IDataManipulator) DataManipulator(org.spongepowered.api.data.manipulator.DataManipulator) ArrayList(java.util.ArrayList) DataView(org.spongepowered.api.data.DataView) DataRegistration(org.spongepowered.api.data.DataRegistration) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) ValueContainer(org.spongepowered.api.data.value.ValueContainer)

Example 85 with DataView

use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.

the class CodecPlayOutChunkData method encode.

@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutChunkData message) throws CodecException {
    final MessagePlayOutChunkData.Section[] sections = message.getSections();
    final byte[] biomes = message.getBiomes();
    final int x = message.getX();
    final int z = message.getZ();
    final ByteBuffer buf = context.byteBufAlloc().buffer();
    buf.writeInteger(message.getX());
    buf.writeInteger(message.getZ());
    buf.writeBoolean(biomes != null);
    int sectionBitmask = 0;
    final ByteBuffer dataBuf = context.byteBufAlloc().buffer();
    ByteBuffer tileEntitiesBuf = null;
    int tileEntitiesCount = 0;
    for (int i = 0; i < sections.length; i++) {
        if (sections[i] == null) {
            continue;
        }
        sectionBitmask |= 1 << i;
        final MessagePlayOutChunkData.Section section = sections[i];
        final VariableValueArray types = section.getTypes();
        dataBuf.writeByte((byte) types.getBitsPerValue());
        final int[] palette = section.getPalette();
        if (palette != null) {
            dataBuf.writeVarInt(palette.length);
            for (int value : palette) {
                dataBuf.writeVarInt(value);
            }
        } else {
            // Using global palette
            dataBuf.writeVarInt(0);
        }
        final long[] backing = types.getBacking();
        dataBuf.writeVarInt(backing.length);
        final byte[] blockLight = section.getBlockLight();
        final byte[] skyLight = section.getSkyLight();
        dataBuf.ensureWritable(backing.length * 8 + blockLight.length + (skyLight != null ? skyLight.length : 0));
        for (long value : backing) {
            dataBuf.writeLong(value);
        }
        dataBuf.writeBytes(blockLight);
        if (skyLight != null) {
            dataBuf.writeBytes(skyLight);
        }
        final Short2ObjectMap<DataView> tileEntities = section.getTileEntities();
        if (!tileEntities.isEmpty() && tileEntitiesBuf == null) {
            tileEntitiesBuf = context.byteBufAlloc().buffer();
        }
        for (Short2ObjectMap.Entry<DataView> tileEntityEntry : tileEntities.short2ObjectEntrySet()) {
            tileEntitiesCount++;
            final int index = tileEntityEntry.getShortKey() & 0xffff;
            final DataView dataView = tileEntityEntry.getValue();
            dataView.set(X, x * 16 + (index & 0xf));
            dataView.set(Y, i << 4 | index >> 8);
            dataView.set(Z, z * 16 + ((index >> 4) & 0xf));
            // noinspection ConstantConditions
            tileEntitiesBuf.writeDataView(dataView);
        }
    }
    if (biomes != null) {
        dataBuf.writeBytes(biomes);
    }
    buf.writeVarInt(sectionBitmask);
    buf.writeVarInt(dataBuf.writerIndex());
    try {
        buf.writeBytes(dataBuf);
    } finally {
        dataBuf.release();
    }
    buf.writeVarInt(tileEntitiesCount);
    if (tileEntitiesBuf != null) {
        try {
            buf.writeBytes(tileEntitiesBuf);
        } finally {
            tileEntitiesBuf.release();
        }
    }
    return buf;
}
Also used : VariableValueArray(org.lanternpowered.server.util.collect.array.VariableValueArray) MessagePlayOutChunkData(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutChunkData) ByteBuffer(org.lanternpowered.server.network.buffer.ByteBuffer) Short2ObjectMap(it.unimi.dsi.fastutil.shorts.Short2ObjectMap) DataView(org.spongepowered.api.data.DataView)

Aggregations

DataView (org.spongepowered.api.data.DataView)100 DataContainer (org.spongepowered.api.data.DataContainer)30 DataQuery (org.spongepowered.api.data.DataQuery)24 ArrayList (java.util.ArrayList)21 Map (java.util.Map)17 List (java.util.List)13 Vector3i (com.flowpowered.math.vector.Vector3i)11 LanternItemStack (org.lanternpowered.server.inventory.LanternItemStack)11 ItemStack (org.spongepowered.api.item.inventory.ItemStack)11 UUID (java.util.UUID)10 Nullable (javax.annotation.Nullable)10 NBTTagCompound (net.minecraft.nbt.NBTTagCompound)10 ImmutableList (com.google.common.collect.ImmutableList)8 IOException (java.io.IOException)8 Test (org.junit.Test)8 CatalogType (org.spongepowered.api.CatalogType)8 Path (java.nio.file.Path)7 DataTypeSerializer (org.lanternpowered.server.data.persistence.DataTypeSerializer)7 InvalidDataException (org.spongepowered.api.data.persistence.InvalidDataException)7 ImmutableMap (com.google.common.collect.ImmutableMap)6