Jump to content

Reading from NBT issue


BourgeoisArab

Recommended Posts

I am trying to make a custom cauldron and working out how to make it store water properly. I have it filling and emptying, but if it's filled, and I log out and then log in, it isn't filled anymore. I think it has something to do with my readFromNBT method, but I'm not sure. Can anyone point out where I went wrong?

 

Here is my Tile Entity class for it:

package jakoubeck503.alchemicalinstillation.common.tileentity;

import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidEvent;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
import net.minecraftforge.fluids.IFluidTank;

public class TEBrewingCauldron extends TileEntity implements IFluidTank, IFluidHandler {

private FluidTank tank = new FluidTank(FluidContainerRegistry.BUCKET_VOLUME);
private boolean boiling = false;

public TEBrewingCauldron() {
	System.out.println("Creating a new tile entity...");
}

public void setBoiling(boolean par1) {
	this.boiling = par1;
	System.out.println("Cauldron " + (this.boiling==true ? "is" : "isn't") + " boiling!");
}

public boolean getBoiling() {
	return this.boiling;
}

public boolean isFillable() {
	if (tank.getFluid()!=null) {
		if (tank.getFluid().getFluid()==FluidRegistry.WATER && tank.getFluidAmount()<FluidContainerRegistry.BUCKET_VOLUME){
			return true;
		} else return false;
	} else return true;
}

@Override
    public void readFromNBT(NBTTagCompound nbt) {
	System.out.println("Reading from NBT...");
	super.readFromNBT(nbt);
        if (!nbt.hasKey("Empty")) {
            FluidStack fluid = this.tank.getFluid().loadFluidStackFromNBT(nbt);
            System.out.println(fluid.amount + "mB of " + fluid.getFluid());

            if (fluid!=null) {
                this.tank.setFluid(fluid);
            }
        }
        if (tank.getFluid().getFluid()!=FluidRegistry.WATER){
        	System.out.println("ERROR! Not equal to water...");
        }
    }

@Override
    public void writeToNBT(NBTTagCompound nbt) {
    	System.out.println("Writing to NBT...");
    	super.writeToNBT(nbt);
        if (tank.getFluid()!=null) {
        	tank.getFluid().writeToNBT(nbt);
        } else {
            nbt.setString("Empty", "");
        }
    }

@Override
public FluidStack getFluid() {
	return tank.getFluid();
}

@Override
public int getFluidAmount() {
	if (tank.getFluid()==null) {
		return 0;
	} else return tank.getFluidAmount();
}

@Override
public int getCapacity() {
	return tank.getCapacity();
}

@Override
public FluidTankInfo getInfo() {
	return tank.getInfo();
}

@Override
public int fill(ForgeDirection from, FluidStack resource, boolean doFill) {
	// TODO Auto-generated method stub
	return tank.fill(resource, doFill);
}

@Override
public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public boolean canFill(ForgeDirection from, Fluid fluid) {
	// TODO Auto-generated method stub
	return false;
}

@Override
public boolean canDrain(ForgeDirection from, Fluid fluid) {
	// TODO Auto-generated method stub
	return false;
}

@Override
public FluidTankInfo[] getTankInfo(ForgeDirection from) {
	// TODO Auto-generated method stub
	return null;
}

    private void setFluid(FluidStack f) {
	this.tank.setFluid(f);
}

@Override
public int fill(FluidStack resource, boolean doFill) {
	return tank.fill(resource, doFill);
}

@Override
public FluidStack drain(int maxDrain, boolean doDrain) {
	return tank.drain(maxDrain, doDrain);
}


}

Link to comment
Share on other sites

Now, I am not the best with NBT but I think I see a problem. Your are using the key Empty a bit oddly. Imagine this situation.

 

1. You place a cauldron down. It is empty.

2. writeToNBT gets called. Since the tank is empty, "Empty" gets set a value

nbt.setString("Empty", "");

3. You put water in, writeToNBT gets called again.

4. Quit the world and log back in.

5.  readFromNBT runs. Here is the problem. On the first if statement it checks if the key "Empty" exists. It does! You set it earlier, it hasn't been removed in any way. Because it exists the rest of the code between the brackets is ignored. Fluid never gets set.

 

NOTE: I could be COMPLETELY wrong. However this feels right to me. i recommend you change the Empty key completely. Maybe to some kind of boolean? Not too familiar with NBT so you'll have to figure it out.

 

Good Luck

An average guy who mods Minecraft. If you need help and are willing to use your brain, don't be afraid to ask.

 

Also, check out the Unofficial Minecraft Coder Pack (MCP) Prerelease Center for the latest from the MCP Team!

 

Was I helpful? Leave some karma/thanks! :)

Link to comment
Share on other sites

I've tried to do it the way it is in TileFluidHandler, but still it doesn't work. Does that mean the problem is elsewhere? Like my cauldron block class:

package jakoubeck503.alchemicalinstillation.common.block;

