Unicopia/src/main/java/com/minelittlepony/unicopia/util/NbtSerialisable.java

100 lines
3 KiB
Java
Raw Normal View History

package com.minelittlepony.unicopia.util;
2020-01-16 12:35:46 +01:00
2022-09-04 14:16:47 +02:00
import java.util.*;
import java.util.function.Function;
import java.util.stream.Stream;
import com.mojang.serialization.Codec;
2022-09-04 14:16:47 +02:00
import net.minecraft.nbt.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
2020-01-16 12:35:46 +01:00
2020-04-15 18:12:00 +02:00
public interface NbtSerialisable {
Serializer<BlockPos> BLOCK_POS = Serializer.of(NbtHelper::toBlockPos, NbtHelper::fromBlockPos);
2020-01-16 12:35:46 +01:00
/**
* Called to save this to nbt to persist state on file or to transmit over the network
*
* @param compound Compound tag to write to.
*/
void toNBT(NbtCompound compound);
2020-01-16 12:35:46 +01:00
/**
* Called to load this state from nbt
*
* @param compound Compound tag to read from.
*/
void fromNBT(NbtCompound compound);
2020-01-16 12:35:46 +01:00
2021-08-04 15:38:03 +02:00
default NbtCompound toNBT() {
NbtCompound compound = new NbtCompound();
2020-01-16 12:35:46 +01:00
toNBT(compound);
return compound;
}
2021-08-04 15:38:03 +02:00
static NbtList writeVector(Vec3d vector) {
NbtList list = new NbtList();
list.add(NbtDouble.of(vector.getX()));
list.add(NbtDouble.of(vector.getY()));
list.add(NbtDouble.of(vector.getZ()));
return list;
2020-01-16 12:35:46 +01:00
}
2021-08-04 15:38:03 +02:00
static Vec3d readVector(NbtList list) {
return new Vec3d(list.getDouble(0), list.getDouble(1), list.getDouble(2));
2020-01-16 12:35:46 +01:00
}
static <T> T decode(Codec<T> codec, NbtElement nbt) {
return codec.decode(NbtOps.INSTANCE, nbt).result().get().getFirst();
}
static <T> NbtElement encode(Codec<T> codec, T value) {
return codec.encodeStart(NbtOps.INSTANCE, value).result().get();
}
2022-09-04 14:16:47 +02:00
interface Serializer<T> {
T read(NbtCompound compound);
NbtCompound write(T t);
default Optional<T> readOptional(String name, NbtCompound compound) {
return compound.contains(name, NbtElement.COMPOUND_TYPE)
? Optional.ofNullable(read(compound.getCompound(name)))
: Optional.empty();
}
default void writeOptional(String name, NbtCompound compound, Optional<T> t) {
t.map(this::write).ifPresent(tag -> compound.put(name, tag));
}
2022-09-04 14:16:47 +02:00
default T read(NbtElement element) {
return read((NbtCompound)element);
}
default NbtList writeAll(Collection<T> ts) {
NbtList list = new NbtList();
ts.stream().map(this::write).forEach(list::add);
return list;
}
default Stream<T> readAll(NbtList list) {
return list.stream().map(this::read).filter(Objects::nonNull);
}
static <T> Serializer<T> of(Function<NbtCompound, T> read, Function<T, NbtCompound> write) {
return new Serializer<>() {
@Override
public T read(NbtCompound compound) {
return read.apply(compound);
}
@Override
public NbtCompound write(T t) {
return write.apply(t);
}
};
}
}
2020-01-16 12:35:46 +01:00
}