AuLib/src/main/java/com/io/yutian/aulib/nbt/NBTItem.java
2024-07-15 21:02:38 +08:00

81 lines
2.2 KiB
Java

package com.io.yutian.aulib.nbt;
import net.minecraft.nbt.NBTTagCompound;
import org.bukkit.craftbukkit.v1_18_R2.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import java.util.function.Consumer;
public class NBTItem {
private ItemStack originalItemStack;
private net.minecraft.world.item.ItemStack nmsItemStack;
protected ItemStack resultItemStack;
public NBTItem(ItemStack itemStack) {
this.originalItemStack = itemStack;
this.nmsItemStack = CraftItemStack.asNMSCopy(itemStack);
}
@NotNull
public NBTCompound getTag() {
NBTTagCompound tag = nmsItemStack.u();
if (tag == null) {
tag = new NBTTagCompound();
}
return (NBTCompound) INBT.as(tag);
}
public boolean has(String key) {
NBTCompound nbtCompound = getTag();
return nbtCompound.hasKey(key);
}
public boolean has(String key, int type) {
NBTCompound nbtCompound = getTag();
return nbtCompound.hasKey(key, type);
}
@Nullable
public INBT get(String key) {
NBTCompound nbtCompound = getTag();
return nbtCompound.hasKey(key) ? nbtCompound.get(key) : null;
}
public void editTag(Consumer<NBTCompound> consumer) {
NBTCompound tag = getTag();
consumer.accept(tag);
setTag(tag);
}
public void setTag(NBTCompound nbtCompound) {
nmsItemStack.c((NBTTagCompound) INBT.asNMS(nbtCompound));
resultItemStack = CraftItemStack.asBukkitCopy(nmsItemStack);
}
public ItemStack getOriginalItemStack() {
return originalItemStack;
}
public ItemStack getItemStack() {
return resultItemStack;
}
public net.minecraft.world.item.ItemStack getNMSItemStack() {
return nmsItemStack;
}
public static NBTItem build(ItemStack itemStack) {
return new NBTItem(itemStack);
}
public static NBTItem build(NBTCompound nbtCompound) {
net.minecraft.world.item.ItemStack nmsItemStack = net.minecraft.world.item.ItemStack.a((NBTTagCompound) INBT.asNMS(nbtCompound));
return new NBTItem(CraftItemStack.asBukkitCopy(nmsItemStack));
}
}