Jump to content

[1.12.2][SOLVED] Passing NBT/Instance data to functions


Recommended Posts

Posted (edited)

I have an entity with a custom NBT value "type". This is a String, and can be equal to "normal" or "shadow".

Several aspects of this entity rely on the NBT value "type", and I want them to be updated when the value is changed. 

I want to change the model of the entity (or rather, just the texture which is rendered on the entity's model).

The entity also has an inventory capability, allowing it to store items. The size of this inventory, along with the corresponding elements of the inventory GUI, should change with the NBT value.

 

My problem is that I don't know how to do this. When I set the "type" variable to static within the entity's class, all of this works as I want. However, all entities are affected, as expected with a static variable.

When I remove the static modifier from "type", none of the aforementioned things happen.

 

My full source code is available here(GitHub link).

 

The following are the relevant parts of the files to do with this issue:

My entity's class:

Spoiler

package neck.dontstarve.entity;

public class EntityChester extends EntityTameable
{
	private String type;
	private EntityPlayer owner;
    private int index;
	
	public EntityChester(World worldIn)
	{
		super(worldIn);
		this.setSize(0.9F, 0.9F);
		if (this.type == null)
		{
			this.setType("normal");
		}
	}

	private int getInventorySize()
	{
		return 12;
	}

    
	public boolean processInteract(EntityPlayer player, EnumHand hand)
	{
		ItemStack stack = player.getHeldItem(hand);
		
		if (!stack.isEmpty())
		{
			if (stack.getItem() instanceof ItemFood)
			{
				if (getHealth() < getMaxHealth())
				{
					heal(((ItemFood)stack.getItem()).getHealAmount(stack));
					stack.shrink(1);
					if (stack.getCount() == 0) stack = ItemStack.EMPTY;
					if(this.world.isRemote)
					{
						this.world.spawnParticle(EnumParticleTypes.HEART, this.posX, this.posY + 0.5D, this.posZ, 0.0D, 0.0D, 0.0D, new int[0]);
					}
				}
				return true;
			}
		}
		else
		{
			player.openGui(Main.instance, Reference.GUI_CHESTER, world, this.getEntityId(), (int)player.posY, (int)player.posZ);
		
		return true;
		}
		
		return true;
	}
	
	@Override
    public void writeEntityToNBT(NBTTagCompound compound)
    {
        super.writeEntityToNBT(compound);
        compound.setString("Type", this.getType());
        if (this.getOwner() == null)
        {
            compound.setString("OwnerUUID", "");
        }
        else
        {
            compound.setString("OwnerUUID", this.getOwner().getUniqueID().toString());
        }
    }
    
    @Override
    public void readEntityFromNBT(NBTTagCompound compound)
    {
        super.readEntityFromNBT(compound);
        this.setType(compound.getString("Type"));
        String s;
        if (compound.hasKey("OwnerUUID", 8))
        {
            s = compound.getString("OwnerUUID");
        }
        else
        {
            String s1 = compound.getString("Owner");
            s = PreYggdrasilConverter.convertMobOwnerIfNeeded(this.getServer(), s1);
        }

        if (!s.isEmpty())
        {
            try
            {
                this.setOwnerId(UUID.fromString(s));
                this.setTamed(true);
            }
            catch (Throwable var4)
            {
                this.setTamed(false);
            }
        }
    }
    
}

The entity's render class:

Spoiler

package neck.dontstarve.entity.render;

public class RenderChester extends RenderLiving<EntityChester>
{
	public static final ResourceLocation TEXTURES_NORMAL = new ResourceLocation(Reference.MOD_ID + ":textures/entity/chester.png");
	public static final ResourceLocation TEXTURES_SNOW = new ResourceLocation(Reference.MOD_ID + ":textures/entity/chester_snow.png");
	public static final ResourceLocation TEXTURES_SHADOW = new ResourceLocation(Reference.MOD_ID + ":textures/entity/chester_shadow.png");

	public RenderChester(RenderManager manager)
	{
		super(manager, new ModelChester(), 0.5F);
	}

	@Override
	protected ResourceLocation getEntityTexture(EntityChester entity)
	{
		ResourceLocation textures;
		switch(entity.getType())
		{
			case("normal") : textures =  TEXTURES_NORMAL; break;
			case("snow") :  textures =  TEXTURES_SNOW; break;
			case("shadow") : textures =  TEXTURES_SHADOW; break;
			default: textures = TEXTURES_NORMAL; break;
		}
		
		return textures;
	}
}

The capability provider class:

Spoiler

package neck.dontstarve.capability;

public class CapabilityProvider implements ICapabilityProvider
{
	final ChesterInventory chesterInv = new ChesterInventory();
	public static final ResourceLocation KEY = new ResourceLocation(Reference.MOD_ID, "chester_inventory");
	
	public CapabilityProvider(EntityChester chester)
	{
		this.chesterInv.setInstance(chester);
	}

	@Override
	public boolean hasCapability(Capability<?> capability, EnumFacing facing)
	{
		if (capability == ChesterInventoryCapability.CAPABILITY)
		{
			return true;
		}
		return false;
	}

	public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing)
	{
		if (capability == ChesterInventoryCapability.CAPABILITY)
		{
			return (T) this.chesterInv;
		}
		return null;
	}

 

Edited by RiNickolous
Posted

Consider changing your field from a string to an enum and serialize/deserialize it by an ordinal. It will save on both the NBT data size and the network packet size(more on that later).

If you want some data of the entity to affect something on the client you need to create a new DataParameter, store your data in the entity's DataManager with that DataParameter as the key and retrieve the data by using that DataParameter as the key. See pretty much any minecraft entity for an example, an EntitySheep for example.

Additionally since it is your own entity you do not need a capability provider, the entity itself is one. Directly have the inventory stored in your entity as a field, override Entity#hasCapability and Entity#getCapability to check if the capability parameter is your capability and return your inventory if it is, otherwise default to a super implementation.

By the way if you are wondering the reason the static field worked was only because you were reaching across logical sides. It would not work if you would have launched a dedicated server and connected to it.

Posted (edited)
1 hour ago, V0idWa1k3r said:

Consider changing your field from a string to an enum and serialize/deserialize it by an ordinal.

I'm not very experienced with Java, but I think I did this correctly.

EnumChesterType.class

Spoiler

package neck.dontstarve.entity;

import net.minecraft.util.IStringSerializable;

public enum EnumChesterType implements IStringSerializable
{
	NORMAL(0, "normal", 3, false),
	SNOW(1, "snowl", 3, true),
	SHADOW(3, "shadow", 3, false);
	
	private static final EnumChesterType[] META_LOOKUP = new EnumChesterType[values().length];
	private final int meta;
	private final String name;
	private final int invSize;
	private final boolean chillFood;
			
	
	private EnumChesterType(int metaIn, String nameIn, int invSizeIn, boolean chillFoodIn)
	{
		this.meta = metaIn;
		this.name = nameIn;
		this.invSize = invSizeIn;
		this.chillFood = chillFoodIn;
	}
	
	public int getMetadata()
	{
		return this.meta;
	}
	
	public String getName()
	{
		return this.name;
	}
	
	public int getInvSize()
	{
		return this.invSize;
	}
	
	public boolean getChillFood()
	{
		return this.chillFood;
	}
	
	public static EnumChesterType byMetadata(int meta)
	{
		if (meta < 0 || meta >= META_LOOKUP.length)
		{
			meta = 0;
		}
		
		return META_LOOKUP[meta];
	}
	
	static
	{
		for (EnumChesterType type : values())
			META_LOOKUP[type.getMetadata()] = type;
	}
}

 

 

1 hour ago, V0idWa1k3r said:

If you want some data of the entity to affect something on the client you need to create a new DataParameter, store your data in the entity's DataManager with that DataParameter as the key and retrieve the data by using that DataParameter as the key.

I think I did this as well? This is all very foreign to me.

 

In EntityChester:

Spoiler

private static final DataParameter<Byte> TYPE = EntityDataManager.<Byte>createKey(EntityChester.class, DataSerializers.BYTE);

 

 

1 hour ago, V0idWa1k3r said:

Additionally since it is your own entity you do not need a capability provider, the entity itself is one. Directly have the inventory stored in your entity as a field, override Entity#hasCapability and Entity#getCapability to check if the capability parameter is your capability and return your inventory if it is, otherwise default to a super implementation.

This is what confuses me. Could you elaborate on this part, please?

 

For reference:

My CapabilityProvider class:

Spoiler

package neck.dontstarve.capability;

import javax.annotation.Nullable;

import neck.dontstarve.entity.EntityChester;
import neck.dontstarve.util.Reference;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;

public class CapabilityProvider implements ICapabilityProvider
{
	final ChesterInventory chesterInv = new ChesterInventory();
	public static final ResourceLocation KEY = new ResourceLocation(Reference.MOD_ID, "chester_inventory");
	
	public CapabilityProvider(EntityChester chester)
	{
		this.chesterInv.setInstance(chester);
	}

	@Override
	public boolean hasCapability(Capability<?> capability, EnumFacing facing)
	{
		if (capability == ChesterInventoryCapability.CAPABILITY)
		{
			return true;
		}
		return false;
	}

	public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing)
	{
		if (capability == ChesterInventoryCapability.CAPABILITY)
		{
			return (T) this.chesterInv;
		}
		return null;
	}

 

My Capability class:

Spoiler

package neck.dontstarve.capability;

import java.util.concurrent.Callable;

import net.minecraft.nbt.NBTBase;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.CapabilityManager;

public class ChesterInventoryCapability
{
	@CapabilityInject(ChesterInventory.class)
	public static Capability<ChesterInventory> CAPABILITY;
	
	public void register()
	{
		CapabilityManager.INSTANCE.register(ChesterInventory.class, new StorageHelper(), new DefaultInstanceFactory());
	}
	
	public static class StorageHelper implements Capability.IStorage<ChesterInventory>
	{
		public NBTBase writeNBT(Capability<ChesterInventory> capability, ChesterInventory instance, EnumFacing side)
		{
			return instance.writeData();
		}
		
		public void readNBT(Capability<ChesterInventory> capability, ChesterInventory instance, EnumFacing side, NBTBase nbt)
		{
			instance.readData(nbt);
		}
	}
	
	public static class DefaultInstanceFactory implements Callable<ChesterInventory>
	{
		public ChesterInventory call() throws Exception
		{
			return new ChesterInventory();
		}
	}
}

 

and the Inventory itself:

Spoiler

package neck.dontstarve.capability;

import neck.dontstarve.entity.EntityChester;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.items.ItemStackHandler;

public class ChesterInventory
{
	private ChesterStackHandler inventory;
	private String customName = null;
	private String type = "default";
	private EntityChester instance;
	
	private float Health = 20.0F;
	
	public ChesterInventory()
	{
		int slotNum = 12;
		this.inventory = new ChesterStackHandler(slotNum);
	}
	
	public ItemStackHandler getInventoryHandler()
	{
		return this.inventory;
	}
	
	public void setStackInSlot(int index, ItemStack stack)
	{
		this.inventory.setStackInSlot(index, stack);
	}
	
	public NBTBase writeData()
	{
		NBTTagCompound compound = this.inventory.serializeNBT();
		
		if ((getName() != null) && (getName().length() > 0))
		{
			compound.setString("customName", getName());
		}
		compound.setString("type", getType());
		compound.setFloat("health", getHealth());
		
		return compound;
	}
	
	public void readData(NBTBase nbt)
	{
		NBTTagCompound compound = (NBTTagCompound)nbt;
		this.inventory.deserializeNBT((NBTTagCompound)nbt);
		if (compound.hasKey("customName"))
		{
			setName(compound.getString("customName"));
		}
		setType(compound.getString("type"));
		setHealth(compound.getFloat("health"));
	}
	
	public String getName()
	{
		return this.customName;
	}
	
	public void setName(String name)
	{
		this.customName = name;
	}
	
	public String getType()
	{
		return this.type;
	}
	
	public void setType(String type)
	{
		this.type = type;
	}
	
	public float getHealth()
	{
		return this.Health;
	}
	
	public void setHealth(float health)
	{
		this.Health = health;
	}
	
	public void setInstance(EntityChester chester)
	{
		this.instance = chester;
	}
	
	public EntityChester getInstnace()
	{
		return this.instance;
	}
}

 

 

Edited by RiNickolous
added code snippets
Posted

Okay, as it turns out, I have no idea what I'm doing.

 

My most recent crashlog:

Spoiler

---- Minecraft Crash Report ----
// Uh... Did I do that?

Time: 9/19/18 10:13 PM
Description: Unexpected error

java.lang.NoClassDefFoundError: Could not initialize class neck.dontstarve.entity.EnumChesterType
	at neck.dontstarve.entity.EntityChester.getType(EntityChester.java:116)
	at neck.dontstarve.inventory.ContainerChester.<init>(ContainerChester.java:18)
	at neck.dontstarve.gui.GuiChester.<init>(GuiChester.java:26)
	at neck.dontstarve.util.handlers.GuiHandler.getClientGuiElement(GuiHandler.java:31)
	at net.minecraftforge.fml.common.network.NetworkRegistry.getLocalGuiContainer(NetworkRegistry.java:276)
	at net.minecraftforge.fml.common.network.internal.FMLNetworkHandler.openGui(FMLNetworkHandler.java:111)
	at net.minecraft.entity.player.EntityPlayer.openGui(EntityPlayer.java:2809)
	at neck.dontstarve.entity.EntityChester.processInteract(EntityChester.java:93)
	at net.minecraft.entity.EntityLiving.processInitialInteract(EntityLiving.java:1355)
	at net.minecraft.entity.player.EntityPlayer.interactOn(EntityPlayer.java:1299)
	at net.minecraft.client.multiplayer.PlayerControllerMP.interactWithEntity(PlayerControllerMP.java:587)
	at net.minecraft.client.Minecraft.rightClickMouse(Minecraft.java:1680)
	at net.minecraft.client.Minecraft.processKeyBinds(Minecraft.java:2379)
	at net.minecraft.client.Minecraft.runTickKeyboard(Minecraft.java:2145)
	at net.minecraft.client.Minecraft.runTick(Minecraft.java:1933)
	at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:1186)
	at net.minecraft.client.Minecraft.run(Minecraft.java:441)
	at net.minecraft.client.main.Main.main(Main.java:118)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at net.minecraft.launchwrapper.Launch.launch(Launch.java:135)
	at net.minecraft.launchwrapper.Launch.main(Launch.java:28)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at net.minecraftforge.gradle.GradleStartCommon.launch(GradleStartCommon.java:97)
	at GradleStart.main(GradleStart.java:25)


