Jump to content

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


Recommended Posts

Posted

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 ?

Posted

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

Posted

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/

Posted

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... :(

Posted

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.

Posted

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 :)
Posted

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...

Posted

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.

Posted

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.

Posted

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 ?

Posted

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.

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.