net.minecraft.nbt.CompoundNBT Java Examples

The following examples show how to use net.minecraft.nbt.CompoundNBT. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MiningProperties.java    From MiningGadgets with MIT License 6 votes vote down vote up
public static CompoundNBT serializeItemStackList(List<ItemStack> stacks) {
    ListNBT nbtTagList = new ListNBT();
    for (int i = 0; i < stacks.size(); i++)
    {
        if (stacks.get(i).isEmpty())
            continue;

        CompoundNBT itemTag = new CompoundNBT();
        stacks.get(i).write(itemTag);
        nbtTagList.add(itemTag);
    }

    CompoundNBT nbt = new CompoundNBT();
    nbt.put("Items", nbtTagList);
    return nbt;
}
 
Example #2
Source File: RenderBlockTileEntity.java    From MiningGadgets with MIT License 6 votes vote down vote up
@Override
public CompoundNBT write(CompoundNBT tag) {
    if (renderBlock!= null)
        tag.put("renderBlock", NBTUtil.writeBlockState(renderBlock));
    tag.putInt("originalDurability", originalDurability);
    tag.putInt("priorDurability", priorDurability);
    tag.putInt("durability", durability);
    tag.putInt("ticksSinceMine", ticksSinceMine);
    if (!playerUUID.equals(null))
        tag.putUniqueId("playerUUID", playerUUID);
    tag.put("upgrades", UpgradeTools.setUpgradesNBT(gadgetUpgrades).getList("upgrades", Constants.NBT.TAG_COMPOUND));
    tag.putByte("breakType", (byte) breakType.ordinal());
    tag.put("gadgetFilters", MiningProperties.serializeItemStackList(getGadgetFilters()));
    tag.putBoolean("gadgetIsWhitelist", isGadgetIsWhitelist());
    tag.putBoolean("blockAllowed", blockAllowed);
    return super.write(tag);
}
 
