Jump to content

1.7.10 - Problem syncing entity client- vs server-side with NBT loaded params


AlekBardzo

Recommended Posts

Hello

  So I'm trying to access the entity I'm rendering, espiecially I want to access her fields. I did stuff according to this tutorial : http://jabelarminecraft.blogspot.com/p/creating-custom-entities.html

I'm pretty green to Java so perhaps its something simple. No errors pop-up. The problem is the entity is empty and all fields come up as null, even though entities themselves behave properly.

 

public class HumanRenderer extends RenderBiped {

protected ResourceLocation texture;
protected final ResourceLocation male_smallfolk = new ResourceLocation(Constants.MODID+":"+"textures/models/male/Smallfolk.png");
protected final ResourceLocation female_smallfolk = new ResourceLocation(Constants.MODID+":"+"textures/models/female/Smallfolk.png");

public HumanRenderer(ModelBiped p_i1261_1_, float p_i1261_2_) {
	super((ModelBiped) p_i1261_1_, p_i1261_2_);
	texture = new ResourceLocation(Constants.MODID+":"+"textures/models/Brigand.png");
}

protected void setEntityTexture(){}

@Override
protected void preRenderCallback(EntityLivingBase entity, float f) {
	callback((HumanEntity) entity,f);
}

protected void callback(HumanEntity human, float f){
	System.out.println("Rendering "+human.firstName+" "+human.familyName+" male ? : "+String.valueOf(human.isMale)+" | ");
}

@Override
protected ResourceLocation getEntityTexture(Entity entity) {
	return texture;
}

}

 

Any ideas please ?

 

EDIT:

The entity in question is a mob. I've found then when interacting with it, I get a double response, one is an empty entity and second is the one I expect. What did I screw up then ? Which piece of code do You need to see ? Is it perhaps due to the server/client issues ?

Link to comment
Share on other sites

Did you register your renderer?

 

You get 2 messages: one is client side and on is server side.

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

Yes, one is client, and one is server, I looked closely now and that is true. I did Register my Renderer and the rendering is more or less correct. I believe my problem is that server side has proper data and client side, does not. The parameters in my Entity are loaded through NBT... where should I look then ?

 

EDIT:

I checked now more thoroughly and entity's readEntityFromNBT() is called on the server only

Link to comment
Share on other sites

You have to sync the variables from server->client. You can probably use the DataWatcher for that.

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

Well, I dont think Datawatcher is what is appropriate here, the fields in question are defined when entity is spawned and only then (I dont plan to enable sex changes), so I guess IExtendedEntityProperties is the way to go ?

 

I was going gray and bald, and then I found this :

http://www.minecraftforum.net/forums/mapping-and-modding/mapping-and-modding-tutorials/1571567-forge-1-6-4-1-8-eventhandler-and?comment=2

 

I bet the answer is there, but I'm none the wiser... its so freaking convoluted... code for 1.6.4 then updated for 1.7.2 with examples out of context... nightmare...

 

I managed to save/load my data with IEntityExtendedParameters, but client is still out of sync with server... :(

Link to comment
Share on other sites

And it ALWAYS will be. All NBT-reading happens always on Server thread. Client can't have them (data inside) if you don't synchronize it. You will need to send packets.

 

About packets:

http://www.minecraftforum.net/forums/mapping-and-modding/mapping-and-modding-tutorials/2137055-1-7-2-customizing-packet-handling-with

Or bit simplier: www.minecraftforge.net/forum/index.php/topic,20135.0.html

 

As for your "the fields in question are defined when entity is spawned" you could use something called IEntityAdditionalSpawnData.

But then you won't be updating it, its only added on spawning new entities.

 

Btw. Polak? ("Bardzo" = "very" in Polish)

1.7.10 is no longer supported by forge, you are on your own.

Link to comment
Share on other sites

And it ALWAYS will be. All NBT-reading happens always on Server thread. Client can't have them (data inside) if you don't synchronize it. You will need to send packets.

Yeah, I figured as much already...

 

About packets:

http://www.minecraftforum.net/forums/mapping-and-modding/mapping-and-modding-tutorials/2137055-1-7-2-customizing-packet-handling-with

Or bit simplier: www.minecraftforge.net/forum/index.php/topic,20135.0.html

Many thanks :)

 