A detailed walkthrough of the error, its code path and all known details is as follows:
---------------------------------------------------------------------------------------

-- Head --
Thread: Client thread
Stacktrace:
	at neck.dontstarve.entity.EntityChester.getType(EntityChester.java:116)
	at neck.dontstarve.inventory.ContainerChester.<init>(ContainerChester.java:18)
	at neck.dontstarve.gui.GuiChester.<init>(GuiChester.java:26)
	at neck.dontstarve.util.handlers.GuiHandler.getClientGuiElement(GuiHandler.java:31)
	at net.minecraftforge.fml.common.network.NetworkRegistry.getLocalGuiContainer(NetworkRegistry.java:276)
	at net.minecraftforge.fml.common.network.internal.FMLNetworkHandler.openGui(FMLNetworkHandler.java:111)
	at net.minecraft.entity.player.EntityPlayer.openGui(EntityPlayer.java:2809)
	at neck.dontstarve.entity.EntityChester.processInteract(EntityChester.java:93)
	at net.minecraft.entity.EntityLiving.processInitialInteract(EntityLiving.java:1355)
	at net.minecraft.entity.player.EntityPlayer.interactOn(EntityPlayer.java:1299)
	at net.minecraft.client.multiplayer.PlayerControllerMP.interactWithEntity(PlayerControllerMP.java:587)
	at net.minecraft.client.Minecraft.rightClickMouse(Minecraft.java:1680)
	at net.minecraft.client.Minecraft.processKeyBinds(Minecraft.java:2379)
	at net.minecraft.client.Minecraft.runTickKeyboard(Minecraft.java:2145)

