Jump to content

Recommended Posts

Posted (edited)

I got another tile entity, with yet another problem.. When I right click it, it does nothing, but when I click the barrel(the other tile entity I had problems with) it opens.

Gui Handler:

public class GuiHandler {
	public static GuiScreen openGui(FMLPlayMessages.OpenContainer openContainer) {
		BlockPos pos = openContainer.getAdditionalData().readBlockPos();
		EntityPlayerSP player = Minecraft.getInstance().player;
		
		//Barrel
		if(openContainer.getId().equals(new ResourceLocation(Main.modid, "barrel"))) {
			return new GuiBarrel(player.inventory, (TileEntityBarrel)Minecraft.getInstance().world.getTileEntity(pos), player);
		}
		if(openContainer.getId().equals(new ResourceLocation(Main.modid, "press"))) {
			return new GuiPress(player.inventory, (TileEntityPress)Minecraft.getInstance().world.getTileEntity(pos));
		}
		
		return null;
	}
	
	public static enum GUI {
		BARREL("moresimplestuff:barrel", new ResourceLocation(Main.modid, "textures/gui/barrel.png")),
		PRESS("moresimplestuff:press", new ResourceLocation(Main.modid, "textures/gui/press.png"));
    	
    	private ResourceLocation texture;
    	private String guiId;
    	
    	GUI(String guiId, ResourceLocation texture) {
    		this.guiId = guiId;
    		this.texture = texture;
    	}
    	
    	public String getGuiID() {
    		return guiId;
    	}
    	
    	public ResourceLocation getTexture() {
    		return texture;
    	}
	}
}

How I registered it (in my main class):

ModLoadingContext.get().registerExtensionPoint(ExtensionPoint.GUIFACTORY, () -> GuiHandler::openGui);

And how I open it (block class): 

@Override
	public boolean onBlockActivated(IBlockState state, World worldIn, BlockPos pos, EntityPlayer player, EnumHand hand,
			EnumFacing side, float hitX, float hitY, float hitZ) {
		if (worldIn.isRemote) {
			return true;
		} else {
			TileEntityPress te = (TileEntityPress)worldIn.getTileEntity(pos);
			
			if(te != null) {
				if(player instanceof EntityPlayerMP && !(player instanceof FakePlayer)) {
					EntityPlayerMP playermp = (EntityPlayerMP)player;
					
					NetworkHooks.openGui(playermp, te, buf -> buf.writeBlockPos(pos));
				}
			}
			
			return true;
		}
	}

If you need to me to show other code, just tell me

Edited by MyRedAlien43
Posted
  On 5/14/2019 at 7:57 AM, diesieben07 said:

Show your tile entity and container class.

Expand  

Tile Entity:

package beta.mod.tileentity.press;

import beta.mod.init.ItemInit;
import beta.mod.tileentity.ModTET;
import beta.mod.util.GuiHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.IInteractionObject;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;

@SuppressWarnings("unused")
public class TileEntityPress extends TileEntity implements ITickable, IInteractionObject {
	public ItemStackHandler handler = new ItemStackHandler(3);
	private int burnTime, currentBurnTime, cookTime, totalCookTime;
	private ITextComponent customName;
	
	private TileEntityPress(TileEntityType<?> type) {
		super(type);
	}
	
	public TileEntityPress() {
		this(ModTET.PRESS);
	}
	
	@Override
	public ITextComponent getName() {
		return this.hasCustomName() ? this.customName : new TextComponentTranslation("container.press");
	}
	
	@Override
	public boolean hasCustomName() {
		return this.customName != null;
	}
	
	public void setCustomName(ITextComponent customName) {
		this.customName = customName;
	}
	
	@Override
	public void read(NBTTagCompound compound) {
		super.read(compound);
		this.handler.deserializeNBT(compound.getCompound("inventory"));
		this.burnTime = compound.getInt("BurnTime");
		this.cookTime = compound.getInt("CookTime");
		this.totalCookTime = compound.getInt("TotalCookTime");
		this.currentBurnTime = compound.getInt("CurrentBurnTime");
		
		if(compound.contains("CustomName", Constants.NBT.TAG_STRING)) {
			this.customName = ITextComponent.Serializer.fromJson(compound.getString("CustomName"));
		}
	}
	
	@Override
	public NBTTagCompound write(NBTTagCompound compound) {
		super.write(compound);
		compound.setTag("inventory", this.handler.serializeNBT());
		compound.setInt("BurnTime", this.burnTime);
		compound.setInt("CookTime", this.cookTime);
		compound.setInt("TotalCookTime", this.totalCookTime);
		compound.setInt("CurrentBurnTime", this.currentBurnTime);
		if(this.hasCustomName()) {
			compound.setString("CustomName", ITextComponent.Serializer.toJson(customName));
		}
		
		return compound;
	}
	
