Jump to content

Gui to Edit Tile Entity Data


Reika

Recommended Posts

I am aware this has been asked before, but no thread I have found has had a solution that worked for me.

What I need to do is simple and probably will look excessively newbie-like to those of you experienced with the 1.3+ integrated server.

 

I have a GUI with several custom buttons, and I want clicking these buttons to be able to update the state of variables inside the Tile Entity. I started off with old 1.2.5-style code, and got the "client side effect but no server update" glitch; switching to using the packet handlers in the forge tutorials now leaves the changes not happening at all.

 

The relevant sections of my code:

Tile Entity:

    @Override
    public Packet getDescriptionPacket()
    {
     NBTTagCompound var1 = new NBTTagCompound();
     this.writeToNBT(var1);
     return new Packet132TileEntityData(this.xCoord, this.yCoord, this.zCoord, 2, var1);
    }
            
    @Override
    public void onDataPacket(INetworkManager netManager, Packet132TileEntityData packet)
    {
     readFromNBT(packet.customParam1);
    }
    
@Override
public void handlePacketData(INetworkManager network, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream)
{
	try {
		this.mode = dataStream.readInt();
	} catch (Exception e)
	{
		System.out.println("[RotaryCraft] Error while handling tile entity packet.");
		e.printStackTrace();
	}
}

 

Gui:

    public GuiBorer(InventoryPlayer par1InventoryPlayer, TileEntityBorer par2TileEntityBorer, EntityPlayer par5player)
    {
        super(new ContainerBorer(par1InventoryPlayer, par2TileEntityBorer));
        borer = par2TileEntityBorer;
    	this.ySize = 215;
    	dropstatus = "Drops On";
    	player = par5player;
    	drops = borer.drops;
    	mode = borer.mode;
    }
    
    @Override
    public void initGui() {
        int j = (width - xSize) / 2;
        int k = (height - ySize) / 2;
            this.controlList.add(new GuiButton(0, j+8, -1+k+32, 72, 20, "1x1 Square"));
            this.controlList.add(new GuiButton(1, j+8, -1+k+52, 72, 20, "1x2 Hallway"));
            this.controlList.add(new GuiButton(2, j+8, -1+k+72, 72, 20, "2x2 Square"));
            this.controlList.add(new GuiButton(3, j+8, -1+k+92, 72, 20, "3x3 Square"));
            this.controlList.add(new GuiButton(4, j+8, -1+k+112, 72, 20, "5x5 Circle"));
            this.controlList.add(new GuiButton(5, j+8, -1+k+132, 72, 20, "7x4 Archway"));
            this.controlList.add(new GuiButton(6, j+8, -1+k+152, 72, 20, "4x4 Tunnel"));
            
            if (drops)
            	this.controlList.add(new GuiButton(7, j+95, -1+k+32, 72, 20, "Drops On"));
            else
            	this.controlList.add(new GuiButton(7, j+95, -1+k+32, 72, 20, "Drops Off"));
    }
    
    public void toggleDrops() {
    	if (drops) {
    		dropstatus = "Drops Off";
    		drops = false;
    	}
    	else {
    		dropstatus = "Drops On";
    		drops = true;
    	}
    	
    	this.sendPacket(1);
    }
    
    public void updateMode(int mode) {
    	borer.mode = (byte)mode;
    }
    
    /**
     * Returns true if this GUI should pause the game when it is displayed in single-player
     */
    public boolean doesGuiPauseGame()
    {
        return true;
    }

    @Override
    public void actionPerformed(GuiButton button) {
            if (button.id == 7) {
            	this.toggleDrops();
            }
            if (button.id < 7) {
            	//this.updateMode(button.id);
            	mode = button.id;
            }
            this.sendPacket(2);
            this.refreshScreen();
            
    }
    
    public void sendPacket(int a) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(;
        DataOutputStream outputStream = new DataOutputStream(bos);
        try {
        	if (a == 1)
        		outputStream.writeBoolean(drops);
        	if (a == 2)
        		outputStream.writeInt(mode);
        } catch (Exception ex) {
                ex.printStackTrace();
        }
       
        Packet250CustomPayload packet = new Packet250CustomPayload();
        packet.channel = "GenericRandom";
        packet.data = bos.toByteArray();
        packet.length = bos.size();
       
        Side side = FMLCommonHandler.instance().getEffectiveSide();
        if (side == Side.SERVER) {
                // We are on the server side.
                EntityPlayerMP player2 = (EntityPlayerMP) player;
        } else if (side == Side.CLIENT) {
                // We are on the client side.
                EntityClientPlayerMP player2 = (EntityClientPlayerMP) player;
                this.mc.getSendQueue().addToSendQueue(packet);
        } else {
                // We are on the Bukkit server.
        }
    }

 

