Jump to content

Recommended Posts

Posted

It seems to me there are a couple of common situations that many mod developers may face, with respect to the whole client/server side issue:

  1. You have code on the client side that needs to spawn an entity (which must be done on the server side).
  2. You have code on the client side that wants to trigger an explosion (which should also be done on the server side).
  3. Or more generally, you have code on the client side that wants to modify the world, e.g. change blocks (which also must be done on the server).

These are sufficiently general and common cases that a library could do it for us — that is, prepare a packet, send it to the server, and have the server catch it and do the appropriate thing.

Before I start in on such utility code myself, are there any cases where the framework already does something like this for us?  Where?

If not, are there any common open-source solutions to this already written?

 

Posted

Yes, it is called minecraft.

You seem to be under the inital false understanding that any of that should be triggered by the client doing anything.

Unless you're explicitly doing it from a GUI, and even in that case you should use the generic button click handlers and the like to talk to the server.

None of this logic should touch any client side code.

I do Forge for free, however the servers to run it arn't free, so anything is appreciated.
Consider supporting the team on Patreon

Posted

Well as a concrete example of situation 1, I've got some custom mouse-button handling (and yes, I tried the built-in click handlers on the Item class, but (1) they didn't do what I need, and (2) those handlers also run on the client thread).  And in response to that mouse input — which obviously the server doesn't know anything about — I need to spawn a projectile.

I find it hard to believe that this situation is unique.

So I'm going to interpret your answer as "no" (there is no built-in support for that in the framework), and "no" (you don't know any standard open-source solution for it).

No big deal — I've already got the necessary networking code implemented for one case, and it won't take long to add the others.  Just wanted to avoid reinventing the wheel if there was a well-oiled wheel already available.

 

(But I do hear and respect your point that in most cases, Minecraft is already interpreting all the client input and sending higher-level events to the server, and we should our custom logic on the server in response to those events as much as possible.)

Posted

Hey,

 

