Jump to content

[SOLVED] Synchronizing ItemStack NBT during onItemUse method


Recommended Posts

Posted

I've recently been trying to update my Structure Generation Toolhttps://github.com/coolAlias/StructureGenerationTool to be compatible with multi-player; as such, I've changed to a KeyHandler and storing the Item variables in NBT.

 

Each key press changes a variable in the item's NBT, but this is only client side. I know I can send packets, but I was hoping not to spam packets because the data is only needed when the item is used. I've been trying to send a packet from client to server onItemUse, which works, but it's too late to the party and the Item activates with the data from the previous time instead of the current data.

 

I played around with synchronized variable and wait/notify, but it results in thread lock since the server side is waiting for the information but it can't get it until the onItemUse method is called client side, which obviously doesn't happen while the thread is waiting.

 

Here's my item code with my failed attempts:

 

public class ItemStructureSpawner extends BaseModItem
{
/** Enumerates valid values for increment / decrement offset methods */
public static enum Offset { OFFSET_X, OFFSET_Y, OFFSET_Z }

/** List of all structures that can be generated with this item */
private static final List<Structure> structures = new LinkedList();

private static final StructureGeneratorBase gen = new WorldGenStructure();

/** String identifiers for NBT storage and retrieval */
private static final String[] data = {"Structure", "Rotations", "OffsetX", "OffsetY", "OffsetZ", "InvertY"};

/** Indices for data variables */
private static final int STRUCTURE_INDEX = 0, ROTATIONS = 1, OFFSET_X = 2, OFFSET_Y = 3, OFFSET_Z = 4, INVERT_Y = 5;

public ItemStructureSpawner(int par1)
{
	super(par1);
	setMaxDamage(0);
	setMaxStackSize(1);
	setCreativeTab(CreativeTabs.tabMisc);
	// constructor should only be called once anyways
	init();
	LogHelper.log(Level.INFO, "ItemStructureSpawner initialized structures.");
}

/**
     * Called when item is crafted/smelted. Not called from Creative Tabs.
     */
@Override
    public void onCreated(ItemStack itemstack, World world, EntityPlayer player)
    {
	initNBTCompound(itemstack);
    }

/**
 * Increments the appropriate Offset and returns the new value for convenience.
 */
public int incrementOffset(ItemStack itemstack, Offset type)
{
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);

	int offset;

	switch(type) {
	case OFFSET_X:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_X]) + 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_X], offset);
		return offset;
	case OFFSET_Y:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_Y]) + 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_Y], offset);
		return offset;
	case OFFSET_Z:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_Z]) + 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_Z], offset);
		return offset;
	default: return 0;
	}
}

/**
 * Decrements the appropriate Offset and returns the new value for convenience.
 */
public int decrementOffset(ItemStack itemstack, Offset type)
{
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);

	int offset;

	switch(type) {
	case OFFSET_X:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_X]) - 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_X], offset);
		return offset;
	case OFFSET_Y:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_Y]) - 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_Y], offset);
		return offset;
	case OFFSET_Z:
		offset = itemstack.stackTagCompound.getInteger(data[OFFSET_Z]) - 1;
		itemstack.stackTagCompound.setInteger(data[OFFSET_Z], offset);
		return offset;
	default: return 0;
	}
}

/**
 * Returns true if y offset is inverted (i.e. y will decrement)
 */
public boolean isInverted(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	return itemstack.stackTagCompound.getBoolean(data[iNVERT_Y]);
}

/**
 * Inverts Y axis for offset adjustments; returns new value for convenience.
 */
public boolean invertY(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	boolean invert = !itemstack.stackTagCompound.getBoolean(data[iNVERT_Y]);
	itemstack.stackTagCompound.setBoolean(data[iNVERT_Y], invert);
	return invert;
}

/**
 * Resets all manual offsets to 0.
 */
