Jump to content

Recommended Posts

Posted

I have made an autocrafting table (quite different from Buildcraft's), but the problem is, it always crafts item stacks with a stack size of 0. I don't want to give away too much of the code, but here's the tile entity:

 

 

package com.earthcomputer.farmersheaven;

import java.lang.reflect.Field;

import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.gui.IUpdatePlayerListBox;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IChatComponent;
import net.minecraftforge.common.util.Constants;

public class TileEntityAutoCraftingTable extends TileEntity implements IUpdatePlayerListBox, ISidedInventory
{

private Container			container		= new Container() {
												@Override
												public boolean canInteractWith(EntityPlayer player)
												{
													return true;
												}

												@Override
												public void onCraftMatrixChanged(IInventory inventory)
												{
													//changeOutput();
												}
											};

private InventoryCrafting	invCrafting		= new InventoryCrafting(container, 3, 3);
private ItemStack			result;
private IRecipe				currentRecipe;
private boolean				canContinue		= true;
private int					craftTime		= 0;
public static final int		MAX_CRAFT_TIME	= 200;

private String				customName;

private static final Field	invCraftingStackList;

static
{
	try
	{
		invCraftingStackList = InventoryCrafting.class.getDeclaredField("stackList");
	}
	catch (Exception e)
	{
		throw new RuntimeException(e);
	}
	invCraftingStackList.setAccessible(true);
}

@Override
public String getName()
{
	return hasCustomName() ? customName : "container.autocrafting_table";
}

@Override
public boolean hasCustomName()
{
	return customName != null && customName.length() > 0;
}

@Override
public IChatComponent getDisplayName()
{
	return hasCustomName() ? new ChatComponentText(getName()) : new ChatComponentTranslation(getName());
}

@Override
public int getSizeInventory()
{
	return 10;
}

@Override
public ItemStack getStackInSlot(int index)
{
	return index == 9 ? result : invCrafting.getStackInSlot(index);
}

private void setStackInSlot(int index, ItemStack stack)
{
	if(index == 9)
		result = stack;
	else try
	{
		ItemStack before = getStackInSlot(index);
		((ItemStack[]) invCraftingStackList.get(invCrafting))[index] = stack;
		if(!ItemStack.areItemsEqual(before, stack) || !ItemStack.areItemStackTagsEqual(before, stack))
			changeOutput();
	}
	catch (Exception e)
	{
		throw new RuntimeException(e);
	}
}

@Override
public ItemStack decrStackSize(int index, int count)
{
	if(getStackInSlot(index) != null)
	{
		ItemStack stack;

		if(getStackInSlot(index).stackSize <= count)
		{
			stack = getStackInSlot(index);
			setStackInSlot(index, null);
			return stack;
		}
		else
		{
			stack = getStackInSlot(index).splitStack(count);

			if(getStackInSlot(index).stackSize == 0)
			{
				setStackInSlot(index, null);
			}

			return stack;
		}
	}
	else
	{
		return null;
	}
}

@Override
public ItemStack getStackInSlotOnClosing(int index)
{
	if(getStackInSlot(index) != null)
	{
		ItemStack itemstack = getStackInSlot(index);
		setStackInSlot(index, null);
		return itemstack;
	}
	else
	{
		return null;
	}
}

@Override
public void setInventorySlotContents(int index, ItemStack stack)
{
	boolean sameStackInSlot = stack != null && stack.isItemEqual(getStackInSlot(index))
		&& ItemStack.areItemStackTagsEqual(stack, getStackInSlot(index));
	setStackInSlot(index, stack);

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

	if(index != 9 && !sameStackInSlot)
	{
		changeOutput();
		markDirty();
	}
}

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

@Override
public boolean isUseableByPlayer(EntityPlayer player)
{
	return worldObj.getTileEntity(pos) != this ? false : player.getDistanceSq(pos.getX() + 0.5D, pos.getY() + 0.5D,
		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 stack)
{
	return index != 9;
}

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

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

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

@Override
public void clear()
{
	for(int i = 0; i < getSizeInventory(); i++)
	{
		setStackInSlot(i, null);
	}
}

@Override
public void readFromNBT(NBTTagCompound compound)
{
	super.readFromNBT(compound);
	NBTTagList craftMatrix = compound.getTagList("CraftMatrix", Constants.NBT.TAG_COMPOUND);
	for(int i = 0; i < craftMatrix.tagCount(); i++)
	{
		NBTTagCompound stack = craftMatrix.getCompoundTagAt(i);
		int slot = stack.getByte("Slot") & 255;
		if(slot >= 0 && slot < 9) setStackInSlot(slot, ItemStack.loadItemStackFromNBT(stack));
	}
	NBTTagCompound result = compound.getCompoundTag("Result");
	if(result.hasNoTags())
		this.result = null;
	else this.result = ItemStack.loadItemStackFromNBT(result);
	changeOutput();
	craftTime = compound.getInteger("CraftTime");
	if(compound.hasKey("CustomName")) customName = compound.getString("CustomName");
}

@Override
public void writeToNBT(NBTTagCompound compound)
{
	super.writeToNBT(compound);
	NBTTagList craftMatrix = new NBTTagList();
	for(int i = 0; i < 9; i++)
	{
		if(getStackInSlot(i) != null)
		{
			NBTTagCompound stack = new NBTTagCompound();
			getStackInSlot(i).writeToNBT(stack);
			stack.setByte("Slot", (byte) i);
			craftMatrix.appendTag(stack);
		}
	}
	compound.setTag("CraftMatrix", craftMatrix);
	if(result != null)
	{
		NBTTagCompound result = new NBTTagCompound();
		this.result.writeToNBT(result);
		compound.setTag("Result", result);
	}
	compound.setInteger("CraftTime", craftTime);
	if(hasCustomName()) compound.setString("CustomName", customName);
}

@Override
public void update()
{
	updateOutput();
}

private void changeOutput()
{
	FarmersHeaven.LOGGER.info("Changing output");
	if(currentRecipe == null || !currentRecipe.matches(invCrafting, worldObj)) craftTime = 0;
	currentRecipe = null;
	for(Object object : CraftingManager.getInstance().getRecipeList())
	{
		IRecipe recipe = (IRecipe) object;
		if(recipe.matches(invCrafting, worldObj))
		{
			FarmersHeaven.LOGGER.info("Setting current recipe to an output of " + recipe.getRecipeOutput());
			currentRecipe = recipe;
		}
	}
	if(currentRecipe == null) FarmersHeaven.LOGGER.info("Could not find matching recipe");
}

private void updateOutput()
{
	boolean flag = currentRecipe == null;
	flag = flag || currentRecipe.getRecipeOutput() == null;
	if(result != null)
	{
		flag = flag || !ItemStack.areItemsEqual(currentRecipe.getRecipeOutput(), result);
		flag = flag || !ItemStack.areItemStackTagsEqual(currentRecipe.getRecipeOutput(), result);
		flag = flag || result.stackSize > result.getMaxStackSize() - currentRecipe.getRecipeOutput().stackSize;
	}
	if(flag)
	{
		craftTime = 0;
	}
	else
	{
		craftTime++;
		if(craftTime >= MAX_CRAFT_TIME)
		{
			FarmersHeaven.LOGGER.info("Crafting...");
			craftTime = 0;
			ItemStack recipeOutput = currentRecipe.getRecipeOutput(); // For some reason this has a stackSize of 0
			if(result == null)
				result = recipeOutput;
			else result.stackSize += recipeOutput.stackSize;
			ItemStack[] additionalOutputs = CraftingManager.getInstance().func_180303_b(invCrafting, worldObj);
			for(int i = 0; i < 9; i++)
			{
				decrStackSize(i, 1);
				if(additionalOutputs[i] != null)
				{
					if(getStackInSlot(i) == null)
					{
						setInventorySlotContents(i, additionalOutputs[i]);
					}
					else
					{
						EntityItem entity = new EntityItem(worldObj);
						entity.setLocationAndAngles(pos.getX() + 0.5, pos.getY() + 0.2, pos.getZ() + 0.5, 0, 0);
						entity.setEntityItemStack(additionalOutputs[i]);
						worldObj.spawnEntityInWorld(entity);
					}
				}
			}
		}
	}
}

@Override
public int[] getSlotsForFace(EnumFacing side)
{
	return side == EnumFacing.DOWN ? new int[] { 9 } : new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
}

@Override
public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction)
{
	return index != 9;
}

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

public void setCustomName(String customName)
{
	this.customName = customName;
}

public boolean isCrafting()
{
	return craftTime > 0;
}

public int getScaleCraftingWidth(int maxWidth)
{
	return (int) ((float) craftTime / MAX_CRAFT_TIME * maxWidth);
}
}

 

 

If you need any more of my code, feel free to ask for it. You can also ask me to do some debugging tests

 

So can you see why the recipe output stackSize is always 0? I'm probably missing something really obvious lol

Thanks in advance

catch(Exception e)

{

 

}

Yay, Pokémon exception handling, gotta catch 'em all (and then do nothing with 'em).