Container:

public class ContainerBorer extends Container
{
    private TileEntityBorer borer;

    public ContainerBorer(InventoryPlayer par1InventoryPlayer, TileEntityBorer par2TileEntityBorer)
    {
        borer = par2TileEntityBorer;
        int posX = borer.xCoord;
        int posY = borer.yCoord;
        int posZ = borer.zCoord;
    }

    public boolean canInteractWith(EntityPlayer par1EntityPlayer)
    {
        return borer.isUseableByPlayer(par1EntityPlayer);
    }
}

 

Packet Handler:

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;

import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet250CustomPayload;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.Player;


public class ClientPacketHandler implements IPacketHandler {

    @Override
    public void onPacketData(INetworkManager manager, Packet250CustomPayload payload, Player player) {
        DataInputStream data = new DataInputStream(new ByteArrayInputStream(payload.data));
    }
}

 

Excerpt from main mod class:

@Mod( modid = "RotaryCraft", name="RotaryCraft", version="beta v0.1")
@NetworkMod(clientSideRequired=true, serverSideRequired=false,
channels={"GenericRandom"}, packetHandler = PacketHandler.class)

Link to comment
Share on other sites

Everything but block was in the OP, but here is my block code:

public BlockBorer(int blockID, int textureID) {
	super(blockID, textureID, Material.iron);
	setHardness(4F);
	setResistance(10F);
	setLightValue(0F);
	setStepSound(soundMetalFootstep);
	this.requiresSelfNotify[this.blockID] = true;	
	this.blockIndexInTexture = 57;
	setCreativeTab(mod_RotaryCraft.tabRotary);
}

public void addCreativeItems(ArrayList list)
{
        list.add(new ItemStack(this));
}

    /**
     * Returns the TileEntity used by this block.
     */
    public TileEntity createNewTileEntity(World world)
    {
        return new TileEntityBorer();
    }

    public int idDropped(int par1, Random par2Random, int par3)
    {
        return this.blockID;
    }
    
    public int damageDropped(int par1)
    {
        return 0;
    }
    
    public int quantityDropped(Random par1Random)
    {
        return 1;
    }
    
    /**
     * Called upon block activation (left or right click on the block.). The three integers represent x,y,z of the
     * block.
     */
    public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer ep, int par6, float par7, float par8, float par9)
    {
        if (world.isRemote)
        {
            return true;
        }

        TileEntityBorer borer = (TileEntityBorer)world.getBlockTileEntity(x, y, z);

        if (borer != null)
        {
        	ep.openGui(mod_RotaryCraft.instance, 9, world, x, y, z);
        	//ModLoader.openGUI(ep, new GuiBorer());
        }

        return true;
    }
