Jump to content

[SOLVED] [1.14.4] Syncing player capabilities to client


Recommended Posts

Posted (edited)

Hey. I need to sync the player's capabilities to them when they log in, respawn, etc., but the events that worked for this purpose in 1.12.2 for some reason no longer work. The capabilities just don't sync when those events happen.

CapabilityStorage:

public class PlayerBaseCapStorage implements IStorage<IPlayerBaseCap> {

	@Override
	public INBT writeNBT(Capability<IPlayerBaseCap> capability, IPlayerBaseCap instance, Direction side) {
		CompoundNBT tag = new CompoundNBT();
		
		tag.putBoolean("firstspawn", instance.getFirstSpawn());
		tag.putInt("village", instance.getVillage());
		tag.putInt("clan", instance.getClan());
		tag.putInt("rank", instance.getRank());
		tag.putInt("level", instance.getLevel());
		tag.putInt("exp", instance.getExp());
		tag.putInt("chakra", instance.getChakra());
		tag.putInt("maxchakra", instance.getMaxChakra());
		
		return tag;
	}

	@Override
	public void readNBT(Capability<IPlayerBaseCap> capability, IPlayerBaseCap instance, Direction side, INBT nbt) {
		CompoundNBT tag = new CompoundNBT();
		
		instance.setFirstSpawn(tag.getBoolean("firstspawn"));
		instance.setVillage(tag.getInt("village"));
		instance.setClan(tag.getInt("clan"));
		instance.setRank(tag.getInt("rank"));
		instance.setLevel(tag.getInt("level"));
		instance.setExp(tag.getInt("exp"));
		instance.setChakra(tag.getInt("chakra"));
		instance.setMaxChakra(tag.getInt("maxchakra"));
		
	}
	
	@Mod.EventBusSubscriber(modid = Main.modid)
    private static class EventHandler {

		@SubscribeEvent
		public static void onAttachCapabilities(AttachCapabilitiesEvent<Entity> event) {
			if (event.getObject() instanceof PlayerEntity) {
				event.addCapability(new ResourceLocation(Main.modid, "base"), new PlayerBaseCapProvider());
			}
		}
		
		@SubscribeEvent
	    public static void playerClone(final PlayerEvent.Clone event) {
			final IPlayerBaseCap oldBaseCap = event.getOriginal().getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!"));
			final IPlayerBaseCap newBaseCap = event.getPlayer().getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!"));
			if (oldBaseCap != null && newBaseCap != null) {
				newBaseCap.setFirstSpawn(oldBaseCap.getFirstSpawn());
				newBaseCap.setVillage(oldBaseCap.getVillage());
				newBaseCap.setClan(oldBaseCap.getClan());
				newBaseCap.setRank(oldBaseCap.getRank());
				newBaseCap.setExp(oldBaseCap.getExp());
				newBaseCap.setLevel(oldBaseCap.getLevel());
				newBaseCap.setChakra(oldBaseCap.getChakra());
				newBaseCap.setMaxChakra(oldBaseCap.getMaxChakra());
			}
		}
		