Posted

Okay so I've solved that problem, but I'm now getting some syncronization issues with the client and server. Here's my updated tile entity:

 

 

package com.earthcomputer.farmersheaven;

import java.lang.reflect.Field;

import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.gui.IUpdatePlayerListBox;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IChatComponent;
import net.minecraftforge.common.util.Constants;

public class TileEntityAutoCraftingTable extends TileEntity implements IUpdatePlayerListBox, ISidedInventory
{

private Container			container		= new Container() {
												@Override
												public boolean canInteractWith(EntityPlayer player)
												{
													return true;
												}

												@Override
												public void onCraftMatrixChanged(IInventory inventory)
												{
													//changeOutput();
												}
											};

private InventoryCrafting	invCrafting		= new InventoryCrafting(container, 3, 3);
private ItemStack			result;
private IRecipe				currentRecipe;
private boolean				canContinue		= true;
private int					craftTime		= 0;
public static final int		MAX_CRAFT_TIME	= 200;

private String				customName;

private static final Field	invCraftingStackList;

static
{
	try
	{
		invCraftingStackList = InventoryCrafting.class.getDeclaredField("stackList");
	}
	catch (Exception e)
	{
		throw new RuntimeException(e);
	}
	invCraftingStackList.setAccessible(true);
}

@Override
public String getName()
{
	return hasCustomName() ? customName : "container.autocrafting_table";
}

@Override
public boolean hasCustomName()
{
	return customName != null && customName.length() > 0;
}

@Override
public IChatComponent getDisplayName()
{
	return hasCustomName() ? new ChatComponentText(getName()) : new ChatComponentTranslation(getName());
}

@Override
public int getSizeInventory()
{
	return 10;
}

@Override
public ItemStack getStackInSlot(int index)
{
	return index == 9 ? result : invCrafting.getStackInSlot(index);
}

private void setStackInSlot(int index, ItemStack stack)
{
	if(index == 9)
		result = stack;
	else try
	{
		ItemStack before = getStackInSlot(index);
		((ItemStack[]) invCraftingStackList.get(invCrafting))[index] = stack;
		if(!ItemStack.areItemsEqual(before, stack) || !ItemStack.areItemStackTagsEqual(before, stack))
			changeOutput();
	}
	catch (Exception e)
	{
		throw new RuntimeException(e);
	}
}

@Override
public ItemStack decrStackSize(int index, int count)
{
	if(getStackInSlot(index) != null)
	{
		ItemStack stack;

		if(getStackInSlot(index).stackSize <= count)
		{
			stack = getStackInSlot(index);
			setStackInSlot(index, null);
			return stack;
		}
		else
		{
			stack = getStackInSlot(index).splitStack(count);

			if(getStackInSlot(index).stackSize == 0)
			{
				setStackInSlot(index, null);
			}

			return stack;
		}
	}
	else
	{
		return null;
	}
}

@Override
public ItemStack getStackInSlotOnClosing(int index)
{
	if(getStackInSlot(index) != null)
	{
		ItemStack itemstack = getStackInSlot(index);
		setStackInSlot(index, null);
		return itemstack;
	}
	else
	{
		return null;
	}
}

@Override
public void setInventorySlotContents(int index, ItemStack stack)
{
	boolean sameStackInSlot = stack != null && stack.isItemEqual(getStackInSlot(index))
		&& ItemStack.areItemStackTagsEqual(stack, getStackInSlot(index));
	setStackInSlot(index, stack);

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

	if(index != 9 && !sameStackInSlot)
	{
		changeOutput();
		markDirty();
	}
}

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

@Override
public boolean isUseableByPlayer(EntityPlayer player)
{
	return worldObj.getTileEntity(pos) != this ? false : player.getDistanceSq(pos.getX() + 0.5D, pos.getY() + 0.5D,
		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 stack)
{
	return index != 9;
}

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

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

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

@Override
public void clear()
{
	for(int i = 0; i < getSizeInventory(); i++)
	{
		setStackInSlot(i, null);
	}
}

@Override
public void readFromNBT(NBTTagCompound compound)
{
	super.readFromNBT(compound);
	NBTTagList craftMatrix = compound.getTagList("CraftMatrix", Constants.NBT.TAG_COMPOUND);
	for(int i = 0; i < craftMatrix.tagCount(); i++)
	{
		NBTTagCompound stack = craftMatrix.getCompoundTagAt(i);
		int slot = stack.getByte("Slot") & 255;
		if(slot >= 0 && slot < 9) setStackInSlot(slot, ItemStack.loadItemStackFromNBT(stack));
	}
	NBTTagCompound result = compound.getCompoundTag("Result");
	if(result.hasNoTags())
		this.result = null;
	else this.result = ItemStack.loadItemStackFromNBT(result);
	changeOutput();
	craftTime = compound.getInteger("CraftTime");
	if(compound.hasKey("CustomName")) customName = compound.getString("CustomName");
}

@Override
public void writeToNBT(NBTTagCompound compound)
{
	super.writeToNBT(compound);
	NBTTagList craftMatrix = new NBTTagList();
	for(int i = 0; i < 9; i++)
	{
		if(getStackInSlot(i) != null)
		{
			NBTTagCompound stack = new NBTTagCompound();
			getStackInSlot(i).writeToNBT(stack);
			stack.setByte("Slot", (byte) i);
			craftMatrix.appendTag(stack);
		}
	}
	compound.setTag("CraftMatrix", craftMatrix);
	if(result != null)
	{
		NBTTagCompound result = new NBTTagCompound();
		this.result.writeToNBT(result);
		compound.setTag("Result", result);
	}
	compound.setInteger("CraftTime", craftTime);
	if(hasCustomName()) compound.setString("CustomName", customName);
}

@Override
public void update()
{
	updateOutput();
}

private void changeOutput()
{
	FarmersHeaven.LOGGER.info("Changing output");
	if(currentRecipe == null || !currentRecipe.matches(invCrafting, worldObj)) craftTime = 0;
	currentRecipe = null;
	for(Object object : CraftingManager.getInstance().getRecipeList())
	{
		IRecipe recipe = (IRecipe) object;
		if(recipe.matches(invCrafting, worldObj))
		{
			FarmersHeaven.LOGGER.info("Setting current recipe to an output of " + recipe.getRecipeOutput());
			currentRecipe = recipe;
		}
	}
	if(currentRecipe == null) FarmersHeaven.LOGGER.info("Could not find matching recipe");
}

private void updateOutput()
{
	boolean flag = currentRecipe == null;
	flag = flag || currentRecipe.getRecipeOutput() == null;
	if(result != null)
	{
		flag = flag || !ItemStack.areItemsEqual(currentRecipe.getRecipeOutput(), result);
		flag = flag || !ItemStack.areItemStackTagsEqual(currentRecipe.getRecipeOutput(), result);
		flag = flag || result.stackSize > result.getMaxStackSize() - currentRecipe.getRecipeOutput().stackSize;
	}
	if(flag)
	{
		craftTime = 0;
	}
	else
	{
		craftTime++;
		if(craftTime >= MAX_CRAFT_TIME)
		{
			FarmersHeaven.LOGGER.info("Crafting...");
			craftTime = 0;
			ItemStack recipeOutput = currentRecipe.getRecipeOutput();
			if(result == null)
				result = recipeOutput.copy();
			else result.stackSize += recipeOutput.stackSize;
			ItemStack[] additionalOutputs = CraftingManager.getInstance().func_180303_b(invCrafting, worldObj);
			for(int i = 0; i < 9; i++)
			{
				decrStackSize(i, 1);
				if(additionalOutputs[i] != null)
				{
					if(getStackInSlot(i) == null)
					{
						setInventorySlotContents(i, additionalOutputs[i]);
					}
					else
					{
						EntityItem entity = new EntityItem(worldObj);
						entity.setLocationAndAngles(pos.getX() + 0.5, pos.getY() + 0.2, pos.getZ() + 0.5, 0, 0);
						entity.setEntityItemStack(additionalOutputs[i]);
						worldObj.spawnEntityInWorld(entity);
					}
				}
			}
		}
	}
}

@Override
public int[] getSlotsForFace(EnumFacing side)
{
	return side == EnumFacing.DOWN ? new int[] { 9 } : new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
}

@Override
public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction)
{
	return index != 9;
}

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

public void setCustomName(String customName)
{
	this.customName = customName;
}

public boolean isCrafting()
{
	return craftTime > 0;
}

public int getScaleCraftingWidth(int maxWidth)
{
	return (int) ((float) craftTime / MAX_CRAFT_TIME * maxWidth);
}
}

 

 

