Jump to content

[Solved] Why is this value desyncronized? [1.6.4]


larsgerrits

Recommended Posts

Hello, i got another problem for you now. I have a value that's getting updated on the client side, but not on the server side. The way i update the code is via a GUI, when a click a button it's incrementing or decrementing a value and setting it to a TileEntity. In my container class i have some debug code:

System.out.println((tileentity.worldObj.isRemote ? "Client" : "Server") + " : " + tileentity.getPage());

That prints this in the console:

2014-02-24 17:00:47 [iNFO] [sTDOUT] Server : 0
2014-02-24 17:00:47 [iNFO] [sTDOUT] Client : 0

And if i increment the value using a button, this is getting printed in the console:

2014-02-24 17:07:41 [iNFO] [sTDOUT] Server : 0
2014-02-24 17:07:42 [iNFO] [sTDOUT] Client :1

As you see the value is getting updated client-side, but not on the server side. I added this code to my TileEntity class:

public Packet getDescriptionPacket()
{
	NBTTagCompound tag = new NBTTagCompound();
	this.writeToNBT(tag);
	return new Packet132TileEntityData(this.xCoord, this.yCoord, this.zCoord, 1, tag);
}

public void onDataPacket(INetworkManager networkManager, Packet132TileEntityData packet)
{
	this.readFromNBT(packet.data);
}

But that doesn't seem to work. I have registered my TileEntity class. Does anyone know how to correctly syncronize that value?

 

Code:

[spoiler=TileEntityCustomizableBlock]

package larsg310.mods.customization.tileentity;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet132TileEntityData;
import net.minecraft.tileentity.TileEntity;