		@SubscribeEvent
	    public static void serverLoginEvent(final PlayerLoggedInEvent event) {
	    	PlayerEntity player = event.getPlayer();

	    	PacketDispatcher.INSTANCE.sendTo(new PacketFirstSpawn(player), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    	PacketDispatcher.INSTANCE.sendTo(new PacketVillageC(player), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    	PacketDispatcher.INSTANCE.sendTo(new PacketClanC(player), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    	
	    	if (player.getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!")).getFirstSpawn() == true) {
	    		player.getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!")).setFirstSpawn(false);
	    		PacketDispatcher.INSTANCE.sendTo(new PacketFirstSpawn(player), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    		player.sendMessage(new TranslationTextComponent("msgs.firstjoin", ""));
	    		ItemStack stack = new ItemStack(ItemList.character_creation, 1);
	    		player.addItemStackToInventory(stack);
	    	}
		}
		
		@SubscribeEvent
	    public static void changeDimesionEvent(final PlayerChangedDimensionEvent event) {
			PlayerEntity player = event.getPlayer();

	    	PacketDispatcher.INSTANCE.sendTo(new PacketFirstSpawn(player), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    	PacketDispatcher.INSTANCE.sendTo(new PacketVillageC(player), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    	PacketDispatcher.INSTANCE.sendTo(new PacketClanC(player), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
		}
		
		@SubscribeEvent
	    public static void respawnEvent(final PlayerRespawnEvent event) {
	    	PlayerEntity player = event.getPlayer();

	    	PacketDispatcher.INSTANCE.sendTo(new PacketFirstSpawn(player), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    	PacketDispatcher.INSTANCE.sendTo(new PacketVillageC(player), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    	PacketDispatcher.INSTANCE.sendTo(new PacketClanC(player), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
		}
    }
}

 

Packet:

public class PacketFirstSpawn {
	private boolean data;
	private static PlayerEntity player;

	public PacketFirstSpawn() {}
	
    public PacketFirstSpawn(PlayerEntity player) {
    	PacketFirstSpawn.player = player;
    	IPlayerBaseCap playercap = player.getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!"));
        data = playercap.getFirstSpawn();
    }
    public static void encode(PacketFirstSpawn msg, PacketBuffer buf) {
        buf.writeBoolean(msg.data);
    }
    public static PacketFirstSpawn decode(PacketBuffer buf) {
    	return new PacketFirstSpawn(player);
    }
    public static void handle(PacketFirstSpawn msg, Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> {
            Main.proxy.handleClientBooleanPackets(0, msg.data);
        });
        ctx.get().setPacketHandled(true);
    }
}

 

Proxy:

public class ClientProxy extends CommonProxy {
	public void handleClientBooleanPackets(int id, boolean b) {
		IPlayerBaseCap basecap = Minecraft.getInstance().player.getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!"));
		switch(id) {
		case 0:
			basecap.setFirstSpawn(b);
		}
	}
	
	public void handleClientIntPackets(int id, int i) {
		IPlayerBaseCap basecap = Minecraft.getInstance().player.getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!"));
		switch(id) {
		case 0:
			basecap.setVillage(i);
		case 1:
			basecap.setClan(i);
		}
	}
}

What am I doing wrong?

Also, oddly enough firstspawn doesn't even need syncing for some reason, its default value is true but even without syncing it on those events it stays false after it gets set to false.

Edited by FlashHUN
marked as solved
Posted (edited)

Did some debugging, apparently the data I'm trying to send from the CapabilityStorage is the default value (0) for the village and clan tags, but only in the login event. Why could that be?

Edited by FlashHUN
Posted
57 minutes ago, diesieben07 said:

Why on earth is this static?

If it's not static, I'm getting an error at

	public static PacketFirstSpawn decode(PacketBuffer buf) {
    	return new PacketFirstSpawn(player);
    }

saying

Quote

Cannot make a static reference to the non-static field player

The two ways I can solve that error is by either making packets in a different way and send the needed data of the player in the constructor instead of sending the player and then getting the data from the player inside the packet

public class PacketClanC {
	private int data;

	public PacketClanC() {}
	
    public PacketClanC(int data) {
        this.data = data;
    }
    public static void encode(PacketClanC msg, PacketBuffer buf) {
        buf.writeInt(msg.data);
    }
    public static PacketClanC decode(PacketBuffer buf) {
    	int data = buf.readInt();
    	return new PacketClanC(data);
    }
    public static void handle(PacketClanC msg, Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> {
        	IPlayerBaseCap basecap = Minecraft.getInstance().player.getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!"));
        	basecap.setClan(msg.data);
        });
        ctx.get().setPacketHandled(true);
    }
}

or make that field static. Please tell me which way you think is better, I'm still new to this whole networking thing and just learning what would be the best way to handle things like this. Both ways work, but the PlayerLoggedInEvent still doesn't send the needed data.

 

1 hour ago, diesieben07 said:

Define "debugging".

By "debugging" I meant that I set the events and packets up in a way where I can see the data being sent from the event and received in the packet by writing it out. I think the problem occours in the PlayerLoggedInEvent, since the data being sent is 0 every time that event runs, but in every other event the data syncing is completely fine.

Posted
4 hours ago, diesieben07 said:
  • You do not need a no-argument constructor in your packet anymore.
  • The new way to handle the data and decoding is the only one that makes sense. Using a static field as a shared reference between server and client thread (which is what you did before) makes no logical sense, breaks outside singleplayer and also breaks in singleplayer with random, seemingly inexplicable and strange bugs (multithreading is hard!).

Thanks, I didn't know that.

4 hours ago, diesieben07 said:
  • How have you tested this?

I used a logger to print out the data being sent from the events and received in the packet. In both the respawn and change dimension events the data being sent and received is correct. In the PlayerLoggedInEvent the data being sent and received is 0.

Posted
44 minutes ago, diesieben07 said:

Is your NBT reading for the capability being called?

Not exactly sure what you mean by that, but this is how I set up and registered my capability:

Provider:

public class PlayerBaseCapProvider implements ICapabilitySerializable<INBT> {

	@CapabilityInject(IPlayerBaseCap.class)
	public static Capability<IPlayerBaseCap> PLAYER_BASE_CAP;
	
	private LazyOptional<IPlayerBaseCap> instance = LazyOptional.of(PLAYER_BASE_CAP::getDefaultInstance);
	
	@Override
	public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
		return cap == PLAYER_BASE_CAP ? instance.cast() : LazyOptional.empty();
	}

	@Override
	public INBT serializeNBT() {
		return PLAYER_BASE_CAP.getStorage().writeNBT(PLAYER_BASE_CAP, this.instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), null);
	}

	@Override
	public void deserializeNBT(INBT nbt) {
		PLAYER_BASE_CAP.getStorage().readNBT(PLAYER_BASE_CAP, this.instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), null, nbt);
	}

}

 

Storage:

public class PlayerBaseCapStorage implements IStorage<IPlayerBaseCap> {

	@Override
	public INBT writeNBT(Capability<IPlayerBaseCap> capability, IPlayerBaseCap instance, Direction side) {
		CompoundNBT tag = new CompoundNBT();
		
		tag.putBoolean("firstspawn", instance.getFirstSpawn());
		tag.putInt("village", instance.getVillage());
		tag.putInt("clan", instance.getClan());
		tag.putInt("rank", instance.getRank());
		tag.putInt("level", instance.getLevel());
		tag.putInt("exp", instance.getExp());
		tag.putInt("chakra", instance.getChakra());
		tag.putInt("maxchakra", instance.getMaxChakra());
		
		return tag;
	}

	@Override
	public void readNBT(Capability<IPlayerBaseCap> capability, IPlayerBaseCap instance, Direction side, INBT nbt) {
		CompoundNBT tag = new CompoundNBT();
		
		instance.setFirstSpawn(tag.getBoolean("firstspawn"));
		instance.setVillage(tag.getInt("village"));
		instance.setClan(tag.getInt("clan"));
		instance.setRank(tag.getInt("rank"));
		instance.setLevel(tag.getInt("level"));
		instance.setExp(tag.getInt("exp"));
		instance.setChakra(tag.getInt("chakra"));
		instance.setMaxChakra(tag.getInt("maxchakra"));
		
	}
	
	@Mod.EventBusSubscriber(modid = Main.modid)
    private static class EventHandler {
		
		@SubscribeEvent(priority = EventPriority.HIGHEST)
		public static void onAttachCapabilities(AttachCapabilitiesEvent<Entity> event) {
			if (event.getObject() instanceof PlayerEntity) {
				event.addCapability(new ResourceLocation(Main.modid, "base"), new PlayerBaseCapProvider());
			}
		}
		
		@SubscribeEvent
	    public static void playerClone(final PlayerEvent.Clone event) {
			final IPlayerBaseCap oldBaseCap = event.getOriginal().getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!"));
			final IPlayerBaseCap newBaseCap = event.getPlayer().getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!"));
			if (oldBaseCap != null && newBaseCap != null) {
				newBaseCap.setFirstSpawn(oldBaseCap.getFirstSpawn());
				newBaseCap.setVillage(oldBaseCap.getVillage());
				newBaseCap.setClan(oldBaseCap.getClan());
				newBaseCap.setRank(oldBaseCap.getRank());
				newBaseCap.setExp(oldBaseCap.getExp());
				newBaseCap.setLevel(oldBaseCap.getLevel());
				newBaseCap.setChakra(oldBaseCap.getChakra());
				newBaseCap.setMaxChakra(oldBaseCap.getMaxChakra());
			}
		}
		
		@SubscribeEvent
	    public static void serverLoginEvent(final PlayerLoggedInEvent event) {
			PlayerEntity player = event.getPlayer();
			IPlayerBaseCap basecap = player.getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!"));
			if (basecap != null) {
		    	Main.logger.info("Clan data sent from Storage: " + basecap.getClan());
		    	PacketDispatcher.INSTANCE.sendTo(new PacketFirstSpawn(basecap.getFirstSpawn()), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
		    	PacketDispatcher.INSTANCE.sendTo(new PacketVillageC(basecap.getVillage()), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
		    	PacketDispatcher.INSTANCE.sendTo(new PacketClanC(basecap.getClan()), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
		    	if (basecap.getFirstSpawn() == true) {
		    		basecap.setFirstSpawn(false);
		    		PacketDispatcher.INSTANCE.sendTo(new PacketFirstSpawn(basecap.getFirstSpawn()), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
		    		player.sendMessage(new TranslationTextComponent("msgs.firstjoin", ""));
		    		ItemStack stack = new ItemStack(ItemList.character_creation, 1);
		    		player.addItemStackToInventory(stack);
		    	}
			}
		}
		
		
		
		@SubscribeEvent
	    public static void changeDimesionEvent(final PlayerChangedDimensionEvent event) {
			PlayerEntity player = event.getPlayer();
			IPlayerBaseCap basecap = player.getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!"));

	    	PacketDispatcher.INSTANCE.sendTo(new PacketFirstSpawn(basecap.getFirstSpawn()), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    	PacketDispatcher.INSTANCE.sendTo(new PacketVillageC(basecap.getVillage()), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    	PacketDispatcher.INSTANCE.sendTo(new PacketClanC(basecap.getClan()), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
		}
		
		@SubscribeEvent
	    public static void respawnEvent(final PlayerRespawnEvent event) {
	    	PlayerEntity player = event.getPlayer();
	    	IPlayerBaseCap basecap = player.getCapability(PlayerBaseCapProvider.PLAYER_BASE_CAP).orElseThrow(() -> new RuntimeException("No player capability found!"));

	    	PacketDispatcher.INSTANCE.sendTo(new PacketFirstSpawn(basecap.getFirstSpawn()), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    	PacketDispatcher.INSTANCE.sendTo(new PacketVillageC(basecap.getVillage()), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
	    	PacketDispatcher.INSTANCE.sendTo(new PacketClanC(basecap.getClan()), ((ServerPlayerEntity)player).connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
		}
    }
}

 

Main:

@Mod("naruto")
public class Main {
	public static final String modid = "naruto";
	public static final Logger logger = LogManager.getLogger(modid);
	public Main() {
		FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
		MinecraftForge.EVENT_BUS.register(this);
	}

	private void setup(final FMLCommonSetupEvent event) {
		CapabilityManager.INSTANCE.register(IPlayerBaseCap.class, new PlayerBaseCapStorage(), PlayerBaseCap::new);
	}
}

 

Is there anything I'm doing wrong?

Posted
8 hours ago, diesieben07 said:

I mean you should verify (using the debugger!) that your NBT reading is called (preferably before the login event is fired).

I added this line in readNBT() in my capability storage,

Main.logger.debug("NBT Reading in Storage");

and this is the result:

Quote

[m[32m[18:56:28] [Netty Local Client IO #1/INFO] [ne.mi.fm.ne.NetworkHooks/]: Connected to a modded server.
[m[36m[18:56:29] [Server thread/DEBUG] [naruto/]: NBT Reading in Storage
[m[32m[18:56:29] [Server thread/INFO] [minecraft/PlayerList]: Dev[local:E:903188c3] logged in with entity id 36 at (50.290344437014184, 32.0, 97.11247292805938)
[m[32m[18:56:29] [Server thread/INFO] [minecraft/MinecraftServer]: Dev joined the game
[m[32m[18:56:29] [Server thread/INFO] [naruto/]: Clan data sent from Storage: 0
[m[32m[18:56:29] [Server thread/INFO] [minecraft/IntegratedServer]: Saving and pausing game...
[m[32m[18:56:29] [Server thread/INFO] [minecraft/MinecraftServer]: Saving chunks for level 'Superflat Testing'/minecraft:overworld
[m[32m[18:56:29] [Client thread/INFO] [naruto/]: Clan data received: 0
[m[32m[18:56:29] [Client thread/INFO] [minecraft/AdvancementList]: Loaded 151 advancements
[m[36m[18:56:29] [Server thread/DEBUG] [ne.mi.fm.FMLWorldPersistenceHook/WP]: Gathering id map for writing to world save Superflat Testing

 

This should mean that it's called before the login event, right? If so, then why is it not sending the data that was saved to the player?

Posted
On 10/18/2019 at 9:40 AM, FlashHUN said:

public void readNBT(Capability<IPlayerBaseCap> capability, IPlayerBaseCap instance, Direction side, INBT nbt) { CompoundNBT tag = new CompoundNBT();  instance.setFirstSpawn(tag.getBoolean("firstspawn"));

Because you are creating a new CompoundNBT and loading your data from there instead of using the INBT instance you are provided. Cast it to a CompoundNBT.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Posted
1 hour ago, Animefan8888 said:

Because you are creating a new CompoundNBT and loading your data from there instead of using the INBT instance you are provided. Cast it to a CompoundNBT.

Thank you so much for the solution!

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.