	public boolean isPressing() {
		return this.burnTime > 0;
	}
	
	@Override
	public void tick() {
		boolean flag = this.isPressing(), flag1 = false;
		
		if(this.isPressing()) {
			this.burnTime--;
		}
		
		if(!this.world.isRemote) {
			ItemStack stack = this.handler.getStackInSlot(1);
			
			if(this.isPressing() || !stack.isEmpty() && !this.handler.getStackInSlot(0).isEmpty()) {
				if(!this.isPressing() && this.canSmelt()) {
					this.burnTime = getBurnTime(stack);
					this.currentBurnTime = this.burnTime;
					
					if(this.isPressing()) {
						flag1 = true;
						
						if(!stack.isEmpty()) {
							Item item = stack.getItem();
							stack.shrink(1);
							
							if(stack.isEmpty()) {
								ItemStack item1 = item.getContainerItem(stack);
								this.handler.setStackInSlot(1, item1);
							}
						}
					}
				}
				
				if(this.isPressing() && this.canSmelt()) {
					this.cookTime++;
					
					if(this.cookTime == this.totalCookTime) {
						this.cookTime = 0;
						this.totalCookTime = this.getCookTime(this.handler.getStackInSlot(0));
						this.smeltItem();
						flag1 = true;
					}
				} else {
					this.cookTime = 0;
				}
			} else if(!this.isPressing() && this.cookTime > 0) {
				this.cookTime = MathHelper.clamp(this.cookTime - 2, 0, this.totalCookTime);
			}
			
			if(flag != this.isPressing()) {
				flag1 = true;
				BlockPress.setState(this.isPressing(), this.world, this.pos);
			}
		}
	}

	public void dropInventoryItems(World worldIn, BlockPos pos) {
		for(int i = 0; i < this.handler.getSlots(); i++) {
			ItemStack stack = this.handler.getStackInSlot(i);
			
			if(!stack.isEmpty()) {
				InventoryHelper.spawnItemStack(worldIn, (double)pos.getX(), (double)pos.getY(), (double)pos.getZ(), stack);
			}
		}
	}
	
	public int getCookTime(ItemStack stack) {
		return 200;
	}
	
	private boolean canSmelt() {
		if(this.handler.getStackInSlot(0).isEmpty()) {
			return false;
		} else {
			ItemStack stack = PressRecipes.instance().getCookingResult(this.handler.getStackInSlot(0));
			
			if(stack.isEmpty()) {
				return false;
			} else {
				ItemStack stack1 = this.handler.getStackInSlot(2);
				
				if(stack1.isEmpty()) {
					return true;
				} else if(!stack1.isItemEqual(stack)) {
					return false;
				} else if(stack1.getCount() + stack.getCount() <= 64 && stack1.getCount() + stack.getCount() <= stack1.getMaxStackSize()) {
					return true;
				} else {
					return stack1.getCount() + stack.getCount() <= stack.getMaxStackSize();
				}
			}
		}
	}
	
	public void smeltItem() {
		if(this.canSmelt()) {
			ItemStack stack = this.handler.getStackInSlot(0), stack1 = PressRecipes.instance().getCookingResult(stack), stack2 = this.handler.getStackInSlot(2);
			
			if(stack2.isEmpty()) {
				this.handler.setStackInSlot(2, stack1.copy());
			} else if(stack2.getItem() == stack1.getItem()) {
				stack2.grow(stack1.getCount());
			}
			
			if(stack.getItem() == Blocks.WET_SPONGE.asItem() && !this.handler.getStackInSlot(1).isEmpty() && this.handler.getStackInSlot(1).getItem() == Items.BUCKET) {
				this.handler.setStackInSlot(1, new ItemStack(Items.WATER_BUCKET));
			}
			
			stack.shrink(1);
		}
	}
	
	@SuppressWarnings("unlikely-arg-type")
	public static int getBurnTime(ItemStack stack) {
		if(stack.isEmpty()) {
			return 0;
		} else {
			int burnTime = net.minecraft.tileentity.TileEntityFurnace.getBurnTimes().get(stack);
			if(burnTime >= 0) return burnTime;
			Item item = stack.getItem();
			
			if(item == ItemInit.GRAPE) {
				return 20;
			}
		}
		
		return 200;
	}
	
	public static boolean isItemFuel(ItemStack stack) {
		return getBurnTime(stack) > 0;
	}
	