public void resetOffset(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	itemstack.stackTagCompound.setInteger(data[OFFSET_X], 0);
	itemstack.stackTagCompound.setInteger(data[OFFSET_Y], 0);
	itemstack.stackTagCompound.setInteger(data[OFFSET_Z], 0);
}

/**
 * Rotates structure's facing by 90 degrees clockwise; returns number of rotations for convenience.
 */
public int rotate(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	int rotations = (itemstack.stackTagCompound.getInteger(data[ROTATIONS]) + 1) % 4;
	itemstack.stackTagCompound.setInteger(data[ROTATIONS], rotations);
	return rotations;
}

/**
 * Increments the structure index and returns the new value for convenience.
 */
public int nextStructure(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	int index = itemstack.stackTagCompound.getInteger(data[sTRUCTURE_INDEX]) + 1;
	if (index == structures.size()) index = 0;
	itemstack.stackTagCompound.setInteger(data[sTRUCTURE_INDEX], index);
	return index;
}

/**
 * Decrements the structure index and returns the new value for convenience.
 */
public int prevStructure(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	int index = itemstack.stackTagCompound.getInteger(data[sTRUCTURE_INDEX]) - 1;
	if (index < 0) index = this.structures.size() - 1;
	itemstack.stackTagCompound.setInteger(data[sTRUCTURE_INDEX], index);
	return index;
}

/**
 * Returns the name of the structure at provided index, or "" if index out of bounds
 */
public String getStructureName(int index) {
	return (index < structures.size() ? structures.get(index).name : "");
}

/**
 * Returns index of currently selected structure
 */
public int getCurrentStructureIndex(ItemStack itemstack) {
	if (itemstack.stackTagCompound == null)
		initNBTCompound(itemstack);
	return itemstack.stackTagCompound.getInteger(data[sTRUCTURE_INDEX]);
}

/**
 * Toggles between generate and remove structure setting. Returns new value for convenience.
 */
public boolean toggleRemove() {
	return gen.toggleRemoveStructure();
}

@Override
public int getMaxItemUseDuration(ItemStack par1ItemStack)
    {
        return 1;
    }

@Override
public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int par7, float par8, float par9, float par10)
    {
	// Need to update server with correct information
	if (world.isRemote) {
		if (itemstack.stackTagCompound == null)
			initNBTCompound(itemstack);
		PacketDispatcher.sendPacketToServer(SGTPacketNBTItem.getPacket(itemstack));
	}
	// NOTE: It isn't absolutely necessary to check if the world is not remote here,
	// but I recommend it as the client will be notified automatically anyway.
	if (!world.isRemote && structures.size() > 0)
	{
		//new SyncThread(itemstack);
		/*
		while (itemstack.stackTagCompound == null)
		{
			try {
				System.out.println("Waiting...");
				wait();
			} catch (InterruptedException e) {
				System.out.println("Interrupted.");
				//e.printStackTrace();
				//return false;
			}
			System.out.println("Finished waiting.");
		}
		*/
		/*
		if (itemstack.stackTagCompound == null) {
			LogHelper.log(Level.SEVERE, "Item Structure Spawner's NBT Tag is null.");
			//initNBTCompound(itemstack);
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
				return false;
			}
		}
		*/
		NBTTagCompound tag = itemstack.stackTagCompound;
		// LogHelper.log(Level.INFO, "Preparing to generate structure");
		gen.setPlayerFacing(player);
		//gen.addBlockArray(StructureArrays.blockArrayNPCBlackSmith);
		Structure structure = structures.get(tag.getInteger(data[sTRUCTURE_INDEX]));
		// LogHelper.log(Level.INFO, "Structure size: " + structure.blockArrayList().size());
		gen.setBlockArrayList(structure.blockArrayList());
		gen.setStructureFacing(structure.getFacing() + tag.getInteger(data[ROTATIONS]));
		// LogHelper.log(Level.INFO, "Default offsets: " + structure.getOffsetX() + "/" + structure.getOffsetZ());
		//structure.setDefaultOffset(this.offsetX, this.offsetY, this.offsetZ);
		gen.setDefaultOffset(structure.getOffsetX() + tag.getInteger(data[OFFSET_X]), structure.getOffsetY() + tag.getInteger(data[OFFSET_Y]), structure.getOffsetZ() + tag.getInteger(data[OFFSET_Z]));
		// adjust for structure generating centered on player's position (including height)
		//gen.setDefaultOffset(structure.getOffsetX() + this.offsetX, structure.getOffsetY() + this.offsetY, structure.getOffsetZ() + this.offsetZ); // adjust down one for the buffer layer
		gen.generate(world, world.rand, x, y, z);

		// reset for next time
		itemstack.stackTagCompound = null;
	}

        return true;
    }

