Jump to content

[1.10.2] 2 Problems with tile entity and container


Recommended Posts

Posted

Hi,

i have a custom made kind of furnance. The burning and tank stuff, everyting is working fine.

The problems i have are:

 

1. If there is an item (stone) in the output slot and i shift click a stone in player inventory, he puts the item into this output slot, ignoring isItemValid in the container slot and isItemValidForSlot in the tile entity.

 

2. If i use hoppers to insert and extract items, he will do it, as long as i don't open the gui. If the gui is open, the extraction will not be updated in the gui. The insert will. If i do any interaction then with the gui, the items will be extracted and the gui slot getting updated.

 

This is the tile entity class

Quote

package thewizardmod.extractor;

import javax.annotation.Nullable;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.inventory.SlotFurnaceFuel;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemHoe;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.item.ItemTool;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraftforge.common.ForgeModContainer;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.UniversalBucket;
import net.minecraftforge.fluids.capability.TileFluidHandler;

public class TileEntityExtractor extends TileFluidHandler implements ISidedInventory, ITickable{
	
	public static final int CAPACITY = 10 * Fluid.BUCKET_VOLUME + 1;
	
	
	public ItemStack itemStacks[] = new ItemStack[5];

	public IInventory inventory;
	
	public int coolDown;
	public int burntime;
	public int burntimeLeft;
	public int burntimeMax;
	
	private int bucketInputSlot = 0;
	private int bucketOutputSlot = 1;
	private int oreInputSlot = 2;
	private int stoneOutputSlot = 3;
	private int fuelInputSlot = 4;


    private static final int[] SLOTS_TOP = new int[] {0, 2, 4};
    private static final int[] SLOTS_BOTTOM = new int[] {1, 3};
    private static final int[] SLOTS_SIDES = new int[] {};

	public TileEntityExtractor() {
		tank = new FluidTankWithTile(this, CAPACITY);
		tank.setFluid(new FluidStack(thewizardmod.fluids.StartupCommon.fluidMagic, 1));
		this.coolDown = 0;
		this.burntime = 0;
		this.burntimeLeft = 0;
		this.burntimeMax = 0;
	}

	
	
	@Override
	public NBTTagCompound getUpdateTag() {
		return writeToNBT(new NBTTagCompound());
	}

	@Nullable
	@Override
	public SPacketUpdateTileEntity getUpdatePacket() {
		return new SPacketUpdateTileEntity(getPos(), 0, getUpdateTag());
	}

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

    public void readFromNBT(NBTTagCompound compound)
    {
        super.readFromNBT(compound);
        NBTTagList nbttaglist = compound.getTagList("Items", 10);
        this.itemStacks = new ItemStack[this.getSizeInventory()];

        for (int i = 0; i < nbttaglist.tagCount(); ++i)
        {
            NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i);
            int j = nbttagcompound.getByte("Slot");

            if (j >= 0 && j < this.itemStacks.length)
            {
                this.itemStacks[j] = ItemStack.loadItemStackFromNBT(nbttagcompound);
            }
        }
        int amount = compound.getInteger("tankAmount");
        if(amount == 0)
        	amount = 1;
        tank.drainInternal(CAPACITY, true);
        tank.fill(new FluidStack(thewizardmod.fluids.StartupCommon.fluidMagic, amount), true);