import jakoubeck503.alchemicalinstillation.AlchemicalInstillation;
import jakoubeck503.alchemicalinstillation.common.tileentity.TEBrewingCauldron;

import java.util.List;

import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class BlockBrewingCauldron extends BlockContainer {

    @SideOnly(Side.CLIENT)
    private IIcon iicon;
    
public BlockBrewingCauldron() {
	super(Material.iron);
	setCreativeTab(AlchemicalInstillation.tabAlchemicalInstillation);
	this.setBlockName("blockBrewingCauldron");
	this.setBlockTextureName(AlchemicalInstillation.modid + ":" + "brewingCauldron_side");
	this.setHardness(1.0F);
	this.setResistance(2.0F);
}

public TileEntity createNewTileEntity(World world, int i1) {
	return new TEBrewingCauldron();
}

public TileEntity getTileEntity(World world, int x, int y, int z) {
	return world.getTileEntity(x, y, z);
}

    public void setBlockBoundsForItemRender() {
        this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
    }
    
    public boolean isOpaqueCube() {
        return false;
    }
    
    public int getRenderType() {
        return -1;
    }

    public boolean renderAsNormalBlock() {
        return false;
    }
    
    public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB axis, List list, Entity entity) {
        this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.3125F, 1.0F);
        super.addCollisionBoxesToList(world, x, y, z, axis, list, entity);
        float f = 0.125F;
        this.setBlockBounds(0.0F, 0.0F, 0.0F, f, 1.0F, 1.0F);
        super.addCollisionBoxesToList(world, x, y, z, axis, list, entity);
        this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, f);
        super.addCollisionBoxesToList(world, x, y, z, axis, list, entity);
        this.setBlockBounds(1.0F - f, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
        super.addCollisionBoxesToList(world, x, y, z, axis, list, entity);
        this.setBlockBounds(0.0F, 0.0F, 1.0F - f, 1.0F, 1.0F, 1.0F);
        super.addCollisionBoxesToList(world, x, y, z, axis, list, entity);
        this.setBlockBoundsForItemRender();
    }
    
    @Override
    @SubscribeEvent
    public boolean onBlockEventReceived(World world, int x, int y, int z, int something, int different) {
    	System.out.println("BLOCK CHANGE!!!");
    	if (world.getBlock(x, y - 1, z)==Blocks.fire || world.getBlock(x, y - 1, z)==Blocks.lava) {
    		System.out.println("LAVA AND FIRE!!!");
    		TEBrewingCauldron entity =  (TEBrewingCauldron) world.getTileEntity(x, y, z);
    		entity.setBoiling(true);
    		return true;
    	} else return false;
    }
    
    @Override
    public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) {
    	TEBrewingCauldron tileEntity = (TEBrewingCauldron) world.getTileEntity(x, y, z);
    	
    	if (tileEntity==null || player.isSneaking()) {
    		return false;
    	}
    	
    	ItemStack heldItem = player.getCurrentEquippedItem();
    	
    	if (heldItem!=null) {
    		if (heldItem.getItem()==Items.water_bucket) {
    			if (tileEntity.isFillable()) {
    				tileEntity.fill(ForgeDirection.UP, new FluidStack(FluidRegistry.WATER, FluidContainerRegistry.BUCKET_VOLUME), true);
    				if (!player.capabilities.isCreativeMode)
    					player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(Items.bucket));
    			}
    			return true;
    		}
    		
    		if (heldItem.getItem()==Items.glass_bottle && tileEntity.getFluidAmount()>=333){
    			tileEntity.drain(ForgeDirection.UP, 333, true);
    			if (!player.capabilities.isCreativeMode)
    				player.inventory.setInventorySlotContents(player.inventory.currentItem, FluidContainerRegistry.fillFluidContainer(
    						FluidRegistry.getFluidStack(FluidRegistry.WATER.getName(), 333), FluidContainerRegistry.EMPTY_BOTTLE));
    			return true;
    		}
    		if (heldItem.getItem()==Items.bucket && tileEntity.getFluidAmount()>=FluidContainerRegistry.BUCKET_VOLUME){
    			tileEntity.drain(ForgeDirection.UP, FluidContainerRegistry.BUCKET_VOLUME, true);
    			if (!player.capabilities.isCreativeMode)
    				player.inventory.setInventorySlotContents(player.inventory.currentItem, FluidContainerRegistry.fillFluidContainer(
    						FluidRegistry.getFluidStack(FluidRegistry.WATER.getName(), FluidContainerRegistry.BUCKET_VOLUME), FluidContainerRegistry.EMPTY_BUCKET));
    			return true;
    		}

    	}
    	return false;
    }


}


Link to comment
Share on other sites

The problem is when the tile is unloaded and reloaded the nbt is only loaded on the server to fix this add the following methods to your tile.

@Override
public Packet getDescriptionPacket() {
	NBTTagCompound tagCompound = new NBTTagCompound();
	writeToNBT(tagCompound);
	return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 1, tagCompound);
}

@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) {
	readFromNBT(pkt.func_148857_g());
}

 