-- Affected level --
Details:
	Level name: MpServer
	All players: 1 total; [EntityPlayerSP['Player379'/160, l='MpServer', x=-170.97, y=69.00, z=230.58]]
	Chunk stats: MultiplayerChunkCache: 624, 624
	Level seed: 0
	Level generator: ID 00 - default, ver 1. Features enabled: false
	Level generator options: 
	Level spawn location: World: (-176,64,228), Chunk: (at 0,4,4 in -11,14; contains blocks -176,0,224 to -161,255,239), Region: (-1,0; contains chunks -32,0 to -1,31, blocks -512,0,0 to -1,255,511)
	Level time: 443864 game time, 1000 day time
	Level dimension: 0
	Level storage version: 0x00000 - Unknown?
	Level weather: Rain time: 0 (now: false), thunder time: 0 (now: false)
	Level game mode: Game mode: creative (ID 1). Hardcore: false. Cheats: false
	Forced entities: 15 total; [EntityChester['Chester'/3456, l='MpServer', x=-172.50, y=68.00, z=230.50], EntitySquid['Squid'/100, l='MpServer', x=-147.43, y=61.62, z=257.93], EntitySquid['Squid'/101, l='MpServer', x=-147.58, y=59.12, z=250.89], EntityLatchedRenderer['unknown'/421, l='MpServer', x=-170.97, y=69.00, z=230.58], EntitySquid['Squid'/102, l='MpServer', x=-148.10, y=62.14, z=245.10], EntitySquid['Squid'/103, l='MpServer', x=-146.20, y=62.24, z=247.33], EntitySquid['Squid'/104, l='MpServer', x=-154.13, y=62.22, z=278.56], EntitySquid['Squid'/105, l='MpServer', x=-156.30, y=62.60, z=287.11], EntityPlayerSP['Player379'/160, l='MpServer', x=-170.97, y=69.00, z=230.58], EntityLatchedRenderer['unknown'/303, l='MpServer', x=8.50, y=65.00, z=8.50], EntityBat['Bat'/83, l='MpServer', x=-227.47, y=29.55, z=169.14], EntityBat['Bat'/115, l='MpServer', x=-111.25, y=24.04, z=304.50], EntityBat['Bat'/3483, l='MpServer', x=-206.87, y=38.00, z=212.73], EntityBat['Bat'/3485, l='MpServer', x=-203.32, y=38.05, z=204.91], EntityBat['Bat'/3486, l='MpServer', x=-206.33, y=38.03, z=213.36]]
	Retry entities: 1 total; [EntityLatchedRenderer['unknown'/303, l='MpServer', x=8.50, y=65.00, z=8.50]]
	Server brand: fml,forge
	Server type: Integrated singleplayer server