        this.coolDown = compound.getInteger("coolDown");
        this.burntime = compound.getInteger("burntime");
        this.burntimeLeft = compound.getInteger("burntimeLeft");
        this.burntimeMax = compound.getInteger("burntimeMax");
    }

    public NBTTagCompound writeToNBT(NBTTagCompound compound)
    {
        super.writeToNBT(compound);
        NBTTagList nbttaglist = new NBTTagList();

        for (int i = 0; i < this.itemStacks.length; ++i)
        {
            if (this.itemStacks[i] != null)
            {
                NBTTagCompound nbttagcompound = new NBTTagCompound();
                nbttagcompound.setByte("Slot", (byte)i);
                this.itemStacks[i].writeToNBT(nbttagcompound);
                nbttaglist.appendTag(nbttagcompound);
            }
        }

        compound.setTag("Items", nbttaglist);
        
        compound.setInteger("tankAmount", tank.getFluidAmount());

        compound.setInteger("coolDown", this.coolDown);
        compound.setInteger("burntime", this.burntime);
        compound.setInteger("burntimeLeft", this.burntimeLeft);
        compound.setInteger("burntimeMax", this.burntimeMax);

        return compound;
    }


	@Override
	public int getSizeInventory() {
		return this.itemStacks.length;
	}



	@Override
	@Nullable
	public ItemStack getStackInSlot(int index) {
		return this.itemStacks[index];
	}



	@Override
	@Nullable
	public ItemStack decrStackSize(int index, int count) {
		return ItemStackHelper.getAndSplit(this.itemStacks, index, count);
	}



	@Override
	@Nullable
	public ItemStack removeStackFromSlot(int index) {
		return ItemStackHelper.getAndRemove(this.itemStacks, index);
	}



	@Override
	public void setInventorySlotContents(int index, @Nullable ItemStack stack) {
        boolean flag = stack != null && stack.isItemEqual(this.itemStacks[index]) && ItemStack.areItemStackTagsEqual(stack, this.itemStacks[index]);
        this.itemStacks[index] = stack;

        if (stack != null && stack.stackSize > this.getInventoryStackLimit())
        {
            stack.stackSize = this.getInventoryStackLimit();
        }

        if (!flag)
        {
            this.markDirty();
        }
	}



	@Override
	public int getInventoryStackLimit() {
		return 64;
	}



	@Override
	public boolean isUseableByPlayer(EntityPlayer player) {
        return this.worldObj.getTileEntity(this.pos) != this ? false : player.getDistanceSq((double)this.pos.getX() + 0.5D, (double)this.pos.getY() + 0.5D, (double)this.pos.getZ() + 0.5D) <= 64.0D;
	}



	@Override
	public void openInventory(EntityPlayer player) {
	}



	@Override
	public void closeInventory(EntityPlayer player) {
	}



	@Override
	public boolean isItemValidForSlot(int index, ItemStack itemstack) {
        if (index == oreInputSlot)
        {
        	if(itemstack.getItem() == Item.getItemFromBlock(thewizardmod.ores.StartupCommon.shadowdustOre))
        		return true;
        }
        else if(index == bucketInputSlot)
        {
            if(itemstack != null)
            {
            	// Empty buckets are allowed
            	if(itemstack.getItem() == Items.BUCKET)
            	{
            		return true;
            	}
            }
        }
        else if(index == fuelInputSlot)
        {
            return isItemFuel(itemstack) || SlotFurnaceFuel.isBucket(itemstack) && (itemstack == null || itemstack.getItem() != Items.BUCKET);
        }
        return false;
	}




	@Override
	public void setField(int id, int value) {
	}



	@Override
	public int getFieldCount() {
		return 0;
	}

	@Override
	public int getField(int id) {
		return 0;
	}



	@Override
	public void clear() {
        for (int i = 0; i < this.itemStacks.length; ++i)
        {
            this.itemStacks[i] = null;
        }
	}



	@Override
	public String getName() {
        return "container.twm_tank.name";
	}



	@Override
	public boolean hasCustomName() {
		return false;
	}



	@Override
	public int[] getSlotsForFace(EnumFacing side) {
        return side == EnumFacing.DOWN ? SLOTS_BOTTOM : (side == EnumFacing.UP ? SLOTS_TOP : SLOTS_SIDES);
	}



	@Override
	public boolean canInsertItem(int index, ItemStack itemStackIn,
			EnumFacing direction) {
		return this.isItemValidForSlot(index, itemStackIn);
		}



	@Override
	public boolean canExtractItem(int index, ItemStack stack,
			EnumFacing direction) {
			return true;
	}



	@Override
	public void update() {
		ItemStack inputStack = getStackInSlot(bucketInputSlot);

        if(inputStack != null)
        {
        	// Empty buckets are allowed
        	if(inputStack.getItem() == Items.BUCKET)
        	{
    			if(tank.getFluidAmount() - 1000 > 0 && getStackInSlot(bucketOutputSlot) == null)
    			{
    				tank.drain(1000, true);
    				decrStackSize(bucketInputSlot, 1);
    				ItemStack bucket = UniversalBucket.getFilledBucket(ForgeModContainer.getInstance().universalBucket, thewizardmod.fluids.StartupCommon.fluidMagic);
     		       	setInventorySlotContents(bucketOutputSlot, bucket);
     		        markDirty();
    			}
        	}
        }
        
        ItemStack oreInputStack = getStackInSlot(oreInputSlot);

        if(oreInputStack != null)
        {
        	if(burntimeMax > 0)
        	{
        		this.coolDown++;
        		// It takes 2 second(40 ticks) to extract liquid magic from ore
        		if(this.coolDown >= 40)
        		{
    				coolDown = 40;
        			// We need 10 Ore to get a full bucket (1000mB)
        			if(tank.getFluidAmount() + 100 <= tank.getCapacity())
        			{
        				if(itemStacks[stoneOutputSlot] != null)
 		       			{	
        					if(itemStacks[stoneOutputSlot].stackSize < getInventoryStackLimit())
        					{
 		    	   				itemStacks[stoneOutputSlot].stackSize++;
 		        				tank.fill(new FluidStack(thewizardmod.fluids.StartupCommon.fluidMagic, 100), true);
 		        				decrStackSize(oreInputSlot, 1);
 		        				this.coolDown = 0;
        					}
 		       			}
 		       			else
 		       			{
 		       				itemStacks[stoneOutputSlot] = new ItemStack(Blocks.STONE);
 	        				tank.fill(new FluidStack(thewizardmod.fluids.StartupCommon.fluidMagic, 100), true);
 	        				decrStackSize(oreInputSlot, 1);
 	        				this.coolDown = 0;
 		       			}
 		       			setInventorySlotContents(stoneOutputSlot, itemStacks[stoneOutputSlot]);
 		       			markDirty();
        			}
        		}
        	}
        }
        else
        {
        	coolDown = 0;
            markDirty();
        }
        
        // Nothing burning
        if(this.burntimeMax == 0)
        {
        	ItemStack oreStack = getStackInSlot(oreInputSlot);
        	ItemStack fuelInputStack = getStackInSlot(fuelInputSlot);
        	if(fuelInputStack != null && oreStack != null)
        	{
        		if(tank.getFluidAmount() < tank.getCapacity())
        		{
        			if(itemStacks[stoneOutputSlot] != null)
        			{
        				if(itemStacks[stoneOutputSlot].stackSize < getInventoryStackLimit())
        				{
        					burntimeMax = getItemBurnTime(fuelInputStack);
        					if(burntimeMax > 0)
        					{
        						decrStackSize(fuelInputSlot, 1);
        						markDirty();
        					}
        				}
        			}
        			else
        			{
        				burntimeMax = getItemBurnTime(fuelInputStack);
        				if(burntimeMax > 0)
        				{
        					decrStackSize(fuelInputSlot, 1);
        					markDirty();
        				}
        			}
        		}
        	}
        }
        
        // burn fuel
        if(this.burntime < burntimeMax)
        {
        	burntime++;
            markDirty();
        }
        else
        {
        	burntime = 0;
        	burntimeMax = 0;
            markDirty();
        }
        markDirty();
	}

    public static int getItemBurnTime(ItemStack stack)
    {
        if (stack == null)
        {
            return 0;
        }
        else
        {
            Item item = stack.getItem();

            if (item instanceof ItemBlock && Block.getBlockFromItem(item) != Blocks.AIR)
            {
                Block block = Block.getBlockFromItem(item);

                if (block == Blocks.WOODEN_SLAB)
                {
                    return 150;
                }

                if (block.getDefaultState().getMaterial() == Material.WOOD)
                {
                    return 300;
                }

                if (block == Blocks.COAL_BLOCK)
                {
                    return 16000;
                }
            }

            if (item instanceof ItemTool && "WOOD".equals(((ItemTool)item).getToolMaterialName())) return 200;
            if (item instanceof ItemSword && "WOOD".equals(((ItemSword)item).getToolMaterialName())) return 200;
            if (item instanceof ItemHoe && "WOOD".equals(((ItemHoe)item).getMaterialName())) return 200;
            if (item == Items.STICK) return 100;
            if (item == Items.COAL) return 1600;
            if (item == Items.LAVA_BUCKET) return 20000;
            if (item == Item.getItemFromBlock(Blocks.SAPLING)) return 100;
            if (item == Items.BLAZE_ROD) return 2400;
            return net.minecraftforge.fml.common.registry.GameRegistry.getFuelValue(stack);
        }
    }

    public static boolean isItemFuel(ItemStack stack)
    {
        return getItemBurnTime(stack) > 0;
    }


}