they will read the nbt from the server and send it to the client. they are called every time the tile is loaded or the block is updated.

I am the author of Draconic Evolution

Link to comment
Share on other sites

You need to all markDirty() whenever something in your tile entity changes, so that it will be written out when the world is saved.

 

Also, you need to implement getDescriptionPacket() and onDescriptionPacket() even for a single-player environment. There is still a server and a client in single player (they just exist in the same process) and they need to be kept in sync.

Link to comment
Share on other sites

I am positively flummoxed now. I've marked the tile entity dirty and added this piece of code:

    @Override
    public void updateEntity() {
    	System.out.println(this.getFluidAmount() + "mB");
    }

When I place the cauldron down, it prints out "0mB" continuously, as expected. When I fill it, again it continuously prints "1000mB". However if leave it full and re-log, the console does this (if I leave the cauldron empty, it's normal after re-logging):

0mB
0mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
1000mB

 

Does anybody have any explanation as to what is going on here?

Link to comment
Share on other sites

The

readFromNBT()

method only gets called on the server side. So the server knows the saved value (1000mB), but the client still has the default value (0mB). To solve this add the methods from brandon3055 post.

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I use Bisect-Hosting, and I host a relatively modded server.  There is a mod I desperately want to have in a server. https://www.curseforge.com/minecraft/mc-mods/minehoplite This is MineHop. It's a mod that replicates the movement capabilities seen in Source Engine games, such as Half-Life, and such.  https://youtu.be/SbtLo7VbOvk - A video explaining the mod, if anyone is interested.  It is a clientside mod, meaning whoever is using it can change anything about the mod that they want, with no restrictions, even when they join a server with the same mod. They can change it to where they can go infinitely fast, or do some other overpowered thing. I don't want that to happen. So I just want to know if there is some way to force the SERVER'S configuration file, onto whoever is joining.  I'm not very savvy with all this modding stuff. There are two config files: minehop-common.txt, and minehop.txt I don't really know much about how each are different. I just know what the commands relating to acceleration and stuff mean.    
    • My journey into crypto trading began tentatively, with me dipping my toes into the waters by purchasing my first Bitcoin through a seasoned trader. With an initial investment of $5,000, I watched as my investment grew, proving to be both fruitful and lucrative. Encouraged by this success, I decided to increase my investment to $150,000, eager to capitalize on the growing popularity of cryptocurrency, However, as cryptocurrency gained mainstream attention, so too did the number of self-proclaimed "experts" in the field. Suddenly, everyone seemed to be a crypto guru, and more and more people were eager to jump on the bandwagon without fully understanding the intricacies of this complex world. With promises of quick and easy profits, these con artists preyed on the uninformed, luring them into schemes that often ended in disappointment and financial loss. Unfortunately, I fell victim to one such scheme. Seduced by the allure of easy money, I entrusted my hard-earned funds to a dubious trading platform, granting them access to my accounts in the hopes of seeing my investment grow. For a brief period, everything seemed to be going according to plan, with regular withdrawals and promising returns on my investment. However, my hopes were soon dashed when, without warning, communication from the platform ceased, and my Bitcoin holdings vanished into thin air. Feeling helpless and betrayed, I confided in a family member about my predicament. They listened sympathetically and offered a glimmer of hope in the form of a recommendation for Wizard Web Recovery. Intrigued by the possibility of reclaiming what I had lost, I decided to explore this option further. From the moment I reached out to Wizard Web Recovery, I was met with professionalism and empathy. They took the time to understand my situation and reassured me that I was not alone in my plight. With their guidance, I embarked on a journey to reclaim what was rightfully mine. Wizard Web Recovery's expertise and dedication were evident from the start. They meticulously analyzed the details of my case, uncovering crucial evidence that would prove invaluable in our quest for justice. With each step forward, they kept me informed and empowered, instilling in me a newfound sense of hope and determination. Through their tireless efforts and unwavering support, Wizard Web Recovery succeeded in recovering my lost Bitcoin holdings. It was a moment of triumph and relief, knowing that justice had been served and that I could finally put this chapter behind me. In conclusion, My experience with Wizard Web Recovery  was nothing short of transformative. Their professionalism, expertise, and unwavering commitment to their clients set them apart as true leaders in the field of cryptocurrency recovery. I am forever grateful for their assistance and would highly recommend their services to anyone in need of help navigating the treacherous waters of cryptocurrency scams. 
    • Ok so: Two things to note: It got stuck due to my dimension type. It was previously the same as the overworld dimension tpye but after changing it , it didn't freeze during spawn generation. ALSO, APPARENTLY, the way I'm doing things, the game can't have two extremely-rich dimensions or it will make the new chunk generation be veeery VEEERY slow. I'm doing the dimension file genreation all in the data generation step now, so it's all good. Mostly. If anybody has any tips regarding how can i more efficently generate a biome-rich dimension, im all ears.
    • https://mclo.gs/qTo3bUE  
    • Check for the mods ingame - create a new world in creative mod and check the creative inventory  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.