Stacktrace:
	at net.minecraft.client.multiplayer.WorldClient.addWorldInfoToCrashReport(WorldClient.java:461)
	at net.minecraft.client.Minecraft.addGraphicsAndWorldToCrashReport(Minecraft.java:2886)
	at net.minecraft.client.Minecraft.run(Minecraft.java:470)
	at net.minecraft.client.main.Main.main(Main.java:118)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at net.minecraft.launchwrapper.Launch.launch(Launch.java:135)
	at net.minecraft.launchwrapper.Launch.main(Launch.java:28)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at net.minecraftforge.gradle.GradleStartCommon.launch(GradleStartCommon.java:97)
	at GradleStart.main(GradleStart.java:25)

-- System Details --
Details:
	Minecraft Version: 1.12.2
	Operating System: Windows 10 (amd64) version 10.0
	Java Version: 1.8.0_181, Oracle Corporation
	Java VM Version: Java HotSpot(TM) 64-Bit Server VM (mixed mode), Oracle Corporation
	Memory: 745265312 bytes (710 MB) / 1038876672 bytes (990 MB) up to 1038876672 bytes (990 MB)
	JVM Flags: 3 total; -Xincgc -Xmx1024M -Xms1024M
	IntCache: cache: 0, tcache: 0, allocated: 13, tallocated: 95
	FML: MCP 9.42 Powered by Forge 14.23.4.2705 9 mods loaded, 9 mods active
	States: 'U' = Unloaded 'L' = Loaded 'C' = Constructed 'H' = Pre-initialized 'I' = Initialized 'J' = Post-initialized 'A' = Available 'D' = Disabled 'E' = Errored

	| State     | ID              | Version      | Source                           | Signature |
	|:--------- |:--------------- |:------------ |:-------------------------------- |:--------- |
	| UCHIJAAAA | minecraft       | 1.12.2       | minecraft.jar                    | None      |
	| UCHIJAAAA | mcp             | 9.42         | minecraft.jar                    | None      |
	| UCHIJAAAA | FML             | 8.0.99.99    | forgeSrc-1.12.2-14.23.4.2705.jar | None      |
	| UCHIJAAAA | forge           | 14.23.4.2705 | forgeSrc-1.12.2-14.23.4.2705.jar | None      |
	| UCHIJAAAA | dont_starve_mod | 1.0          | bin                              | None      |
	| UCHIJAAAA | ichunutil       | 7.1.4        | iChunUtil-1.12.2-7.1.4.jar       | None      |
	| UCHIJAAAA | jei             | 4.11.0.212   | jei_1.12.2-4.11.0.212.jar        | None      |
	| UCHIJAAAA | nbtedit         | $version     | NBTEdit-0.7.jar                  | None      |
	| UCHIJAAAA | tabula          | 7.0.0        | Tabula-1.12.2-7.0.0.jar          | None      |

	Loaded coremods (and transformers): 
	GL info: ' Vendor: 'NVIDIA Corporation' Version: '4.6.0 NVIDIA 391.35' Renderer: 'GeForce GTX 1060 6GB/PCIe/SSE2'
	Launched Version: 1.12.2
	LWJGL: 2.9.4
	OpenGL: GeForce GTX 1060 6GB/PCIe/SSE2 GL version 4.6.0 NVIDIA 391.35, NVIDIA Corporation
	GL Caps: Using GL 1.3 multitexturing.
