Jump to content

Recommended Posts

Posted

Hi,

 

I'm looking for an event that Forge is firing when a player connect to the server. Everything I found on Google is old stuffs ...

 

EDIT :

 

I found this : FMLServerAboutToStartEvent

It says "Called after FMLPostInitializationEvent on the dedicated server, and after the player has hit "Play Selected World" in the client", but I wanna be sure if this is also fired when connecting to a server.

 

Posted

No, that is only fired when the server initially starts.

 

You can subscribe to

PlayerEvent.PlayerLoggedInEvent

alt either

FMLNetworkEvent.ClientConnectedToServerEvent

or

FMLNetworkEvent.ServerConnectionFromClientEvent

.

ClientConnectedToServerEvent

is only fired on the client, and

ServerConnectionFromClientEvent

is thus, only fired on the server.

 

I've also heard that the

PlayerEvent.PlayerLoggedInEvent

requires you to wait a tick before doing anything, as the event is fired before the player-entity is created.

Also previously known as eAndPi.

"Pi, is there a station coming up where we can board your train of thought?" -Kronnn

Published Mods: Underworld

Handy links: Vic_'s Forge events Own WIP Tutorials.

Posted

How can I get the PlayerLoggedInEvent from ServerConnectionFromClientEvent ?

 

EDIT: Like this ?

 

@SubscribeEvent

public void onPlayerLoggedIn(PlayerLoggedInEvent event) {

    if (event.player.isServerWorld()) {

        EntityPlayerMP player = (EntityPlayerMP) event.player;

        ...

    }

}

Posted

How can I get the PlayerLoggedInEvent from ServerConnectionFromClientEvent ?

Those are 2 different events altogether. They both fire when the player connects to the server, but in different places.

 

Don't cast the Player to EntityPlayerMP or EntityPlayerSP unless you really do have to. Most if not all you really need exist in EntityPlayer already, which is what the event#player is.

Entity->EntityLivingBase->EntityPlayer-> [EntityPlayerSp | EntityPlayerMP]. SP/MP are the same thing, just on the opposite sides of the server/client coin.

 

If you only want to do something server-side, check if

event#player#worldObj#isRemote

returns false, and then do something, instead of checking

isServerWorld()

.

Also previously known as eAndPi.

"Pi, is there a station coming up where we can board your train of thought?" -Kronnn

Published Mods: Underworld

Handy links: Vic_'s Forge events Own WIP Tutorials.

Posted

I don't need ServerConnectionFromClientEvent then.

How can I check that the server is dedicated ? I want to exclude the integrated server case.

 

I need an EntityPlayerMP to call a method, so I have to cast, but I think it's safe if I checked on what side I am before.

Posted

Aaaaah. My bad then.

You can simply skip checking what side you are on, and focus directly on the player instead.

Your previous code-snippet should be fine to run, however, it is not explicitly safe.

If you are on a server, the player should be EntityPlayerMP, yes, however, you never actually check if the player IS EntityPlayer first.

You can cast classes to equal or super classes. You cannot cast it to another forked class like EntityPlayerMP/SP are.

 

You can simply check:

if(event.player instanceof EntityPlayerMP){
   EntityplayerMP player = (EntityPlayerMP) event.player;
   //Rest of your code.
}

That is explicitly safe casting. Only cast to what you know you are casting to.

Who knows, with the power of Java, pigs can easily fly. A mod spawning an EntityPlayerSP on a server wouldn't be too hard to imagine, bar for what possible reason.

Also previously known as eAndPi.

"Pi, is there a station coming up where we can board your train of thought?" -Kronnn

Published Mods: Underworld

Handy links: Vic_'s Forge events Own WIP Tutorials.

Posted

No.

 

There are always 2 sides. There is one Entity for each side.

Client + Integrated (also integrated LAN)

Client + Dedicated (or other non-integrated, like outside LAN).

 

EntityPlayer is a special Entity where Client thread uses AbstractClientPlayer (for EntityPlayer you control, Minecraft#thePlayer, it's EntityPlayerSP), server thread uses EntityPlayerMP.

So to answer your question - "if (player instanceof EntityPlayerMP)" is almost same check as "if (!World#isRemote)" - where remote means that code is ran on client (so negative is server). you can sue Entity#worldObj to check logical side.

More here: http://mcforge.readthedocs.io/en/latest/concepts/sides/

 

Now - you shouldn't create mods that are physical-side specific (meaning they work differently on dedic and integrated). It will get messy for a novice. If you are planning on writing sided mods you should be writing two mods such as one for ONLY dedic, and one for ONLY client.

Otherwise you should write universal mod (and for real - dedic and integrated is the same thing, so it's easier this way).

 

To solve your problem in best possible way - please describe the goal you are after, including on what side what should happen. Some of code/events are reserved for specific sides so it's important to state end-goal (like e.g: checking if server is dedic looks different for server and different for client that connects to it).

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

Posted

I probably should have explain the purpose of this at the beginning  ;D

The dedicated server must send some settings to the connected clients : recipes, block hardness and resistance ...

This is dedicated server behavior only, not integrated.

Posted

If you want your mod to be "universal" (keep it in one .jar), this is step by step on how I'd do it:

 

Events part:

1. Create DedicatedServerEvents.class. Mark it with @SideOnly(Side.SERVER).

2. @SubscribeEvent to PlayerLoggedInEvent in class above.

3. Register class above from ServerProxy (call during preInit).

4. At this point whenever mod is ran on dedicated server (so ServerProxy is fired), you will be firing event for all players that log in on this server.

 

Dedicated part:

1. In ServerProxy load (during preInit) your data from files (using forge config or configs of your design).

2. Place loaded data in @SideOnly(Side.SERVER) static storage - it could be for example Map<Block, Double> for block hardness or other ways for different values.

3. Use loaded data to change vanilla values. In mod's init (ServerProxy) call Block#setHardness and other methods you want and use data you loaded from config.

4. At this point whenever mod is ran on dedicated server (so ServerProxy is fired), you will be modifying vanilla properties with stuff loaded from configs while storing this data in static maps. @SideOnly also prevents those classes/fields from existing on Client.jar, so there is that.

 

Syncing stuff:

1. Create SimpleNetworkWrapper and proper IMessages (remember about thread safety).

2. In PlayerLoggedInEvent send data from server's static maps to client (serialize them into something and deserialize on receiving client).

3. On receiver client modify proper Blocks by puling them from registry by names (So e.g: in your packet you send arrays of stuff like: "modid:blockname"=5.0D).

 

This should work assuming vanilla allows such hot-modifications to hardness values.

 

Note that similar effects (for only some of block properties) can be achieved with HarvestSpeed (or whetever the name was) and some other events.

 

BIG NOTE: Mind EVERY word I wrote - each one of them is important as they directly describe possible design approach.

 

Questions?

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

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.