private final void initNBTCompound(ItemStack itemstack)
{
	if (itemstack.stackTagCompound == null)
		itemstack.stackTagCompound = new NBTTagCompound();

	for (int i = 0; i < INVERT_Y; ++i) {
    		itemstack.stackTagCompound.setInteger(data[i], 0);
    	}
    	
    	itemstack.stackTagCompound.setBoolean(data[iNVERT_Y], false);
    	
    	LogHelper.log(Level.INFO, "NBT Tag initialized for ItemStructureSpawner");
}

private final void init()
{
	Structure structure = new Structure("Hut");
	structure.addBlockArray(StructureArrays.blockArrayNPCHut);
	structure.setFacing(StructureGeneratorBase.EAST);
	// has a buffer layer on the bottom in case no ground; spawn at y-1 for ground level
	structure.setStructureOffset(0, -1, 0);
	structures.add(structure);

	structure = new Structure("Blacksmith");
	structure.addBlockArray(StructureArrays.blockArrayNPCBlackSmith);
	structure.setFacing(StructureGeneratorBase.NORTH);
	structures.add(structure);

	structure = new Structure("Viking Shop");
	structure.addBlockArray(StructureArrays.blockArrayShop);
	structure.setFacing(StructureGeneratorBase.WEST);
	structures.add(structure);

	structure = new Structure("Redstone Dungeon");
	structure.addBlockArray(StructureArrays.blockArrayRedstone);
	//structure.setFacing(StructureGeneratorBase.EAST);
	structures.add(structure);

	structure = new Structure("Offset Test");
	structure.addBlockArray(StructureArrays.blockArraySpawnTest);
	structure.setFacing(StructureGeneratorBase.NORTH);
	structures.add(structure);
}
}
// mangled attempt at multi-threading...
class SyncThread implements Runnable
{
Thread t;

private final ItemStack itemstack;

public SyncThread(ItemStack itemstack) {
	t = new Thread();
	this.itemstack = itemstack;
	t.start();
}

@Override
public void run()
{
	//synchronized (itemstack)
	{
		while (itemstack.stackTagCompound == null)
		{
			try {
				wait();
			} catch (InterruptedException e) {

			}
		}
	}
}
}

 

And my PacketHandler with custom packet class:

 

public class SGTPacketHandler implements IPacketHandler
{
/** Packet IDs */
public static final byte PACKET_NBT_ITEM = 1;

@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player player)
{
	System.out.println("[sERVER] Received client packet.");
	DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data));
	byte packetType;

	try {
		packetType = inputStream.readByte();
	} catch (IOException e) {
		e.printStackTrace();
		return;
	}

	switch(packetType) {
	case PACKET_NBT_ITEM: handlePacketNBTItem(packet, (EntityPlayer) player, inputStream); break;
	default: LogHelper.log(Level.SEVERE, "Unhandled packet exception for packet id " + packetType);
	}
}

private void handlePacketNBTItem(Packet250CustomPayload packet, EntityPlayer player, DataInputStream inputStream)
{
	short size;

	try {
		size = inputStream.readShort();
		if (size > 0) {
			byte[] abyte = new byte[size];
			inputStream.readFully(abyte);
			player.getHeldItem().stackTagCompound = CompressedStreamTools.decompress(abyte);
		}
	} catch (IOException e) {
		e.printStackTrace();
		return;
	}

	//notifyAll();
}
}