And this is the container

Quote

package thewizardmod.extractor;


import javax.annotation.Nullable;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import thewizardmod.ores.StartupCommon;
 
public class ContainerExtractor extends Container {
 
    public final TileEntityExtractor tileTank;

    public ContainerExtractor(InventoryPlayer playerInventory, TileEntityExtractor te)
    {
        this.tileTank = te;
        this.addSlotToContainer(new InputSlot(tileTank, 0, 26, 19));
        this.addSlotToContainer(new OutputSlot(tileTank, 1, 26, 55));
        this.addSlotToContainer(new OreInputSlot(tileTank, 2, 80, 19));
        this.addSlotToContainer(new StoneOutputSlot(tileTank, 3, 134, 19));
        this.addSlotToContainer(new FuelInputSlot(tileTank, 4, 80, 54));

        for (int i = 0; i < 3; ++i)
        {
            for (int j = 0; j < 9; ++j)
            {
                this.addSlotToContainer(new Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
            }
        }

        for (int k = 0; k < 9; ++k)
        {
            this.addSlotToContainer(new Slot(playerInventory, k, 8 + k * 18, 142));
        }
    }
    /**
     * Determines whether supplied player can use this container
     */
    public boolean canInteractWith(EntityPlayer playerIn)
    {
        return this.tileTank.isUseableByPlayer(playerIn);
    }

    /**
     * Take a stack from the specified inventory slot.
     */
    @Nullable
    public ItemStack transferStackInSlot(EntityPlayer playerIn, int index)
    {
        ItemStack itemstack = null;
        Slot slot = (Slot)this.inventorySlots.get(index);
 
        if (slot != null && slot.getHasStack()) {
            ItemStack itemstack1 = slot.getStack();
            itemstack = itemstack1.copy();
 
            if (index < 5) {
                if (!this.mergeItemStack(itemstack1, 5, this.inventorySlots.size(), true)) {
                    return null;
                }
            }
            else if(index != 1 && index != 3) 
            {
            	if(!this.mergeItemStack(itemstack1, 0, 5, false)) 
            	{
            		return null;
            	}
            }
 
            if (itemstack1.stackSize == 0) {
                slot.putStack((ItemStack)null);
            }
            else {
                slot.onSlotChanged();
            }
        }
 
        return itemstack;
    }
    
	public class InputSlot extends Slot {

	    public InputSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) {
			super(inventoryIn, index, xPosition, yPosition);
		}

		// if this function returns false, the player won't be able to insert the given item into this slot
		@Override
		public boolean isItemValid(ItemStack itemstack) {
            if(itemstack != null)
            {
            	// Empty buckets are allowed
            	if(itemstack.getItem() == Items.BUCKET)
            	{
            		return true;
            	}
            }
            
            return false;
		}
	}