	@Override
	public String getGuiID() {
		return GuiHandler.GUI.PRESS.getGuiID();
	}
	
	@Override
	public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) {
		return new ContainerPress(playerInventory, this);
	}
	
	public int getField(int id) {
		switch(id) {
		case 0:
			return this.burnTime;
		case 1:
			return this.currentBurnTime;
		case 2:
			return this.cookTime;
		case 3:
			return this.totalCookTime;
		default:
			return 0;
		}
	}
	
	public void setField(int id, int value) {
		switch(id) {
		case 0:
			this.burnTime = value;
			break;
		case 1:
			this.currentBurnTime = value;
			break;
		case 2:
			this.cookTime = value;
			break;
		case 3:
			this.totalCookTime = value;
			break;
		}
	}
	
	public int getFieldCount() {
		return 4;
	}
	
	public void clear() {
		for(int i = 0; i < this.handler.getSlots(); i++) {
			this.handler.setStackInSlot(i, ItemStack.EMPTY);
		}
	}
	
	public ItemStackHandler getInventory() {
		return this.handler;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <T> LazyOptional<T> getCapability(Capability<T> cap) {
		if(!this.removed && cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
			return LazyOptional.of(() -> (T)handler);
		} else {
			return LazyOptional.empty();
		}
	}

	@Override
	public ITextComponent getCustomName() {
		return this.hasCustomName() ? this.customName : new TextComponentTranslation("Press");
	}
}

(I made setField and getField, not from IInventory)

Container:

package beta.mod.tileentity.press;

import beta.mod.tileentity.press.slots.SlotPressFuel;
import beta.mod.tileentity.press.slots.SlotPressOutput;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IContainerListener;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.SlotItemHandler;

public class ContainerPress extends Container {
	private final TileEntityPress te;
	private int cookTime, totalCookTime, burnTime, currentBurnTime;
	