Using GL 1.3 texture combiners.
Using framebuffer objects because OpenGL 3.0 is supported and separate blending is supported.
Shaders are available because OpenGL 2.1 is supported.
VBOs are available because OpenGL 1.5 is supported.

	Using VBOs: Yes
	Is Modded: Definitely; Client brand changed to 'fml,forge'
	Type: Client (map_client.txt)
	Resource Packs: 
	Current Language: English (US)
	Profiler Position: N/A (disabled)
	CPU: 4x Intel(R) Core(TM) i5-7500 CPU @ 3.40GHz

 

 

Posted (edited)

You do not need all this "metadata" nonsense, get the enum by it's ordinal(Enum.values()[ordinal], Enum#ordinal).

As for your capability question create a field of ChesterInventory in your entity class, (de)serialize it when needed(readFrom/writeToNBT), override Entity#hasCapability and Entity#getCapability. In those methods check if the capability is yours exactly the same way you are checking it in your provider. If it is return your ChesterInventory, otherwise return a super implementation(return cap == YOUR_CAP ? yourField : super.getCapability(cap, facing) and return cap == YOUR_CAP || super.hasCapability(cap, facing))

Edited by V0idWa1k3r
Posted
55 minutes ago, V0idWa1k3r said:

You do not need all this "metadata" nonsense, get the enum by it's ordinal(Enum.values()[ordinal], Enum#ordinal).