	public class OutputSlot extends Slot {

	    public OutputSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) {
			super(inventoryIn, index, xPosition, yPosition);
		}

		// if this function returns false, the player won't be able to insert the given item into this slot
		@Override
		public boolean isItemValid(ItemStack itemstack) {
            return false;
		}
		
		
	}

	public class OreInputSlot extends Slot {

	    public OreInputSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) {
			super(inventoryIn, index, xPosition, yPosition);
		}

		// if this function returns false, the player won't be able to insert the given item into this slot
		@Override
		public boolean isItemValid(ItemStack itemstack) {
            if(itemstack != null)
            {
            	if(itemstack.getItem() == Item.getItemFromBlock(StartupCommon.shadowdustOre))
            	{
            		return true;
            	}
            }
            
            return false;
		}
	}

	public class StoneOutputSlot extends Slot {

	    public StoneOutputSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) {
			super(inventoryIn, index, xPosition, yPosition);
		}

		// if this function returns false, the player won't be able to insert the given item into this slot
		@Override
		public boolean isItemValid(ItemStack itemstack) {
            return false;
		}
	}

	public class FuelInputSlot extends Slot {

	    public FuelInputSlot(IInventory inventoryIn, int index, int xPosition, int yPosition) {
			super(inventoryIn, index, xPosition, yPosition);
		}

		// if this function returns false, the player won't be able to insert the given item into this slot
		@Override
		public boolean isItemValid(ItemStack itemstack) {
            if(itemstack != null)
            {
            	return tileTank.isItemFuel(itemstack);
            }
            
            return false;
		}
	}


}

 

 