// The custom packet class:
public class SGTPacketNBTItem
{
public static Packet250CustomPayload getPacket(ItemStack itemstack)
{
	NBTTagCompound compound = itemstack.stackTagCompound;
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	DataOutputStream outputStream = new DataOutputStream(bos);

	try {
		outputStream.writeByte(SGTPacketHandler.PACKET_NBT_ITEM);
		if (compound == null) {
			outputStream.writeShort(-1);
        } else {
            byte[] abyte = CompressedStreamTools.compress(compound);
            outputStream.writeShort((short) abyte.length);
            outputStream.write(abyte);
        }
	} catch (Exception ex) {
		ex.printStackTrace();
	}
	Packet250CustomPayload packet = new Packet250CustomPayload();
	packet.channel = ModInfo.CHANNEL;
	packet.data = bos.toByteArray();
	packet.length = bos.size();

	return packet;
}
}

 

 

Posted

Heh, yeah I know. I was just trying to figure a way around sending so many packets, but I guess there's no help for it in this situation. I was really hoping to be able to just send one packet with all the information, but since the keyboard is handled client side, that's impossible (as far as I know) without editing NBT from there, which isn't good practice. Thanks for the reply anyway.

Posted

The way I have it set up now is to send packets to the server with the key pressed information, but I also directly edit the NBT client side for display purposes only. When the NBT is actually needed for processing, it only uses the NBT stored on the server. Would this be considered acceptable, or should I not edit the NBT at all client side without requesting the data from the server?

 

I'll show you what I mean:

 

@Override
public void keyDown(EnumSet<TickType> types, KeyBinding kb, boolean tickEnd, boolean isRepeat)
{
	if (tickEnd && SGTKeyBindings.SGTKeyMap.containsKey(kb.keyCode) && FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT)
	{
		EntityClientPlayerMP player = FMLClientHandler.instance().getClient().thePlayer;

		if (player.getHeldItem() != null && player.getHeldItem().getItem() instanceof ItemStructureSpawner)
		{
// This packet tells the server what key was pressed so it can update server-side NBT:
PacketDispatcher.sendPacketToServer(SGTPacketKeyPress.getPacket((byte) SGTKeyBindings.SGTKeyMap.get(kb.keyCode)));

			ItemStructureSpawner spawner = (ItemStructureSpawner) player.getHeldItem().getItem();

// This switch changes NBT client side to display a message only:
			switch (SGTKeyBindings.SGTKeyMap.get(kb.keyCode)) {
			case SGTKeyBindings.PLUS_X: player.addChatMessage("[sTRUCTURE GEN] Incremented x offset: " + spawner.incrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_X)); break;
			case SGTKeyBindings.MINUS_X: player.addChatMessage("[sTRUCTURE GEN] Decremented x offset: " + spawner.decrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_X)); break;
			case SGTKeyBindings.PLUS_Z: player.addChatMessage("[sTRUCTURE GEN] Incremented z offset: " + spawner.incrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_Z)); break;
			case SGTKeyBindings.MINUS_Z: player.addChatMessage("[sTRUCTURE GEN] Decremented z offset: " + spawner.decrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_Z)); break;
			case SGTKeyBindings.OFFSET_Y:
				if (spawner.isInverted(player.getHeldItem()))
					player.addChatMessage("[sTRUCTURE GEN] Decremented y offset: " + spawner.decrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_Y));
				else
					player.addChatMessage("[sTRUCTURE GEN] Incremented y offset: " + spawner.incrementOffset(player.getHeldItem(), ItemStructureSpawner.Offset.OFFSET_Y));
				break;
			case SGTKeyBindings.INVERT_Y: player.addChatMessage("[sTRUCTURE GEN] y offset will now " + (spawner.invertY(player.getHeldItem()) ? "decrement." : "increment.")); break;
			case SGTKeyBindings.RESET_OFFSET:
				spawner.resetOffset(player.getHeldItem());
				player.addChatMessage("[sTRUCTURE GEN] Offsets x/y/z reset to 0.");
				break;
			case SGTKeyBindings.ROTATE: player.addChatMessage("[sTRUCTURE GEN] Structure orientation rotated by " + (spawner.rotate(player.getHeldItem()) * 90) + " degrees."); break;
			case SGTKeyBindings.PREV_STRUCT: player.addChatMessage("[sTRUCTURE GEN] Selected structure: " + spawner.getStructureName(spawner.prevStructure(player.getHeldItem())) + " at index " + (spawner.getCurrentStructureIndex(player.getHeldItem()) + 1)); break;
			case SGTKeyBindings.NEXT_STRUCT: player.addChatMessage("[sTRUCTURE GEN] Selected structure: " + spawner.getStructureName(spawner.nextStructure(player.getHeldItem())) + " at index " + (spawner.getCurrentStructureIndex(player.getHeldItem()) + 1)); break;
			case SGTKeyBindings.TOGGLE_REMOVE: player.addChatMessage("[sTRUCTURE GEN] Structure will " + (spawner.toggleRemove() ? "be removed" : "generate") + " on right click."); break;
			}
		}
	}
}

 