I'm sorry, I still don't think I quite understand. I'm not at all familiar with Enums. Where does this go? How do I make use of this? Looking at the EntitySheep code has left me quite confused.

Posted

(De)serialize the enum as the ordinal. Use the ordinal in your DataManager.

Pseudo-code:

Deserialization: setType(EnumChesterType.values()[tag.readByte("type")])

Serialization: tag.writeByte("type", this.getType().ordinal())

getType: EnumChesterType.values()[dataManager.get(TYPE)]

setType: dataManager.set(TYPE, type.ordinal())

Posted (edited)

I don't know what is going on.

 

EnumChesterType:

Spoiler

package neck.dontstarve.entity;

public enum EnumChesterType
{
	NORMAL(0,"normal", 3, false),
	SNOW(1,"snowl", 3, true),
	SHADOW(2,"shadow", 3, false);
	
	private static final EnumChesterType[] META_LOOKUP = new EnumChesterType[values().length];
	private int id;
	private final String name;
	private final int invSize;
	private final boolean chillFood;
	
	private EnumChesterType(int id, String nameIn, int invSizeIn, boolean chillFoodIn)
	{
		this.name = nameIn;
		this.invSize = invSizeIn;
		this.chillFood = chillFoodIn;
	}
}

 

 

In EntityChester:

Spoiler

private static final DataParameter TYPE = EntityDataManager.createKey(EntityChester.class, DataSerializers.BYTE);

	public void entityInit()
	{
		super.entityInit();
		this.dataManager.register(TYPE, EnumChesterType.NORMAL);
	}

	public EnumChesterType getType()
	{
		return EnumChesterType.values()[(int) this.dataManager.get(TYPE)];
	}
	
	public void setType(EnumChesterType type)
	{
		this.dataManager.set(TYPE,(byte) type.ordinal());
	}
	
	@Override
    public void writeEntityToNBT(NBTTagCompound compound)
    {
        super.writeEntityToNBT(compound);
        compound.setByte("Type", (byte) this.getType().ordinal());
        if (this.getOwner() == null)
        {
            compound.setString("OwnerUUID", "");
        }
        else
        {
            compound.setString("OwnerUUID", this.getOwner().getUniqueID().toString());
        }
    }
    
    @Override
    public void readEntityFromNBT(NBTTagCompound compound)
    {
        super.readEntityFromNBT(compound);
        this.setType(EnumChesterType.values()[compound.getByte("Type")]);
        String s;
        if (compound.hasKey("OwnerUUID", 8))
        {
            s = compound.getString("OwnerUUID");
        }
        else
        {
            String s1 = compound.getString("Owner");
            s = PreYggdrasilConverter.convertMobOwnerIfNeeded(this.getServer(), s1);
        }

        if (!s.isEmpty())
        {
            try
            {
                this.setOwnerId(UUID.fromString(s));
                this.setTamed(true);
            }
            catch (Throwable var4)
            {
                this.setTamed(false);
            }
        }
    }

 

 

crash-log:

Spoiler

---- Minecraft Crash Report ----
// Don't be sad. I'll do better next time, I promise!

Time: 9/20/18 12:52 AM
Description: Exception in server tick loop

java.lang.ClassCastException: neck.dontstarve.entity.EnumChesterType cannot be cast to java.lang.Byte
	at net.minecraft.network.datasync.DataSerializers$1.copyValue(DataSerializers.java:22)
	at net.minecraft.network.datasync.EntityDataManager$DataEntry.copy(EntityDataManager.java:384)
	at net.minecraft.network.datasync.EntityDataManager.getDirty(EntityDataManager.java:212)
	at net.minecraft.network.play.server.SPacketEntityMetadata.<init>(SPacketEntityMetadata.java:32)
	at net.minecraft.entity.EntityTrackerEntry.sendMetadata(EntityTrackerEntry.java:333)
	at net.minecraft.entity.EntityTrackerEntry.updatePlayerList(EntityTrackerEntry.java:285)
	at net.minecraft.entity.EntityTracker.tick(EntityTracker.java:297)
	at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:854)
	at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:743)
	at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:192)
	at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:592)
	at java.lang.Thread.run(Unknown Source)