Posted

If needed, this is the gui

Quote

package thewizardmod.extractor;

import java.awt.Color;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import thewizardmod.Gui.ProgressBar;
import thewizardmod.Gui.ProgressBar.ProgressBarDirection;
import thewizardmod.Util.CapabilityUtils;

@SideOnly(Side.CLIENT)
public class GuiExtractor extends GuiContainer {
	private ProgressBar TankGauge;
	private ProgressBar progressBar;
	private ProgressBar burnBar;
	
	// This is the resource location for the background image for the GUI
	private static final ResourceLocation texture = new ResourceLocation("thewizardmod", "textures/gui/extractor_bg.png");
	private TileEntityExtractor tileEntityTank;

	public GuiExtractor(InventoryPlayer invPlayer, TileEntityExtractor tile) {
		super(new ContainerExtractor(invPlayer, tile));
		tileEntityTank = tile;
		this.TankGauge = new ProgressBar(texture, ProgressBarDirection.DOWN_TO_UP, 10, 62, 9, 9, 176, 14);
		this.progressBar = new ProgressBar(texture, ProgressBarDirection.LEFT_TO_RIGHT, 35, 17, 98, 18, 195, 0);
		this.burnBar = new ProgressBar(texture, ProgressBarDirection.DOWN_TO_UP, 14, 14, 81, 39, 195, 20);
	}

	// draw the background for the GUI - rendered first
	@Override
	protected void drawGuiContainerBackgroundLayer(float partialTicks, int x, int y) {
		// Bind the image texture of our custom container
		Minecraft.getMinecraft().getTextureManager().bindTexture(texture);
		// Draw the image
		GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
		drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);
	}

	// draw the foreground for the GUI - rendered after the slots, but before the dragged items and tooltips
	// renders relative to the top left corner of the background
	@Override
	protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
		fontRendererObj.drawString("Liquid Magic Extractor", 50, 5, Color.darkGray.getRGB());
		final IFluidHandler fluidHandler = getFluidHandler();
		if (fluidHandler != null) {
	        FluidStack fluid = fluidHandler.getTankProperties()[0].getContents();
	        if (fluid != null)
	        {
	    		this.TankGauge.setMin(fluid.amount - 1).setMax(fluidHandler.getTankProperties()[0].getCapacity() - 1);
	    		this.TankGauge.draw(this.mc);
	    		
	    		this.progressBar.setMin(tileEntityTank.coolDown).setMax(40);
	    		this.progressBar.draw(this.mc);
	    		
	    		this.burnBar.setMin(tileEntityTank.burntimeMax - tileEntityTank.burntime).setMax(tileEntityTank.burntimeMax);
	    		this.burnBar.draw(this.mc);
	        }
		}
	}
	
	private IFluidHandler getFluidHandler() {
		return CapabilityUtils.getCapability(tileEntityTank, CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null);
	}
	
	

}

 

 

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



×
×
  • Create New...

Important Information

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