	public ContainerPress(InventoryPlayer plrInv, TileEntityPress te) {
		this.te = te;
		this.addSlot(new SlotItemHandler(te.getInventory(), 0, 56, 53));
		this.addSlot(new SlotPressFuel(te.getInventory(), 1, 56, 17));
		this.addSlot(new SlotPressOutput(plrInv.player, te.getInventory(), 2, 116, 35));
		
		for(int i = 0; i < 3; i++)
		{
			for(int j = 0; j < 9; ++j)
			{
				this.addSlot(new Slot(plrInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
			}
		}
		
		for(int k = 0; k < 9; k++)
		{
			this.addSlot(new Slot(plrInv, k, 8 + k * 18, 142));
		}
	}
	
	@Override
	public void detectAndSendChanges() {
		super.detectAndSendChanges();
		
		for(int i = 0; i < this.listeners.size(); i++) {
			IContainerListener icontainerlistener = this.listeners.get(i);

	        if (this.cookTime != this.te.getField(2))
	        {
	            icontainerlistener.sendWindowProperty(this, 2, this.te.getField(2));
	        }

	        if (this.burnTime != this.te.getField(0))
	        {
	            icontainerlistener.sendWindowProperty(this, 0, this.te.getField(0));
	        }

	        if (this.currentBurnTime != this.te.getField(1))
	        {
	            icontainerlistener.sendWindowProperty(this, 1, this.te.getField(1));
	        }

	        if (this.totalCookTime != this.te.getField(3))
	        {
	            icontainerlistener.sendWindowProperty(this, 3, this.te.getField(3));
	        }
		}
	    this.cookTime = this.te.getField(2);
	    this.burnTime = this.te.getField(0);
	    this.currentBurnTime = this.te.getField(1);
	    this.totalCookTime = this.te.getField(3);
	}
	
	@Override
	public void updateProgressBar(int id, int data) {
		this.te.setField(id, data);
	}
	
	@Override
	public boolean canInteractWith(EntityPlayer playerIn) {
		return playerIn.getDistanceSq((double)te.getPos().getX() + 0.5d, (double)te.getPos().getY() + 0.5d, (double)te.getPos().getZ() + 0.5d) <= 64.0d;
	}
	
	@Override
	public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) {
		ItemStack itemstack = ItemStack.EMPTY;
        Slot slot = this.inventorySlots.get(index);

        if (slot != null && slot.getHasStack())
        {
            ItemStack itemstack1 = slot.getStack();
            itemstack = itemstack1.copy();

            if (index == 2)
            {
                if (!this.mergeItemStack(itemstack1, 3, 39, true))
                {
                    return ItemStack.EMPTY;
                }

                slot.onSlotChange(itemstack1, itemstack);
            }
            else if (index != 1 && index != 0)
            {
                if (!PressRecipes.instance().getCookingResult(itemstack1).isEmpty())
                {
                    if (!this.mergeItemStack(itemstack1, 0, 1, false))
                    {
                        return ItemStack.EMPTY;
                    }
                }
                else if (TileEntityPress.isItemFuel(itemstack1))
                {
                    if (!this.mergeItemStack(itemstack1, 1, 2, false))
                    {
                        return ItemStack.EMPTY;
                    }
                }
                else if (index >= 3 && index < 30)
                {
                    if (!this.mergeItemStack(itemstack1, 30, 39, false))
                    {
                        return ItemStack.EMPTY;
                    }
                }
                else if (index >= 30 && index < 39 && !this.mergeItemStack(itemstack1, 3, 30, false))
                {
                    return ItemStack.EMPTY;
                }
            }
            else if (!this.mergeItemStack(itemstack1, 3, 39, false))
            {
                return ItemStack.EMPTY;
            }

            if (itemstack1.isEmpty())
            {
                slot.putStack(ItemStack.EMPTY);
            }
            else
            {
                slot.onSlotChanged();
            }

            if (itemstack1.getCount() == itemstack.getCount())
            {
                return ItemStack.EMPTY;
            }

            slot.onTake(playerIn, itemstack1);
        }

        return itemstack;
	}
}

 

Posted
  On 5/14/2019 at 3:36 PM, diesieben07 said:

Okay. If the first line is not triggered, obviously the other two can't trigger as well.

Now, try to use some logical reasoning. You have various if statements in onBlockActivated, so if it's not getting to openGui some condition before that is not true. Use the debugger to find out what is not true any why.

Expand  

I put a break point on the line:

if(worldIn.isRemote) {
	return true; //This line
}

And it triggered, and not the other one I put on the line:

TileEntityPress te = (TileEntityPress)worldIn.getTileEntity(pos);

that is on the else side of the if above

Posted

I propose adding a "3. LEARN TO USE YOUR IDE's DEBUGGER!" entry under General Issues in your Common Issues / Recommendations post.

@MyRedAlien43seriously, the debugger is a lifesaver.  Modding without it is like trying to run with your shoelaces tied together.

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 removed yetanotherchance booster and now it says Invalid player identity
    • Cracked Launchers are not supported
    • After some time minecraft crashes with an error. Here is the log https://drive.google.com/file/d/1o-2R6KZaC8sxjtLaw5qj0A-GkG_SuoB5/view?usp=sharing
    • The specific issue is that items in my inventory wont stack properly. For instance, if I punch a tree down to collect wood, the first block I collected goes to my hand. So when I punch the second block of wood to collect it, it drops, but instead of stacking with the piece of wood already in my hand, it goes to the second slot in my hotbar instead. Another example is that I'll get some dirt, and then when I'm placing it down later I'll accidentally place a block where I don't want it. When I harvest it again, it doesn't go back to the stack that it came from on my hotbar, where it should have gone, but rather into my inventory. That means that if my inventory is full, then the dirt wont be picked up even though there should be space available in the stack I'm holding. The forge version I'm using is 40.3.0, for java 1.18.2. I'll leave the mods I'm using here, and I'd appreciate it if anybody can point me in the right direction in regards to figuring out how to fix this. I forgot to mention that I think it only happens on my server but I&#39;m not entirely sure. PLEASE HELP ME! LIST OF THE MODS. aaa_particles Adorn AdvancementPlaques AI-Improvements AkashicTome alexsdelight alexsmobs AmbientSounds amwplushies Animalistic another_furniture AppleSkin Aquaculture aquamirae architectury artifacts Atlas-Lib AutoLeveling AutoRegLib auudio balm betterfpsdist biggerstacks biomancy BiomesOPlenty blockui blueprint Bookshelf born_in_chaos Botania braincell BrassAmberBattleTowers brutalbosses camera CasinoCraft cfm (MrCrayfish’s Furniture Mod) chat_heads citadel cloth-config Clumps CMDCam CNB cobweb collective comforts convenientcurioscontainer cookingforblockheads coroutil CosmeticArmorReworked CozyHome CrabbersDelight crashexploitfixer crashutilities Create CreativeCore creeperoverhaul cristellib crittersandcompanions Croptopia CroptopiaAdditions CullLessLeaves curios curiouslanterns curiouslights Curses' Naturals CustomNPCs CyclopsCore dannys_expansion decocraft Decoration Mod DecorationDelightRefurbished Decorative Blocks Disenchanting DistantHorizons doubledoors DramaticDoors drippyloadingscreen durabilitytooltip dynamic-fps dynamiclights DynamicTrees DynamicTreesBOP DynamicTreesPlus Easy Dungeons EasyAnvils EasyMagic easy_npc eatinganimation ecologics effective_fg elevatorid embeddium emotecraft enchantlimiter EnchantmentDescriptions EnderMail engineersdecor entityculling entity_model_features entity_texture_features epicfight EvilCraft exlinefurniture expandability explosiveenhancement factory-blocks fairylights fancymenu FancyVideo FarmersDelight fast-ip-ping FastSuite ferritecore finsandtails FixMySpawnR Forge Middle Ages fossil FpsReducer2 furnish GamingDeco geckolib goblintraders goldenfood goodall H.e.b habitat harvest-with-ease hexerei hole_filler huge-structure-blocks HunterIllager iammusicplayer Iceberg illuminations immersive_paintings incubation infinitybuttons inventoryhud InventoryProfilesNext invocore ItemBorders itemzoom Jade jei (Just Enough Items) JetAndEliasArmors journeymap JRFTL justzoom kiwiboi Kobolds konkrete kotlinforforge lazydfu LegendaryTooltips libIPN lightspeed lmft lodestone LongNbtKiller LuckPerms Lucky77 MagmaMonsters malum ManyIdeasCore ManyIdeasDoors marbledsarsenal marg mcw-furniture mcw-lights mcw-paths mcw-stairs mcw-trapdoors mcw-windows meetyourfight melody memoryleakfix Mimic minecraft-comes-alive MineTraps minibosses MmmMmmMmmMmm MOAdecor (ART, BATH, COOKERY, GARDEN, HOLIDAYS, LIGHTS, SCIENCE) MobCatcher modonomicon mods_optimizer morehitboxes mowziesmobs MutantMonsters mysticalworld naturalist NaturesAura neapolitan NekosEnchantedBooks neoncraft2 nerb nifty NightConfigFixes nightlights nocube's_villagers_sell_animals NoSeeNoTick notenoughanimations obscure_api oculus oresabovediamonds otyacraftengine Paraglider Patchouli physics-mod Pillagers Gun PizzaCraft placeableitems Placebo player-animation-lib pneumaticcraft-repressurized polymorph PrettyPipes Prism projectbrazier Psychadelic-Chemistry PuzzlesLib realmrpg_imps_and_demons RecipesLibrary reeves-furniture RegionsUnexplored restrictedportals revive-me Scary_Mobs_And_Bosses selene shetiphiancore ShoulderSurfing smoothboot
    • Hi everyone, I'm currently developing a Forge 1.21 mod for Minecraft and I want to display a custom HUD overlay for a minigame. My goal: When the game starts, all players should see an item/block icon (from the base game, not a custom texture) plus its name/text in the HUD – similar to how the bossbar overlay works. The HUD should appear centered above the hotbar (or at a similar prominent spot), and update dynamically (icon and name change as the target item changes). What I've tried: I looked at many online tutorials and several GitHub repos (e.g. SeasonHUD, MiniHUD), but most of them use NeoForge or Forge versions <1.20 that provide the IGuiOverlay API (e.g. implements IGuiOverlay, RegisterGuiOverlaysEvent). In Forge 1.21, it seems that neither IGuiOverlay nor RegisterGuiOverlaysEvent exist anymore – at least, I can't import them and they are missing from the docs and code completion. I tried using RenderLevelStageEvent as a workaround but it is probably not intended for custom HUDs. I am not using NeoForge, and switching the project to NeoForge is currently not an option for me. I tried to look at the original minecraft source code to see how elements like hearts, hotbar etc are drawn on the screen but I am too new to Minecraft modding to understand. What I'm looking for: What is the correct way to add a custom HUD element (icon + text) in Forge 1.21, given that the previous overlay API is missing? Is there a new recommended event, callback, or method in Forge 1.21 for custom HUD overlays, or is everyone just using a workaround? Is there a minimal open-source example repo for Forge 1.21 that demonstrates a working HUD overlay without relying on NeoForge or deprecated Forge APIs? My ideal solution: Centered HUD element with an in-game item/block icon (from the base game's assets, e.g. a diamond or any ItemStack / Item) and its name as text, with a transparent background rectangle. It should be visible to the players when the mini game is running. Easy to update the item (e.g. static variable or other method), so it can change dynamically during the game. Any help, code snippets, or up-to-date references would be really appreciated! If this is simply not possible right now in Forge 1.21, it would also help to know that for sure. Thank you very much in advance!
  • Topics

×
×
  • Create New...

Important Information

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