catch(Exception e)

{

 

}

Yay, Pokémon exception handling, gotta catch 'em all (and then do nothing with 'em).

Posted

The client and server try to craft the items at different times, and refresh only when I relog

catch(Exception e)

{

 

}

Yay, Pokémon exception handling, gotta catch 'em all (and then do nothing with 'em).

Posted

Oh OK, I'll play around with that, see if I can get it working. It might involve sending packets which I was hoping to avoid, but there should be a simpler way

catch(Exception e)

{

 

}

Yay, Pokémon exception handling, gotta catch 'em all (and then do nothing with 'em).

Posted

I got it working using packets - it wasn't so much the inventory slot which were the problem, it was the craftTime which wasn't synchronized (it was being displayed on the GUI client side) Thanks for your help diesieben07 :)

catch(Exception e)

{

 

}

Yay, Pokémon exception handling, gotta catch 'em all (and then do nothing with 'em).

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 tried do download the essential mod to my mod pack but i didnt work. I paly on 1.21 and it should work. I use neoforge for my modding. The weird things is my friend somehow added the mod to his modpack and many others that I somehow can´t. Is there anything i can do? 
    • Thanks, I've now installed a slightly newer version and the server is at least starting up now.
    • i have the same issue. Found 1 Create mod class dependency(ies) in createdeco-1.3.3-1.19.2.jar, which are missing from the current create-1.19.2-0.5.1.i.jar Found 11 Create mod class dependency(ies) in createaddition-fabric+1.19.2-20230723a.jar, which are missing from the current create-1.19.2-0.5.1.i.jar Detailed walkthrough of mods which rely on missing Create mod classes: Mod: createaddition-fabric+1.19.2-20230723a.jar Missing classes of create: com/simibubi/create/compat/jei/category/sequencedAssembly/JeiSequencedAssemblySubCategory com/simibubi/create/compat/recipeViewerCommon/SequencedAssemblySubCategoryType com/simibubi/create/compat/rei/CreateREI com/simibubi/create/compat/rei/EmptyBackground com/simibubi/create/compat/rei/ItemIcon com/simibubi/create/compat/rei/category/CreateRecipeCategory com/simibubi/create/compat/rei/category/WidgetUtil com/simibubi/create/compat/rei/category/animations/AnimatedBlazeBurner com/simibubi/create/compat/rei/category/animations/AnimatedKinetics com/simibubi/create/compat/rei/category/sequencedAssembly/ReiSequencedAssemblySubCategory com/simibubi/create/compat/rei/display/CreateDisplay Mod: createdeco-1.3.3-1.19.2.jar Missing classes of create: com/simibubi/create/content/kinetics/fan/SplashingRecipe
    • The crash points to moonlight lib - try other builds or make a test without this mod and the mods requiring it
    • Do you have shaders enabled? There is an issue with the mod simpleclouds - remove this mod or disable shaders, if enabled  
  • Topics

×
×
  • Create New...

Important Information

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