Then in the Item onItemUse, I only get NBT data from the server:

 

@Override
public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int par7, float par8, float par9, float par10)
    {
	if (!world.isRemote)
	{
// since world is not remote, the NBT tag is from the server; I don't use any of the client-side information
		NBTTagCompound tag = itemstack.stackTagCompound;
		gen.setPlayerFacing(player);
		Structure structure = structures.get(tag.getInteger(data[sTRUCTURE_INDEX]));
		gen.setBlockArrayList(structure.blockArrayList());
		gen.setStructureFacing(structure.getFacing() + tag.getInteger(data[ROTATIONS]));
		gen.setDefaultOffset(structure.getOffsetX() + tag.getInteger(data[OFFSET_X]), structure.getOffsetY() + tag.getInteger(data[OFFSET_Y]), structure.getOffsetZ() + tag.getInteger(data[OFFSET_Z]));
		gen.generate(world, world.rand, x, y, z);
	}

        return true;
    }

 

 

(And sorry about spamming the tutorials - I thought they were relevant to the topics, though some were a few days old they didn't look resolved yet, except for one... my bad.)

Posted

"So many packets"? As in one packet per keypress? What is wrong with that?

I was only trying to think of a way to minimize traffic. Guess it's not a big deal, though.

You should never do any calculations client-sided if they affect the game data in any way. If you have to give the player an Item, don't rely on the client to do it. Never trust the client, it never does what you want and always sends wrong data (that's what you have to assume to make your mod save against hacks).

You seem to overcomplicate things. Just send a packet when a key gets pressed, then on the server change the NBT data when the key-pressed packet arrives. That NBT will be automatically synced by minecraft.

Yes, but it won't be synced quickly enough to display the correct values immediately, which is why I did what I did above. As you can tell, I'm no expert in Java, and I couldn't think of an easy way to display the information immediately without changing the client-side NBT. As I mentioned, it's only used for the display, not any actual calculations that affect the world, player or anything else. I only send the key pressed to the server, not the client side NBT data. Is this still bad form? What would you suggest, then, to display the information?

Posted

Heh, yeah I know. I was just trying to figure a way around sending so many packets, but I guess there's no help for it in this situation.

"So many packets"? As in one packet per keypress? What is wrong with that?

 

In regards to this, in the Minecraft I use to play (not develop) which has around 45 mods in it including heavy hitters such as Mo'Creatures, I often see something such as this:

 

"Memory connection overburdened after processing packets with 2500 still to go"

 

Isn't this an artifact of modders spamming too many packets as coolAlias was indicating?

 

 

Note: I'm not blaming Mo'Creatures, just illustrating that the mods I use don't just add a block.

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.