public class TileEntityCustomizableBlock extends TileEntity implements ISidedInventory
{
private ItemStack[] inventory = new ItemStack[2];

private float minX = 0;
private float maxX = 1;

private int page = 0;

public float getMinX()
{
	return minX;
}

public void setMinX(float minX)
{
	this.minX = minX;
}

public float getMaxX()
{
	return maxX;
}

public void setMaxX(float maxX)
{
	this.maxX = maxX;
}

public int getPage()
{
	return page;
}

public void setPage(int page)
{
	this.page = page;
}

public Packet getDescriptionPacket()
{
	NBTTagCompound tag = new NBTTagCompound();
	this.writeToNBT(tag);
	return new Packet132TileEntityData(this.xCoord, this.yCoord, this.zCoord, 1, tag);
}

public void onDataPacket(INetworkManager networkManager, Packet132TileEntityData packet)
{
	this.readFromNBT(packet.data);
}

public void writeToNBT(NBTTagCompound tag)
{
	super.writeToNBT(tag);
	tag.setInteger("Page", page);
	tag.setFloat("minX", minX);
	tag.setFloat("maxX", maxX);
}

public void readFromNBT(NBTTagCompound tag)
{
	page = tag.getInteger("Page");
	minX = tag.getFloat("minX");
	maxX = tag.getFloat("maxX");
}

public int getSizeInventory()
{
	return inventory.length;
}

public ItemStack getStackInSlot(int slot)
{
	return inventory[slot];
}

public ItemStack decrStackSize(int slot, int amount)
{
	if (this.inventory[slot] != null)
	{
		ItemStack itemstack;

		if (this.inventory[slot].stackSize <= amount)
		{
			itemstack = this.inventory[slot];
			this.inventory[slot] = null;
			return itemstack;
		}
		else
		{
			itemstack = this.inventory[slot].splitStack(amount);

			if (this.inventory[slot].stackSize == 0)
			{
				this.inventory[slot] = null;
			}

			return itemstack;
		}
	}
	else
	{
		return null;
	}
}

public ItemStack getStackInSlotOnClosing(int slot)
{
	if (this.inventory[slot] != null)
	{
		ItemStack itemstack = this.inventory[slot];
		this.inventory[slot] = null;
		return itemstack;
	}
	else
	{
		return null;
	}
}

public void setInventorySlotContents(int slot, ItemStack itemstack)
{
	this.inventory[slot] = itemstack;

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

public String getInvName()
{
	return "container.customizableBlock";
}

public boolean isInvNameLocalized()
{
	return false;
}

public int getInventoryStackLimit()
{
	return 1;
}

public boolean isUseableByPlayer(EntityPlayer entityplayer)
{
	return this.worldObj.getBlockTileEntity(this.xCoord, this.yCoord, this.zCoord) != this ? false : entityplayer.getDistanceSq((double) this.xCoord + 0.5D, (double) this.yCoord + 0.5D, (double) this.zCoord + 0.5D) <= 64.0D;
}

public void openChest()
{

}

public void closeChest()
{

}

public boolean isItemValidForSlot(int slot, ItemStack itemstack)
{
	return true;
}

public int[] getAccessibleSlotsFromSide(int var1)
{
	return null;
}

public boolean canInsertItem(int i, ItemStack itemstack, int j)
{
	return false;
}

public boolean canExtractItem(int i, ItemStack itemstack, int j)
{
	return false;
}
}

 

[spoiler=ContainerCustomizableBlock]

package larsg310.mods.customization.inventory;

import larsg310.mods.customization.tileentity.TileEntityCustomizableBlock;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;

public class ContainerCustomizableBlock extends Container
{
private TileEntityCustomizableBlock tileentity;
private InventoryPlayer inventory;

private Slot[] slots;

public ContainerCustomizableBlock(InventoryPlayer inventory, TileEntityCustomizableBlock tileentity)
{
	this.tileentity = tileentity;
	this.inventory = inventory;

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

	for (int i = 0; i < 9; ++i)
	{
		this.addSlotToContainer(new Slot(inventory, i, 8 + i * 18, 142 + 80));
	}
	slots = new Slot[]{new Slot(tileentity, 0, Integer.MIN_VALUE, 20), new Slot(tileentity, 1, Integer.MIN_VALUE, 20)};
	this.addSlotToContainer(slots[0]);
	this.addSlotToContainer(slots[1]);
	System.out.println((tileentity.worldObj.isRemote ? "Client" : "Server") + " : " + tileentity.getPage());
	this.drawSlotsBasedOnPage();
}

public boolean canInteractWith(EntityPlayer entityplayer)
{
	return this.tileentity.isUseableByPlayer(entityplayer);
}

public void detectAndSendChanges()
{
	super.detectAndSendChanges();
	drawSlotsBasedOnPage();
}

private void drawSlotsBasedOnPage()
{
	for(Slot slot : slots)
	{
		slot.xDisplayPosition = Integer.MIN_VALUE;
	}
	switch (tileentity.getPage())
	{
		case 0:
			slots[0].xDisplayPosition = 100;
			break;
		case 1:
			slots[1].xDisplayPosition = 118;
			break;
	}
}
public ItemStack transferStackInSlot(EntityPlayer player, int slot)
{
	return null;
}
}

 

[spoiler=GuiCustomizableBlock]

package larsg310.mods.customization.gui;

import larsg310.mods.customization.inventory.ContainerCustomizableBlock;
import larsg310.mods.customization.lib.Reference;
import larsg310.mods.customization.tileentity.TileEntityCustomizableBlock;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;

public class GuiCustomizableBlock extends GuiContainer
{
private int page;
private int maxPages = 1;

private TileEntityCustomizableBlock tileentity;
ResourceLocation texture = new ResourceLocation(Reference.MOD_ID, "textures/gui/customizableBlock.png");

public GuiCustomizableBlock(InventoryPlayer inventory, TileEntityCustomizableBlock tileentity)
{
	super(new ContainerCustomizableBlock(inventory, tileentity));
	this.tileentity = tileentity;
	this.page = tileentity.getPage();
	this.ySize = 246;
}

@Override
protected void drawGuiContainerForegroundLayer(int x, int y)
{
	fontRenderer.drawString(StatCollector.translateToLocal("container.customizableBlock"), 8, 6, 4210752);

	String pageString = "Page: " + page + " / " + maxPages;
	fontRenderer.drawString(pageString, xSize / 2 - ((pageString.length() / 2) * 6), 123, 4210752);
}

@Override
protected void drawGuiContainerBackgroundLayer(float f, int x, int y)
{
	this.mc.getTextureManager().bindTexture(texture);
	int x1 = (width - xSize) / 2;
	int y1 = (height - ySize) / 2;
	this.drawTexturedModalRect(x1, y1, 0, 0, xSize, ySize);
}

@SuppressWarnings("unchecked")
public void initGui()
{
	super.initGui();

	this.buttonList.clear();
	this.buttonList.add(new GuiButton(0, (width - xSize) / 2 + 7, 113, 12, 20, "<"));
	this.buttonList.add(new GuiButton(1, (width - xSize) / 2 + (xSize - 19), 113, 12, 20, ">"));
}

public void actionPerformed(GuiButton button)
{
	switch (button.id)
	{
		case 0:
			page--;
			break;
		case 1:
			page++;
			break;

	}
	if (page < 0)
	{
		page = 0;
	}
	if (page > maxPages)
	{
		page = maxPages;
	}
	this.tileentity.setPage(page);
}
}

 

[spoiler=BlockCustomizableBlock]

package larsg310.mods.customization.block;

import larsg310.mods.customization.CustomizationCraft;
import larsg310.mods.customization.lib.GuiIds;
import larsg310.mods.customization.lib.Names;
import larsg310.mods.customization.tileentity.TileEntityCustomizableBlock;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;

public class BlockCustomizableBlock extends Block
{
public BlockCustomizableBlock(int id)
{
	super(id, Material.iron);
	this.setCreativeTab(CreativeTabs.tabBlock);
	this.setUnlocalizedName(Names.CUSTOMIZABLE_BLOCK);
}

public TileEntity createTileEntity(World world, int meta)
{
	return new TileEntityCustomizableBlock();
}

public boolean hasTileEntity(int meta)
{
	return true;
}

public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ)
{
	if(!world.isRemote)
	{
		player.openGui(CustomizationCraft.instance, GuiIds.CUSTOMIZABLE_BLOCK, world, x, y, z);
	}
	return true;
}

public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z)
{
	TileEntity te = world.getBlockTileEntity(x, y, z);
	if (te instanceof TileEntityCustomizableBlock)
	{
		TileEntityCustomizableBlock tileentity = (TileEntityCustomizableBlock) te;

		this.setBlockBounds(tileentity.getMinX(), 0, 0, tileentity.getMaxX(), 1, 1);
	}
}
public boolean isOpaqueCube()
{
	return false;
}
}

 