The first two should really be done from the server (spawning an entity client-side can lead to phantom entities... and running an explosion client side lead to phantom client-side holes since the random number generator on the server doesn't always break the same blocks). If you have something spawning a mob or explosion from the client, it would probably be best to send a custom packet over to the server with info about what mob you want to spawn or about the explosion. I don't think there are vanilla packets for that, but I could be wrong.

 

The third has a vanilla packet. I remember recently using it to create a hammer-like tool that has some custom block-breaking logic. Check out tryHarvestBlock in PlayerInteractionManager, it's sending a SPacketBlockChange packet on line 337 or so.

  • Like 1
Posted (edited)

Thank you.

In case it's useful to anyone, here's the networking code I came up with (based on the docs) to create an explosion or spawn a projectile on the server.  (Unfortunately the "spawn a projectile" code is not generic — it's tied to a particular class, in this case a custom Throwable subclass called EntitySpell.  But perhaps it will be useful as sample code anyway.)

 

package net.strout.wizarding;

import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.math.*;
import net.minecraft.world.WorldServer;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.*;
import net.minecraftforge.fml.relauncher.Side;

public class ClientToServerBridge {

	private static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel(ModMain.MODID);
	private static int nextHandlerRegistrationID = 0;
	private static boolean initialized;
	
	public static class TriggerExplosionMessage implements IMessage {
		// A default constructor is always required
		public TriggerExplosionMessage() {}

		private BlockPos position;
		private float strength;
		private boolean smoke;
		
		public TriggerExplosionMessage(BlockPos position, float strength, boolean smoke) {
			this.position = position;
			this.strength = strength;
			this.smoke = smoke;
		}

		@Override public void toBytes(ByteBuf buf) {
			buf.writeInt(position.getX());
			buf.writeInt(position.getY());
			buf.writeInt(position.getZ());
			buf.writeFloat(strength);
			buf.writeBoolean(smoke);
		}

		@Override public void fromBytes(ByteBuf buf) {
			position = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt());
			strength = buf.readFloat();
			smoke = buf.readBoolean();
		}
	}
	
	// The params of the IMessageHandler are <REQUEST, REPLY>
	// This means that the first param is the packet you are receiving, and the second is the packet you are returning.
	// The returned packet can be used as a "response" from a sent packet.
	public static class TriggerExplosionHandler implements IMessageHandler<TriggerExplosionMessage, IMessage> {
		@Override public IMessage onMessage(TriggerExplosionMessage message, MessageContext ctx) {
			System.out.println("Received TriggerExplosionMessage");
			// This is the player the packet was sent to the server from
			EntityPlayerMP serverPlayer = ctx.getServerHandler().player;
			// Execute the action on the main server thread by adding it as a scheduled task
			WorldServer world = serverPlayer.getServerWorld();
			if (!world.isBlockLoaded(message.position)) return null;
			System.out.println("Scheduling explosion on main thread");
			world.addScheduledTask(() -> {
				System.out.println("Creating explosion");
				world.createExplosion(serverPlayer, 
						message.position.getX(),
						message.position.getY(),
						message.position.getZ(),
						message.strength, message.smoke);
			});
			// No response packet
			return null;
		}
	}
	
	
	public static class SpawnSpellMessage implements IMessage {
		// A default constructor is always required
		public SpawnSpellMessage() {}

		private Vec3d position;
		private Vec3d direction;
		
		public SpawnSpellMessage(Vec3d position, Vec3d direction) {
			this.position = position;
			this.direction = direction;
		}

		@Override public void toBytes(ByteBuf buf) {
			buf.writeFloat((float)position.x);
			buf.writeFloat((float)position.y);
			buf.writeFloat((float)position.z);
			buf.writeFloat((float)direction.x);
			buf.writeFloat((float)direction.y);
			buf.writeFloat((float)direction.z);
		}

		@Override public void fromBytes(ByteBuf buf) {
			position = new Vec3d(buf.readFloat(), buf.readFloat(), buf.readFloat());
			direction = new Vec3d(buf.readFloat(), buf.readFloat(), buf.readFloat());
		}
	}
	
	// The params of the IMessageHandler are <REQUEST, REPLY>
	// This means that the first param is the packet you are receiving, and the second is the packet you are returning.
	// The returned packet can be used as a "response" from a sent packet.
	public static class SpawnSpellHandler implements IMessageHandler<SpawnSpellMessage, IMessage> {
		@Override public IMessage onMessage(SpawnSpellMessage message, MessageContext ctx) {
			System.out.println("Received SpawnSpellMessage");
			// This is the player the packet was sent to the server from
			EntityPlayerMP serverPlayer = ctx.getServerHandler().player;
			// Execute the action on the main server thread by adding it as a scheduled task
			WorldServer world = serverPlayer.getServerWorld();
			if (!world.isBlockLoaded(new BlockPos(message.position))) return null;
			System.out.println("Scheduling spawning on main thread");
			world.addScheduledTask(() -> {
				System.out.println("Spawning spell");
				EntitySpell.Spawn(world, serverPlayer, message.position, message.direction);
			});
			// No response packet
			return null;
		}
	}
	
	
	//--------------------------------------------------------------------------------
	// Public API
	//--------------------------------------------------------------------------------
	
	// Initialize: call this once on startup (for example, in your pre-init handler)
	// on both client and server.
	public static void Initialize() {
		assert(!initialized);
		INSTANCE.registerMessage(TriggerExplosionHandler.class, TriggerExplosionMessage.class, nextHandlerRegistrationID++, Side.SERVER);
		INSTANCE.registerMessage(SpawnSpellHandler.class, SpawnSpellMessage.class, nextHandlerRegistrationID++, Side.SERVER);
		System.out.println("ClientToServer module registered " + nextHandlerRegistrationID + " message handlers");
		initialized = true;
	}
	
	// TriggerExplosion: call to trigger an explosion on the server from client code.
	public static void TriggerExplosion(BlockPos position, float strength, boolean smoke) {
		assert(initialized);
		System.out.println("Sending TriggerExplosionMessage message to server");
		INSTANCE.sendToServer(new TriggerExplosionMessage(position, strength, smoke));		
	}
	
	// SpawnSpell: call to spawn an EntitySpell on the server from client code.
	public static void SpawnSpell(Vec3d position, Vec3d direction) {
		assert(initialized);
		System.out.println("Sending SpawnSpell message to server");
		INSTANCE.sendToServer(new SpawnSpellMessage(position, direction));				
	}
}

 

Edited by JoeStrout
added link to docs

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

    • When I first heard about Bitcoin back in 2018, I was skeptical. The idea of a decentralized, digital currency seemed too good to be true. But I was intrigued as I learned more about the technology behind it and its potential. I started small, investing just a few hundred dollars, dipping my toes into the cryptocurrency waters. At first, it was exhilarating to watch the value of my investment grow exponentially. I felt like I was part of the future, an early adopter of this revolutionary new asset. But that euphoria was short-lived. One day, I logged into my digital wallet only to find it empty - my Bitcoin had vanished without a trace. It turned out that the online exchange I had trusted had been hacked, and my funds were stolen. I was devastated, both financially and emotionally. All the potential I had seen in Bitcoin was tainted by the harsh reality that with decentralization came a lack of regulation and oversight. My hard-earned money was gone, lost to the ether of the digital world. This experience taught me a painful lesson about the price of trust in the uncharted territory of cryptocurrency. While the technology holds incredible promise, the risks can be catastrophic if you don't approach it with extreme caution. My Bitcoin investment gamble had failed, and I was left to pick up the pieces, wiser but poorer for having placed my faith in the wrong hands. My sincere appreciation goes to MUYERN TRUST HACKER. You are my hero in recovering my lost funds. Send a direct m a i l ( muyerntrusted ( @ ) mail-me ( . )c o m ) or message on whats app : + 1 ( 4-4-0 ) ( 3 -3 -5 ) ( 0-2-0-5 )
    • You could try posting a log (if there is no log at all, it may be the launcher you are using, the FAQ may have info on how to enable the log) as described in the FAQ, however this will probably need to be reported to/remedied by the mod author.
    • So me and a couple of friends are playing with a shitpost mod pack and one of the mods in the pack is corail tombstone and for some reason there is a problem with it, where on death to fire the player will get kicked out of the server and the tombstone will not spawn basically deleting an entire inventory, it doesn't matter what type of fire it is, whether it's from vanilla fire/lava, or from modded fire like ice&fire/lycanites and it's common enough to where everyone on the server has experienced at least once or twice and it doesn't give any crash log. a solution to this would be much appreciated thank you!
    • It is 1.12.2 - I have no idea if there is a 1.12 pack
  • Topics

×
×
  • Create New...

Important Information

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