As for your "the fields in question are defined when entity is spawned" you could use something called IEntityAdditionalSpawnData.

But then you won't be updating it, its only added on spawning new entities.

I want those entities to be persistent in the game, so I implemented IExtendedEntityProperties, yet it does nothing to inform the client about that data, or perhaps my implementation is wrong. Should IExtendedEntityProperties be updating client info ? Or is it just designed for persistence on the server ?

 

Btw. Polak? ("Bardzo" = "very" in Polish)

Affirmative :)
Link to comment
Share on other sites

Allright, thats probably obvious, but :

- I have a persistent entity that is loaded, upon loading I want to send a packet to a client. So I'm sending a packet, to a player. How do I know which player should I send it to ? Send it to everyone and check if a player is aware of entity's existence ?

 

EDIT:

That wont work since server will load entity's data before client is even ready. I'll have to have client request missing data and hope for response, and the whole thing gets hopelessly convoluted in the process...

Link to comment
Share on other sites

Since I am around stuff you want to use you can call me on Skype: ernio333 (I jak jeszcze nie oczywiste to Polak)

 

As for "figure it on your own".

 

IEEP is (should be) assigned to entity in EntityConstructingEvent, hence it will exist on Client and Server thread (unless you ofc don't want it to). Then - on Server (since its the side handling/saving data it will call read/write NBT).

About synchro:

There is a thing called EntityTracker - each player has a tracker. Inside tracker there is set of entities that given player should be informed about. To simplify: If there is something in your (player's) "tracking" range (which is msot of the time about 64 blocks - visible range) that that means that the server will add this entity to your tracker and you will receive data packet about it - movements, everything.

 

In case you didn't know: Server keeps ALL entities for ALL worlds. Client only has entities that are being tracket by client-player (which means that if something is out of your vision, it's entity will be finalized (deconstructed)). Logically - if something is added to your tracker, your client will construct it. That means that every time someone is added to your tracker, you will need to resynchronize ALL data (since old one is lost).

 

How-to:

PlayerLoggedInEvent - use to send syncho-data after you logged in, use this rather (ofc not always) for your player (e.g you want Client to know that he's level = 10).

PlayerRespawnedEvent - same as above but called after respawn (after client has your PlayerEntity constructed)

PlayerChangedDimensionEvent - same, but other situation

 

PlayerEvent.StartTracking - this is called when an event.target is added to event.player EntityTracker. You can use it for e.g - when you event.player starts "seeing" some Entity, you can send IEEP packet to event.player with update regarding event.target.

PlayerEvent.StopTracking - same, but stop.

 

As for other stuff - sending packets every tick is almost dumb - use dataWatcher (upating stuff like mana, special-shield, stuff)

As for making changes to some entity  and synchronizing it with other clients - e.g Player sees some Entity, but this entity's IEEP will suddenly change some value (ofc Server-side). You will need to send update to all trackers (players that are seeing this entity).

Use:

EntityTracker et = ((WorldServer)this.player.worldObj).getEntityTracker();
		et.func_151248_b(this.player, PacketDispatcher.getInstance().getPacketFrom(new PacketSendLevel(this.player, this.getLevel())));

this.player - owner of my IEEP.

func_151248_b - tracker send update to all tracking entities AND player himself.

 

This probably exhausted thread, any questions? :)

1.7.10 is no longer supported by forge, you are on your own.

Link to comment
Share on other sites

Nice summary there Ernio!

 

For entities that implement IEntityAdditionalSpawnData, is that data not also sent to the client when they start tracking, since the client version of the entity must be constructed?

 

If your data doesn't change, then, I would expect that to be sufficient - you shouldn't even need IExtendedEntityProperties unless you want the data to be applied to vanilla / other mod's entities.

Link to comment
Share on other sites

That clouds up my mind even further... so lets take a wider perspective then.

 

There is a Entity, Entity is a Human, so it has a name, surname and sex. Those are given to it on first spawn, and will not change during the game (lets assume that).

- should it then be enough to use IEntityAdditionalSpawnData ?

- does it require IExtendedEntityProperties ?

- or perhaps it needs additional playing around with packets to get synced ?

 

perhaps I'm creating my entity wrong then, for those parameters to be given to the entity, what is the good place to do it ? Constructor ? "init()" ?

 

By the way "init()" function within Entity declaration, what does it do exacly ? In human comprehendible way I mean ?

Link to comment
Share on other sites

As Ernio said, you would need IEEP and some packet synchronizations.

(or, it would be better to use DataWatcher.)

 

and, the init method will, of course, "initialize" the entity, like initializing datas, IEEP, and so on.

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

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

    • Hi! If you have your forge installation file not in the system disc on PC (D, E etc.), drag it to disk C and try to start again. In my case it solved the problem.
    • KILAT77 : Waspada Situs Scam dengan Withdraw Yang Tidak Dibayar Di era digital saat ini, banyak orang yang mencari keberuntungan melalui situs perjudian online. Namun, dibalik gemerlap janji-janji manis kemenangan, ada bahaya yang mengintai. Salah satu situs yang patut diwaspadai adalah KILAT77. Situs ini mendapat reputasi buruk karena banyak laporan dari pengguna yang mengklaim bahwa mereka tidak bisa menarik dana kemenangan mereka. Dalam artikel ini, kita akan membahas mengapa ROTER88 dianggap sebagai situs scam dan bagaimana Anda bisa melindungi diri dari penipuan serupa. Pengalaman Pengguna: Penarikan Tidak Dibayar Beberapa pengguna telah melaporkan pengalaman buruk mereka dengan KILAT77. Mereka mengaku bahwa setelah memenangkan sejumlah uang dan mencoba menariknya, proses penarikan mereka ditolak tanpa alasan yang jelas. Bahkan, beberapa pengguna melaporkan bahwa akun mereka tiba-tiba diblokir setelah mencoba melakukan penarikan, sehingga mereka kehilangan akses ke dana mereka sama sekali.
    • It is a dupe mod issue Remove Rubidium - you are already using Embeddium which is a fork of Rubidium
    • I made a block entity in forge 1.20.1, I want to prevent hopper from taking input slot item, i tried to override the extractItem method, it prevented hopper from taking input slot item, but the player also unable to take/change the item in input slot unless the slot is empty. public class FluidSeparatorBlockEntity extends BlockEntity implements MenuProvider { private static final int INPUT_SLOT = 0; private final CustomItemHandler itemHandler = new CustomItemHandler(3){ @Override protected void onContentsChanged(int slot) { setChanged(); } @Override public boolean isItemValid(int slot, @NotNull ItemStack stack) { return slot == INPUT_SLOT; } @Override public @NotNull ItemStack extractItem(int slot, int amount, boolean simulate) { if (slot == INPUT_SLOT) { return ItemStack.EMPTY; } return super.extractItem(slot, amount, simulate); } }; private LazyOptional<IItemHandler> lazyItemHandler = LazyOptional.empty(); protected final ContainerData data; private int progress = 0; private int maxProgress = 78; public FluidSeparatorBlockEntity(BlockPos pPos, BlockState pBlockState) { super(ModBlockEntities.FLUID_SEPARATOR_BE.get(), pPos, pBlockState); this.data = new ContainerData() { @Override public int get(int pIndex) { return switch (pIndex) { case 0 -> FluidSeparatorBlockEntity.this.progress; case 1, 2 -> FluidSeparatorBlockEntity.this.maxProgress; default -> 0; }; } @Override public void set(int pIndex, int pValue) { switch (pIndex) { case 0 -> FluidSeparatorBlockEntity.this.progress = pValue; case 1, 2 -> FluidSeparatorBlockEntity.this.maxProgress = pValue; } } @Override public int getCount() { return 3; } }; } @Override public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) { if(cap == ForgeCapabilities.ITEM_HANDLER) { return lazyItemHandler.cast(); } return super.getCapability(cap, side); } @Override public void onLoad() { super.onLoad(); lazyItemHandler = LazyOptional.of(() -> itemHandler); } @Override public void invalidateCaps() { super.invalidateCaps(); lazyItemHandler.invalidate(); } public void drops() { SimpleContainer inventory = new SimpleContainer(itemHandler.getSlots()); for(int i = 0; i < itemHandler.getSlots(); i++) { inventory.setItem(i, itemHandler.getStackInSlot(i)); } Containers.dropContents(this.level, this.worldPosition, inventory); } @Override public Component getDisplayName() { return Component.translatable("block.chemmaster.fluid_separator"); } @Nullable @Override public AbstractContainerMenu createMenu(int pContainerId, Inventory pPlayerInventory, Player pPlayer) { return new FluidSeparatorMenu(pContainerId, pPlayerInventory, this, this.data); } @Override protected void saveAdditional(CompoundTag pTag) { pTag.put("inventory", itemHandler.serializeNBT()); pTag.putInt("fluid_separator.progress", progress); super.saveAdditional(pTag); } @Override public void load(CompoundTag pTag) { super.load(pTag); itemHandler.deserializeNBT(pTag.getCompound("inventory")); progress = pTag.getInt("fluid_separator.progress"); } public void tick(Level pLevel, BlockPos pPos, BlockState pState) { ItemStack inputStack = this.itemHandler.getStackInSlot(INPUT_SLOT); if (inputStack.getCount() < 2) { resetProgress(); return; } if(hasRecipe()) { increaseCraftingProgress(); setChanged(pLevel, pPos, pState); if(hasProgressFinished()) { craftItem(); resetProgress(); } } else { resetProgress(); } } private void resetProgress() { progress = 0; } private void craftItem() { Optional<FluidSeparatingRecipe> recipe = getCurrentRecipe(); if (recipe.isPresent()) { List<ItemStack> results = recipe.get().getOutputs(); ItemStack inputStack = this.itemHandler.getStackInSlot(INPUT_SLOT); if (inputStack.getCount() < 2) { // If there are not enough items, do not proceed with crafting return; } // Extract the input item from the input slot this.itemHandler.internalExtractItem(INPUT_SLOT, 2, false); // Loop through each result item and find suitable output slots for (ItemStack result : results) { int outputSlot = findSuitableOutputSlot(result); if (outputSlot != -1) { this.itemHandler.setStackInSlot(outputSlot, new ItemStack(result.getItem(), this.itemHandler.getStackInSlot(outputSlot).getCount() + result.getCount())); } else { // Handle the case where no suitable output slot is found // This can be logging an error, throwing an exception, or any other handling logic System.err.println("No suitable output slot found for item: " + result); } } } } private int findSuitableOutputSlot(ItemStack result) { // Implement logic to find a suitable output slot for the given result // Return the slot index or -1 if no suitable slot is found for (int i = 0; i < this.itemHandler.getSlots(); i++) { // Ensure we do not place the output item in the input slot if (i == INPUT_SLOT) { continue; } ItemStack stackInSlot = this.itemHandler.getStackInSlot(i); if (stackInSlot.isEmpty() || (stackInSlot.getItem() == result.getItem() && stackInSlot.getCount() + result.getCount() <= stackInSlot.getMaxStackSize())) { return i; } } return -1; } private boolean hasRecipe() { Optional<FluidSeparatingRecipe> recipe = getCurrentRecipe(); if (recipe.isEmpty()) { return false; } List<ItemStack> results = recipe.get().getOutputs(); for (ItemStack result : results) { if (!canInsertAmountIntoOutputSlot(result) || !canInsertItemIntoOutputSlot(result.getItem())) { return false; } } return true; } private Optional<FluidSeparatingRecipe> getCurrentRecipe(){ SimpleContainer inventory = new SimpleContainer(this.itemHandler.getSlots()); for (int i = 0; i < itemHandler.getSlots(); i++) { inventory.setItem(i, this.itemHandler.getStackInSlot(i)); } return this.level.getRecipeManager().getRecipeFor(FluidSeparatingRecipe.Type.INSTANCE, inventory, level); } private boolean canInsertAmountIntoOutputSlot(ItemStack result) { for (int i = 1; i < this.itemHandler.getSlots(); i++) { ItemStack stackInSlot = this.itemHandler.getStackInSlot(i); if (stackInSlot.isEmpty() || (stackInSlot.getItem() == result.getItem() && stackInSlot.getCount() + result.getCount() <= stackInSlot.getMaxStackSize())) { return true; } } return false; } private boolean canInsertItemIntoOutputSlot(Item item) { for (int i = 1; i < this.itemHandler.getSlots(); i++) { ItemStack stackInSlot = this.itemHandler.getStackInSlot(i); if (stackInSlot.isEmpty() || stackInSlot.getItem() == item) { return true; } } return false; } private boolean hasProgressFinished() { return progress >= maxProgress; } private void increaseCraftingProgress() { progress++; } }  
  • Topics

×
×
  • Create New...

Important Information

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