public void onBlockPlacedBy(World par1World, int par2, int par3, int par4, EntityLiving par5EntityLiving)		//Directional code
    {
        int i = MathHelper.floor_double((double)((par5EntityLiving.rotationYaw * 4F) / 360F) + 0.5D);
        while (i > 3)
        	i -= 4;
        while (i < 0)
        	i += 4;

        switch (i) {
        case 0:
            par1World.setBlockMetadataWithNotify(par2, par3, par4, 2);
        break;
        case 1:
            par1World.setBlockMetadataWithNotify(par2, par3, par4, 1);
        break;
        case 2:
            par1World.setBlockMetadataWithNotify(par2, par3, par4, 3);
        break; 
        case 3:
            par1World.setBlockMetadataWithNotify(par2, par3, par4, 0);
        break;
        }            
       this.metadata = par1World.getBlockMetadata(par2, par3, par4);
    }
@Override
public String getTextureFile(){
	return "/Reika/RotaryCraft/textures.png"; //return the block texture where the block texture is saved in
}

Link to comment
Share on other sites

Your problem is the packet handler class.

first of all you named you class ClientPacketHandler but in your networkMod annotation you put PacketHandler.class.

second you didnt put any code in your packet handler to actually handle the packet.

the packet reaches the server but the server doesnt know what to do with it so ignores it.

there is an excellent packet hadling tutorial on the forge wiki.

http://www.minecraftforge.net/wiki/Packet_Handling

i would advice to follow this tutorial and if you got any questions left ask them  ;)

Link to comment
Share on other sites

Your problem is the packet handler class.

first of all you named you class ClientPacketHandler but in your networkMod annotation you put PacketHandler.class.

second you didnt put any code in your packet handler to actually handle the packet.

the packet reaches the server but the server doesnt know what to do with it so ignores it.

there is an excellent packet hadling tutorial on the forge wiki.

http://www.minecraftforge.net/wiki/Packet_Handling

i would advice to follow this tutorial and if you got any questions left ask them  ;)

It works now, but given that I was working from that tutorial - my PacketHandler is a copy-and-paste of its code - I question its use if it caused this much headache.

Of course, in hindsight one remembers one of the opening lines of the tutorial, which says the tutorial will not actually show how to use the packets usefully...

 

 