[spoiler=GuiHandler]

package larsg310.mods.customization.handler;

import larsg310.mods.customization.CustomizationCraft;
import larsg310.mods.customization.gui.GuiCustomizableBlock;
import larsg310.mods.customization.inventory.ContainerCustomizableBlock;
import larsg310.mods.customization.lib.GuiIds;
import larsg310.mods.customization.tileentity.TileEntityCustomizableBlock;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.IGuiHandler;
import cpw.mods.fml.common.network.NetworkRegistry;

public class GuiHandler implements IGuiHandler
{
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
{
	switch(ID)
	{
		case GuiIds.CUSTOMIZABLE_BLOCK:
			return new ContainerCustomizableBlock(player.inventory, (TileEntityCustomizableBlock)world.getBlockTileEntity(x, y, z));
	}
	return null;
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
{
	switch(ID)
	{
		case GuiIds.CUSTOMIZABLE_BLOCK:
			return new GuiCustomizableBlock(player.inventory, (TileEntityCustomizableBlock)world.getBlockTileEntity(x, y, z));
	}
	return null;
}
public static void register()
{
	NetworkRegistry.instance().registerGuiHandler(CustomizationCraft.instance, new GuiHandler());
}
}

 

 

If you need more code, i'll be happy to provide more.

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

getDescriptionPacket is for updating the client tile entity with the data from the server, not the other way around (pretty sure about this - anyone correct me if I'm wrong).

 

You're going to have to send a packet from your Gui when you click a button telling the server which button was clicked (or whatever data you want to send) and let the server process that information.

Link to comment
Share on other sites

So i have to use packets? Damnit, guess it's time to learn how to deal with packets...

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

Ok, i tried using packets, but i can't find find a way to update the tileentity value... Can anyone give a good tutorial, or some code (possibly some pseudocode)?

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

So i have to use packets? Damnit, guess it's time to learn how to deal with packets...

 

Packets are not that hard.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

You can pretty much literally just copy/paste the code from this tutorial (read the tutorial of course, so you know what's going on and where to register your packets and such). Then all you do is create your packet class and fill out the methods. Done. It's really simple once you get familiar with it.

 

EDIT: Sorry, that tutorial is for 1.7.2 - didn't realize you were coding for 1.6.4 at the time.

Link to comment
Share on other sites

Pseudocode:

 

void onButtonPressed() {
    sendPacketToServer(new UpdateTePacket(tileEntity.x, tileEntity.y, tileEntity.z, moreData));
}

void handlePacket(UpdateTePacket packet, World world) {
    if (world.getblock(packet.x, packet.y, packet.z) == MyBlock) {
        MyTileEntity te = world.getBlockTileEntity(packet.x,packet.y,packet.z);
        te.setSomeValue(packet.moreData);
    }
}

At the handlePacket method, how can you make that method? (I'm not good with packets yet, this is the first time i used them)

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

Whoa, whoa, whoa. This can be solved in a much simpler way.

 

If you're just incrementing or decrementing a value, it would be very simple to use Block Events to solve the problem. Block events basically send information consisting of two integers to a specific tile. When a block event is sent, it is received both on client and server side, so you will have to take care of that.

 

To send a block event, simply do

world.addBlockEvent(x, y, z, BlockID, eventIndex, param);

To catch a block event, add this method to the block class belonging to your tile entity:

public boolean onBlockEventReceived(World world, int x, int y, int z, int eventIndex, param)

 

They key to solving your problem is to use world.addBlockEvent each time the value is changed, and send the value along with it. You should add a switch for event indices in onBlockEventReceived, and give this specific event eventIndex 0. If eventIndex == 0, set value in tile entity to param.

Link to comment
Share on other sites

is even easier as expected

 

use the on update function like this:

@Override
public void onUpdate()
{
    if(!worldObj.isRemote)
    {
         if(worldObj.getWorldTime() % 10 == 0)
         {
                PacketDispatcher.sendPacketToAllPlayers(getDiscriptionPacket());
         }
    }
}

 

that should work pretty fine!

Link to comment
Share on other sites

Thanks to all of you! I used the way that diesieben07 linked and it worked!

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

    • Hey folks. I am working on a custom "Mecha" entity (extended from LivingEntity) that the player builds up from blocks that should get modular stats depending on the used blocks. e.g. depending on what will be used for the legs, the entity will have a different jump strength. However, something unexpected is happening when trying to override a few of LivingEntity's functions and using my new own "Mecha" specific fields: instead of their actual instance-specific value, the default value is used (0f for a float, null for an object...) This is especially strange as when executing with the same entity from a point in the code specific to the mecha entity, the correct value is used. Here are some code snippets to better illustrate what I mean: protected float jumpMultiplier; //somewhere later during the code when spawning the entity, jumpMultiplier is set to something like 1.5f //changing the access to public didn't help @Override //Overridden from LivingEntity, this function is only used in the jumpFromGround() function, used in the aiStep() function, used in the LivingEntity tick() function protected float getJumpPower() { //something is wrong with this function //for some reason I can't correctly access the fields and methods from the instanciated entity when I am in one of those overridden protected functions. this is very annoying LogUtils.getLogger().info(String.valueOf(this.jumpMultiplier))) //will print 0f return this.jumpMultiplier * super.getJumpPower(); } //The code above does not operate properly. Written as is, the entity will not jump, and adding debug logs shows that when executing the code, the value of this.jumpMultiplier is 0f //in contrast, it will be the correct value when done here: @Override public void tick() { super.tick(); //inherited LivingEntity logic //Custom logic LogUtils.getLogger().info(String.valueOf(this.jumpMultiplier))) //will print 1.5f } My actual code is slightly different, as the jumpMuliplier is stored in another object (so I am calling "this.legModule.getJumpPower()" instead of the float), but even using a simple float exactly like in the code above didn't help. When running my usual code, the object I try to use is found to be null instead, leading to a crash from a nullPointerException. Here is the stacktrace of said crash: The full code can be viewed here. I have found a workaround in the case of jump strength, but have already found the same problem for another parameter I want to do, and I do not understand why the code is behaving as such, and I would very much like to be able to override those methods as intended - they seemed to work just fine like that for vanilla mobs... Any clues as to what may be happening here?
    • Please delete post. Had not noticed the newest edition for 1.20.6 which resolves the issue.
    • https://paste.ee/p/GTgAV Here's my debug log, I'm on 1.18.2 with forge 40.2.4 and I just want to get it to work!! I cant find any mod names in the error part and I would like some help from the pros!! I have 203 mods at the moment.
    • In 1.20.6 any potion brewed in the brewing stand disappears upon completion.
    • My game crashes whenever I click on Singleplayer then it crashes after the "Saving world". I'm playing on fabric 1.20.1 on forge for the easy instance loading. My game is using 12GB of RAM, I tried deleting the options.txt, and also renaming the saves file but neither worked. Here's the crash report link: https://mclo.gs/qByOqVK
  • Topics

×
×
  • Create New...

Important Information

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