Example #3
Source File: MCDataOutput.java    From CodeChickenLib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Writes an {@link ItemStack} to the stream.
 * The <code>limitedTag</code> parameter, can be used to force the use of
 * the stack {@link ItemStack#getShareTag()} instead of its {@link ItemStack#getTag()}.
 * Under normal circumstances in Server -> Client sync, not all NBT tags are required,
 * to be sent to the client. For Example, the inventory of a pouch / bag(Containers sync it).
 * However, in Client -> Server sync, the entire tag may be required, modders can choose,
 * if they want a stacks full tag or not. The default is to use {@link ItemStack#getShareTag()}.
 * <p>
 * It should also be noted that this implementation writes the {@link ItemStack#getCount()}
 * as a varInt opposed to a byte, as that is favourable in some cases.
 *
 * @param stack      The {@link ItemStack}.
 * @param limitedTag Weather to use the stacks {@link ItemStack#getShareTag()} instead.
 * @return The same stream.
 */
default MCDataOutput writeItemStack(ItemStack stack, boolean limitedTag) {
    if (stack.isEmpty()) {
        writeBoolean(false);
    } else {
        writeBoolean(true);
        Item item = stack.getItem();
        writeRegistryIdUnsafe(ForgeRegistries.ITEMS, item);
        writeVarInt(stack.getCount());
        CompoundNBT nbt = null;
        if (item.isDamageable() || item.shouldSyncTag()) {
            nbt = limitedTag ? stack.getShareTag() : stack.getTag();
        }
        writeCompoundNBT(nbt);
    }
    return this;
}
 
Example #4
Source File: UpgradeTools.java    From MiningGadgets with MIT License 6 votes vote down vote up
public static void updateUpgrade(ItemStack tool, Upgrade upgrade) {
    CompoundNBT tagCompound = tool.getOrCreateTag();
    ListNBT list = tagCompound.getList(KEY_UPGRADES, Constants.NBT.TAG_COMPOUND);

    list.forEach( e -> {
        CompoundNBT compound = (CompoundNBT) e;
        String name = compound.getString(KEY_UPGRADE);
        boolean enabled = compound.getBoolean(KEY_ENABLED);

        if( (name.contains(Upgrade.FORTUNE_1.getBaseName()) && enabled && upgrade.lazyIs(Upgrade.SILK) )
                        || (name.equals(Upgrade.SILK.getBaseName()) && enabled && upgrade.lazyIs(Upgrade.FORTUNE_1) ))
            compound.putBoolean(KEY_ENABLED, false);

        if( name.equals(upgrade.getName()) )
            compound.putBoolean(KEY_ENABLED, !compound.getBoolean(KEY_ENABLED));
    });
}
 
Example #5
Source File: UpgradeTools.java    From MiningGadgets with MIT License 6 votes vote down vote up
public static List<Upgrade> getUpgradesFromTag(CompoundNBT tagCompound) {
    ListNBT upgrades = tagCompound.getList(KEY_UPGRADES, Constants.NBT.TAG_COMPOUND);

    List<Upgrade> functionalUpgrades = new ArrayList<>();
    if (upgrades.isEmpty())
        return functionalUpgrades;

    for (int i = 0; i < upgrades.size(); i++) {
        CompoundNBT tag = upgrades.getCompound(i);

        // Skip unknowns
        Upgrade type = getUpgradeByName(tag.getString(KEY_UPGRADE));
        if( type == null )
            continue;

        type.setEnabled(!tag.contains(KEY_ENABLED) || tag.getBoolean(KEY_ENABLED));
        functionalUpgrades.add(type);
    }

    return functionalUpgrades;
}
 
Example #6
Source File: InventoryUtils.java    From CodeChickenLib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * NBT item saving function with support for stack sizes > 32K
 */
public static ListNBT writeItemStacksToTag(ItemStack[] items, int maxQuantity) {
    ListNBT tagList = new ListNBT();
    for (int i = 0; i < items.length; i++) {
        CompoundNBT tag = new CompoundNBT();
        tag.putShort("Slot", (short) i);
        items[i].write(tag);

        if (maxQuantity > Short.MAX_VALUE) {
            tag.putInt("Quantity", items[i].getCount());
        } else if (maxQuantity > Byte.MAX_VALUE) {
            tag.putShort("Quantity", (short) items[i].getCount());
        }

        tagList.add(tag);
    }
    return tagList;
}
 
Example #7
Source File: NBTStructureLoader.java    From BoundingBoxOutlineReloaded with MIT License 6 votes vote down vote up
void loadStructures(int chunkX, int chunkZ) {
    if (saveHandler == null) return;

    if (!loadedChunks.add(String.format("%s,%s", chunkX, chunkZ))) return;

    CompoundNBT structureStarts = loadStructureStarts(chunkX, chunkZ);
    if (structureStarts == null || structureStarts.size() == 0) return;

    Map<String, StructureStart> structureStartMap = new HashMap<>();
    for (String key : structureStarts.keySet()) {
        CompoundNBT compound = structureStarts.getCompound(key);
        if (compound.contains("BB")) {
            structureStartMap.put(key, new SimpleStructureStart(compound));
        }
    }

    EventBus.publish(new StructuresLoaded(structureStartMap, dimensionId));
}
 
Example #8
Source File: Frequency.java    From EnderStorage with MIT License 5 votes vote down vote up
public static Frequency readFromStack(ItemStack stack) {
    if (stack.hasTag()) {
        CompoundNBT stackTag = stack.getTag();
        if (stackTag.contains("Frequency")) {
            return new Frequency(stackTag.getCompound("Frequency"));
        }
    }
    return new Frequency();
}
 
Example #9
Source File: MCDataInput.java    From CodeChickenLib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Reads a {@link CompoundNBT} from the stream.
 *
 * @return The {@link CompoundNBT}.
 */
@Nullable
default CompoundNBT readCompoundNBT() {
    if (!readBoolean()) {
        return null;
    } else {
        try {
            return CompressedStreamTools.read(toDataInput(), new NBTSizeTracker(2097152L));
        } catch (IOException e) {
            throw new EncoderException("Failed to read CompoundNBT from stream.", e);
        }
    }
}
 
Example #10
Source File: Frequency.java    From EnderStorage with MIT License 5 votes vote down vote up
protected CompoundNBT write_internal(CompoundNBT tagCompound) {
    tagCompound.putInt("left", left.getWoolMeta());
    tagCompound.putInt("middle", middle.getWoolMeta());
    tagCompound.putInt("right", right.getWoolMeta());
    if (owner != null) {
        tagCompound.putUniqueId("owner", owner);
    }
    if (ownerName != null) {
        tagCompound.putString("owner_name", ITextComponent.Serializer.toJson(ownerName));
    }
    return tagCompound;
}
 
Example #11
Source File: Frequency.java    From EnderStorage with MIT License 5 votes vote down vote up
protected Frequency read_internal(CompoundNBT tagCompound) {
    left = EnumColour.fromWoolMeta(tagCompound.getInt("left"));
    middle = EnumColour.fromWoolMeta(tagCompound.getInt("middle"));
    right = EnumColour.fromWoolMeta(tagCompound.getInt("right"));
    if (tagCompound.hasUniqueId("owner")) {
        owner = tagCompound.getUniqueId("owner");
    }
    if (tagCompound.contains("owner_name")) {
        ownerName = ITextComponent.Serializer.fromJson(tagCompound.getString("owner_name"));
    }
    return this;
}
 
Example #12
Source File: TileEnderTank.java    From EnderStorage with MIT License 5 votes vote down vote up
@Override
public void read(CompoundNBT tag) {
    super.read(tag);
    liquid_state.setFrequency(frequency);
    rotation = tag.getByte("rot") & 3;
    pressure_state.invert_redstone = tag.getBoolean("ir");
}
 
Example #13
Source File: TileEnderTank.java    From EnderStorage with MIT License 5 votes vote down vote up
@Override
public CompoundNBT write(CompoundNBT tag) {
    super.write(tag);
    tag.putByte("rot", (byte) rotation);
    tag.putBoolean("ir", pressure_state.invert_redstone);
    return tag;
}
 
Example #14
Source File: RenderBlockTileEntity.java    From MiningGadgets with MIT License 5 votes vote down vote up
@Override
public void read(CompoundNBT tag) {
    super.read(tag);
    renderBlock = NBTUtil.readBlockState(tag.getCompound("renderBlock"));
    originalDurability = tag.getInt("originalDurability");
    priorDurability = tag.getInt("priorDurability");
    durability = tag.getInt("durability");
    ticksSinceMine = tag.getInt("ticksSinceMine");
    playerUUID = tag.getUniqueId("playerUUID");
    gadgetUpgrades = UpgradeTools.getUpgradesFromTag(tag);
    breakType = MiningProperties.BreakTypes.values()[tag.getByte("breakType")];
    gadgetFilters = MiningProperties.deserializeItemStackList(tag.getCompound("gadgetFilters"));
    gadgetIsWhitelist = tag.getBoolean("gadgetIsWhitelist");
    blockAllowed = tag.getBoolean("blockAllowed");
}
 
Example #15
Source File: ModificationTableTileEntity.java    From MiningGadgets with MIT License 5 votes vote down vote up
@Override
public CompoundNBT write(CompoundNBT tag) {
    handler.ifPresent(h -> {
        CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT();
        tag.put("inv", compound);
    });
    return super.write(tag);
}
 
Example #16
Source File: UpgradeTools.java    From MiningGadgets with MIT License 5 votes vote down vote up
public static CompoundNBT setUpgradesNBT(List<Upgrade> laserUpgrades) {
    CompoundNBT listCompound = new CompoundNBT();
    ListNBT list = new ListNBT();

    laserUpgrades.forEach( upgrade -> {
        CompoundNBT compound = new CompoundNBT();
        compound.putString(KEY_UPGRADE, upgrade.getName());
        compound.putBoolean(KEY_ENABLED, upgrade.isEnabled());
        list.add(compound);
    });

    listCompound.put(KEY_UPGRADES, list);
    return listCompound;
}
 
Example #17
Source File: MiningProperties.java    From MiningGadgets with MIT License 5 votes vote down vote up
public static void nextBreakType(ItemStack gadget) {
    CompoundNBT compound = gadget.getOrCreateTag();
    if (compound.contains(BREAK_TYPE)) {
        int type = getBreakType(gadget).ordinal() == BreakTypes.values().length - 1 ? 0 : getBreakType(gadget).ordinal() + 1;
        setBreakType(gadget, BreakTypes.values()[type]);
    } else {
        setBreakType(gadget, BreakTypes.FADE);
    }
}
 
Example #18
Source File: EnderItemStorage.java    From EnderStorage with MIT License 5 votes vote down vote up
public void loadFromTag(CompoundNBT tag) {
    size = tag.getByte("size");
    empty();
    InventoryUtils.readItemStacksFromTag(items, tag.getList("Items", 10));
    if (size != EnderStorageConfig.storageSize) {
        alignSize();
    }
}
 
Example #19
Source File: EnderItemStorage.java    From EnderStorage with MIT License 5 votes vote down vote up
public CompoundNBT saveToTag() {
    if (size != EnderStorageConfig.storageSize && open == 0) {
        alignSize();
    }

    CompoundNBT compound = new CompoundNBT();
    compound.put("Items", InventoryUtils.writeItemStacksToTag(items));
    compound.putByte("size", (byte) size);

    return compound;
}
 
Example #20
Source File: CmdEnchant.java    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public void enchant(ItemStack item, Enchantment e, int level) {
	if (item.getTag() == null) item.setTag(new CompoundNBT());
	if (!item.getTag().contains("Enchantments", 9)) {
		item.getTag().put("Enchantments", new ListNBT());
    }

    ListNBT listnbt = item.getTag().getList("Enchantments", 10);
    CompoundNBT compoundnbt = new CompoundNBT();
    compoundnbt.putString("id", String.valueOf(Registry.ENCHANTMENT.getKey(e)));
    compoundnbt.putInt("lvl", level);
    listnbt.add(compoundnbt);
}
 
Example #21
Source File: MCDataInput.java    From CodeChickenLib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Reads a {@link FluidStack} from the stream.
 *
 * @return The {@link FluidStack}.
 */
default FluidStack readFluidStack() {
    if (!readBoolean()) {
        return FluidStack.EMPTY;
    } else {
        Fluid fluid = readRegistryIdUnsafe(ForgeRegistries.FLUIDS);
        int amount = readVarInt();
        CompoundNBT tag = readCompoundNBT();
        if (fluid == Fluids.EMPTY) {
            return FluidStack.EMPTY;
        }
        return new FluidStack(fluid, amount, tag);
    }
}
 
Example #22
Source File: MCDataOutput.java    From CodeChickenLib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Writes a {@link CompoundNBT} to the stream.
 *
 * @param tag The {@link CompoundNBT}.
 * @return The same stream.
 */
default MCDataOutput writeCompoundNBT(CompoundNBT tag) {
    if (tag == null) {
        writeBoolean(false);
    } else {
        try {
            writeBoolean(true);
            CompressedStreamTools.write(tag, toDataOutput());
        } catch (IOException e) {
            throw new EncoderException("Failed to write CompoundNBT to stream.", e);
        }
    }
    return this;
}
 
Example #23
Source File: CCBlockRendererDispatcher.java    From CodeChickenLib with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings ("Convert2MethodRef")//Suppress these, the lambdas need to be synthetic functions instead of a method reference.
private static void handleCaughtException(Throwable t, BlockState inState, BlockPos pos, ILightReader world) {
    Block inBlock = inState.getBlock();
    TileEntity tile = world.getTileEntity(pos);

    StringBuilder builder = new StringBuilder("\n CCL has caught an exception whilst rendering a block\n");
    builder.append("  BlockPos:      ").append(String.format("x:%s, y:%s, z:%s", pos.getX(), pos.getY(), pos.getZ())).append("\n");
    builder.append("  Block Class:   ").append(tryOrNull(() -> inBlock.getClass())).append("\n");
    builder.append("  Registry Name: ").append(tryOrNull(() -> inBlock.getRegistryName())).append("\n");
    builder.append("  State:         ").append(inState).append("\n");
    builder.append(" Tile at position\n");
    builder.append("  Tile Class:    ").append(tryOrNull(() -> tile.getClass())).append("\n");
    builder.append("  Tile Id:       ").append(tryOrNull(() -> TileEntityType.getId(tile.getType()))).append("\n");
    builder.append("  Tile NBT:      ").append(tryOrNull(() -> tile.write(new CompoundNBT()))).append("\n");
    if (ProxyClient.messagePlayerOnRenderExceptionCaught) {
        builder.append("You can turn off player messages in the CCL config file.\n");
    }
    String logMessage = builder.toString();
    String key = ExceptionUtils.getStackTrace(t) + logMessage;
    if (!ExceptionMessageEventHandler.exceptionMessageCache.contains(key)) {
        ExceptionMessageEventHandler.exceptionMessageCache.add(key);
        logger.error(logMessage, t);
    }
    PlayerEntity player = Minecraft.getInstance().player;
    if (ProxyClient.messagePlayerOnRenderExceptionCaught && player != null) {
        long time = System.nanoTime();
        if (TimeUnit.NANOSECONDS.toSeconds(time - lastTime) > 5) {
            lastTime = time;
            player.sendMessage(new StringTextComponent("CCL Caught an exception rendering a block. See the log for info."));
        }
    }
}
 
Example #24
Source File: DryingRackTileEntity.java    From Survivalist with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public CompoundNBT write(CompoundNBT compound)
{
    compound = super.write(compound);
    compound.put("Items", items.serializeNBT());
    compound.putIntArray("RemainingTime", dryTimeRemaining);
    return compound;
}
 
Example #25
Source File: ChoppingBlockTileEntity.java    From Survivalist with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public CompoundNBT write(CompoundNBT compound)
{
    compound = super.write(compound);
    compound.put("Inventory", CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.writeNBT(slotInventory, null));
    return compound;
}
 
Example #26
Source File: ChoppingBlockTileEntity.java    From Survivalist with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public CompoundNBT getUpdateTag()
{
    CompoundNBT compound = new CompoundNBT();
    compound.put("Item", slotInventory.getStackInSlot(0).serializeNBT());
    return compound;
}
 
Example #27
Source File: NBTStructureLoader.java    From BoundingBoxOutlineReloaded with MIT License 5 votes vote down vote up
SimpleStructureStart(CompoundNBT compound) {
    super(null,
            0,
            0,
            null,
            new MutableBoundingBox(compound.getIntArray("BB")),
            0,
            0);

    ListNBT children = compound.getList("Children", 10);
    for (int index = 0; index < children.size(); ++index) {
        CompoundNBT child = children.getCompound(index);
        if (child.contains("BB")) this.components.add(new SimpleStructurePiece(child));
    }
}
 
Example #28
Source File: SawmillTileEntity.java    From Survivalist with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void func_230337_a_(BlockState state, CompoundNBT compound)
{
    super.func_230337_a_(state, compound);

    ITEMS_CAP.readNBT(inventory, null, compound.get("Items"));

    remainingBurnTime = compound.getInt("BurnTime");
    cookTime = compound.getInt("CookTime");
    needRefreshRecipe = true;
}
 
Example #29
Source File: SawmillTileEntity.java    From Survivalist with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public CompoundNBT write(CompoundNBT compound)
{
    compound = super.write(compound);

    compound.put("Items", ITEMS_CAP.writeNBT(inventory, null));

    compound.putInt("BurnTime", (short) this.remainingBurnTime);
    compound.putInt("CookTime", (short) this.cookTime);

    return compound;
}
 
Example #30
Source File: DryingRackTileEntity.java    From Survivalist with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public CompoundNBT getUpdateTag()
{
    CompoundNBT compound = super.getUpdateTag();
    compound.put("Items", items.serializeNBT());
    return compound;
}