Now, I am left with one other, smaller, glitch. My button toggles the state of a variable in the Tile Entity, and should update the GUI to match (switch a variable inside the Gui Class which controls a string inside a button constructor). The Tile Entity updates and behaves correctly, but the GUI must be closed and reopened, manually, to change...why? (Even more interesting: before I set it to set the GUI class variable to be equal to the one in the Tile Entity, it would only update on world reload (save/reenter).)

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.



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • As the title say, game suddenly crushed during the loading. I got this error message The game crashed whilst rendering overlay Error: java.lang.RuntimeException: null   And Here's the link of crash log bit.ly/3IcVUQG
    • Do these mods have incompatibles: Dynamic View[Forge] (by someaddon) Server Performance - Smooth Chunk Save[Forge/Fabric] (by someaddon) EdivadLib (by 3divad99) Krypton Reforged (by Anthxny) AttributeFix (by DarkhaxDev) Create Stuff & Additions (by Furti_Two) Cristel Lib (by Cristelknight) Resourceful Config (by ThatGravyBoat) Applied Cooking (by ItsSebastrn) Thermal Cultivation (by TeamCoFH) SuperMartijn642's Config Lib (by SuperMartijn642) Create: Bells & Whistles (by sudolev) Thermal Integration (by TeamCoFH) SebastrnLib (by ItsSebastrn) Farmer's Delight (by vectorwing) Right Click, Get Crops (by TeamCoFH) Observable (by tasgon) FPS optimizer (by The_TCT) Dungeons and Taverns (by Nova_Wostra) Explorify – Dungeons & Structures (by bebebea_loste) Fast Leaf Decay (by olafskiii) Create: Vintage Improvements (by Negodya1) Sophisticated Backpacks (by P3pp3rF1y) SuperMartijn642's Core Lib (by SuperMartijn642) Create Crafts & Additions (by MRHminer) Structory (by botanydev) Oculus (by Asek3) Tectonic (by Apollo) Embeddium (Rubidium) Extra (by dimadencep) Athena (by CodexAdrian) Jade 🔍 (by Snownee) Mekanism Tools (by bradyaidanc) Carry On (by Tschipp) Create: Sweets & Treats (by AstralButOnCurseForge) Extreme Reactors Create Compat (by ZeroNoRyouki) AI Improvements (by QueenOfMissiles) AE2 QoL Recipes (by Christofmeg) Create: ComputerCraft (CC: Tweaked) (by EndRage) Create Enchantment Industry (by DragonsPlus) Macaw's Fences and Walls (by sketch_macaw) Better Villages - Forge (by jtl_elisa) Puzzles Lib [Forge & Fabric] (by Fuzs) Mekanism (by bradyaidanc) Create Recycle Everything (by nocubeyt) Searchables (by Jaredlll08) Immersive Paintings [Fabric/Forge] (by Conczin) Create Deco (by talrey) Thermal Foundation (by TeamCoFH) Controlling (by Jaredlll08) Kotlin for Forge (by thedarkcolour) Lithostitched (by Apollo) Let Me Despawn (by frikinjay) MCEF (Minecraft Chromium Embedded Framework) (by ds58) FPS Boost (by The_TCT) Ad Astra (by AlexNijjar) TerraBlender (Forge) (by TheAdubbz) Falling Leaves (Forge) (by Cheaterpaul) CC:C Bridge (by Sammy_echt) Xaero's Minimap (by xaero96) CoFH Core (by TeamCoFH) Create: Applied Kinetics (by Forsteri123) AE Additions - ExtraCells2 Fork (by MasterYodAT9G) Just Enough Items (JEI) (by mezz) Biomes O' Plenty (by Forstride) Curios API (Forge/NeoForge) (by TheIllusiveC4) AE2 Network Analyser (by GlodBlock) Resourceful Lib (by ThatGravyBoat) ChoiceTheorem's Overhauled Village (by ChoiceTheorem) Clockwork: Create x Valkyrien Skies (by triode_) Architectury API (Fabric/Forge/NeoForge) (by shedaniel) Canary (by AbdElAziz333) Structure Essentials[Forge/Fabric] (by someaddon) Library Ferret - Forge (by jtl_elisa) Create Confectionery (by Furti_Two) Leaky - Farm leak detection[Forge/Fabric] (by someaddon) Game Menu Mod Option [Forge] (by morimori0317) Macaw's Bridges (by sketch_macaw) FramedBlocks (by XFactHD) Cherished Worlds (Fabric/Forge/NeoForge/Quilt) (by TheIllusiveC4) Entangled (by SuperMartijn642) Refined Storage: Requestify (by Buuz135) ME Requester (by Relentless) Inventory Sorter (by cpw) Xaero's World Map (by xaero96) William Wythers' Expanded Ecosphere (by Cristelknight) Cloth Config API (Fabric/Forge/NeoForge) (by shedaniel) FTB Library (Forge) (by FTB) Cupboard (by someaddon) Thermal Dynamics (by TeamCoFH) Patchouli (by Vazkii) Entity Culling Fabric/Forge (by tr7zw) Chipped (by terrariumearth) FTB XMod Compat (by FTB) FerriteCore ((Neo)Forge) (by malte0811) Extra Disks (by MelanX) Nature's Compass (by Chaosyr) Thermal Locomotion (by TeamCoFH) TexTrue's Embeddium Options (by TexTrue) Traveler's Backpack (by Tiviacz1337) Geophilic – Vanilla Biome Overhauls (by bebebea_loste) Create: Power Loader (by Lysine) Polymorph (Fabric/Forge/Quilt) (by TheIllusiveC4) Enlightend (by lixir) Create Central Kitchen (by DragonsPlus) Energy Meter (by Relentless) Botarium (by CodexAdrian) FTB Teams (Forge) (by FTB) Storage Drawers (by Texelsaur) Create: Extended Cogwheels (by Rabbitminers) Embeddium/Rubidium Dynamic Lights (by Anthxny) Biome Makeover (Forge) (by Lemonszz) Create Guardian Beam Defense (by ibarnstormer_) Create: The Factory Must Grow (by Dr_Mango_Tea) Create Chunkloading (by embeddedt) Balm (Forge Edition) (by BlayTheNinth) Glodium (by GlodBlock) Thermal Expansion (by TeamCoFH) Chunk-Pregenerator (by Speiger) Advanced Peripherals (by srrendi) Create: Garnished (by DakotaPrideModding) Tidal Towns (by joshieman) Easy Magic [Forge & Fabric] (by Fuzs) Extreme Reactors (by ZeroNoRyouki) Applied Energistics 2 Wireless Terminals (by Mari_023) Redstone Arsenal (by TeamCoFH) ExtraStorage (by 3divad99) Thermal Innovation (by TeamCoFH) Collective (by Serilum) Wizard's Reborn (by MaxBogomol) GraveStone Mod (by henkelmax) Mekanism Additions (by bradyaidanc) Create: New Age (by nilBlade) Refined Storage (by raoulvdberge) Embeddium/Rubidium Extras (by Anthxny) ZeroCore 2 (by ZeroNoRyouki) Mekanism Generators (by bradyaidanc) WebDisplays (by ds58) Clumps (by Jaredlll08) Vein Mining (Fabric/Forge/Quilt) (by TheIllusiveC4) Villager Names (by Serilum) Create Slice & Dice (by possible_triangle) Embeddium (by embeddedt) Create: Steam 'n' Rails (by mattentosh) Get It Together, Drops! (by bl4ckscor3) Sophisticated Core (by P3pp3rF1y) Supplementaries (by MehVahdJukaar) Jade Addons (Forge) (by Snownee) Create: Design n' Decor (by MilkyFur) Construction Wand (by ThetaDev) Create: Diesel Generators (by george8188262) Create : Misc & Things (by to0pa_fr) Valkyrien Skies (Forge/Fabric) (by triode_) Refined Storage Addons (by raoulvdberge) FTB Chunks (Forge) (by FTB) FTB Ranks (Forge) (by FTB) Moonlight Lib (by MehVahdJukaar) CC: Tweaked (by SquidDev) Waystones (by BlayTheNinth) Applied Energistics 2 (by thetechnici4n) Trowels fork (by Luciano_cz) Cooking for Blockheads (by BlayTheNinth) Create (by simibubi) Towns and Towers (by Biban_Auriu)
    • Hi, you guys are probably all tired of having to deal with the same topic everytimes. I want to play mods, but forge doesn't want me to. And after days of videos and forum, i have no choices to ask before giving up.. The classic Error code 1 ( here's my debug.log : https://paste.ee/p/0WMSP). I tryed everything. The Forge version fit the mod version. I have java jdk 17 and the path to java is set. My mods folder is empty. My Minecraft luncher path has been changed. Java, Minecraft and Forged has been reinstalled 3 times. I tryed with the curseforge luncher. The only thing i didn't do, and I think it might be the problem, is updating my graphic card drivers. For the only reason that my computer is an Ace Magician ( Tiny pc) that don't have a graphic card. But then I went with Fabric. And it works just fine.  Anyway I can't find anything so thank you for your help. Sorry for my english if there's any mistake. Razziel.  
    • I am trying to make my own modpack and at the moment it crashes before I can get to the main menu. I have been trying to google and figure it out myself but would really appreciate some help. I've been using CurseForge to install mod and think I've gotten all the dependencies but I'm not 100% sure. I hope I got the paste.ee thing right Thanks in advance! https://paste.ee/p/NXdSO
    • We need a link to your debug.log on paste.ee, as explained in the FAQ
  • Topics

×
×
  • Create New...

Important Information

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