A detailed walkthrough of the error, its code path and all known details is as follows:
---------------------------------------------------------------------------------------

-- System Details --
Details:
	Minecraft Version: 1.12.2
	Operating System: Windows 10 (amd64) version 10.0
	Java Version: 1.8.0_181, Oracle Corporation
	Java VM Version: Java HotSpot(TM) 64-Bit Server VM (mixed mode), Oracle Corporation
	Memory: 519041048 bytes (494 MB) / 1038876672 bytes (990 MB) up to 1038876672 bytes (990 MB)
	JVM Flags: 3 total; -Xincgc -Xmx1024M -Xms1024M
	IntCache: cache: 0, tcache: 0, allocated: 13, tallocated: 95
	FML: MCP 9.42 Powered by Forge 14.23.4.2705 9 mods loaded, 9 mods active
	States: 'U' = Unloaded 'L' = Loaded 'C' = Constructed 'H' = Pre-initialized 'I' = Initialized 'J' = Post-initialized 'A' = Available 'D' = Disabled 'E' = Errored

	| State     | ID              | Version      | Source                           | Signature |
	|:--------- |:--------------- |:------------ |:-------------------------------- |:--------- |
	| UCHIJAAAA | minecraft       | 1.12.2       | minecraft.jar                    | None      |
	| UCHIJAAAA | mcp             | 9.42         | minecraft.jar                    | None      |
	| UCHIJAAAA | FML             | 8.0.99.99    | forgeSrc-1.12.2-14.23.4.2705.jar | None      |
	| UCHIJAAAA | forge           | 14.23.4.2705 | forgeSrc-1.12.2-14.23.4.2705.jar | None      |
	| UCHIJAAAA | dont_starve_mod | 1.0          | bin                              | None      |
	| UCHIJAAAA | ichunutil       | 7.1.4        | iChunUtil-1.12.2-7.1.4.jar       | None      |
	| UCHIJAAAA | jei             | 4.11.0.212   | jei_1.12.2-4.11.0.212.jar        | None      |
	| UCHIJAAAA | nbtedit         | $version     | NBTEdit-0.7.jar                  | None      |
	| UCHIJAAAA | tabula          | 7.0.0        | Tabula-1.12.2-7.0.0.jar          | None      |

	Loaded coremods (and transformers): 
	GL info: ~~ERROR~~ RuntimeException: No OpenGL context found in the current thread.
	Profiler Position: N/A (disabled)
	Player Count: 1 / 8; [EntityPlayerMP['Player72'/158, l='Testing', x=-171.24, y=69.00, z=229.40]]
	Type: Integrated Server (map_client.txt)
	Is Modded: Definitely; Client brand changed to 'fml,forge'

 

 

Edited by RiNickolous
Posted
27 minutes ago, RiNickolous said:

this.dataManager.register(TYPE, EnumChesterType.NORMAL);

Well here you register the value for the TYPE as an EnumChesterType. But later you use this data manager key as if it was associated with a byte. Stay consistent. If only java had a way to automatically check these kind of errors for you... You know, if only you could put a constraint on the TYPE parameter instead of it being a generic Object accepting anything. Something like DataParameter<Byte> TYPE = ... 

  • Like 1
Posted (edited)
26 minutes ago, V0idWa1k3r said:

Well here you register the value for the TYPE as an EnumChesterType. But later you use this data manager key as if it was associated with a byte. Stay consistent. If only java had a way to automatically check these kind of errors for you... You know, if only you could put a constraint on the TYPE parameter instead of it being a generic Object accepting anything. Something like DataParameter<Byte> TYPE = ... 

Wow, it all works! Thank you so much for being so patient with me. I really appreciate the help.

 

All NBT data is now stored correctly, and functions relevant to them now respond correctly.

Edited by RiNickolous

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

    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
    • Remove rubidium - you are already using embeddium, which is a fork of rubidium
  • Topics

×
×
  • Create New...

Important Information

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