Clean up network logic

* Renamed BookNetowkr network to MantleNetwork, as I'd like this to be usable for things other than books if needed
* Replace abstract packet with an interface
* Reimplement threadsafe packet
* Simplify registration methods
* Require a network direction on registation, to filter packets into client only/server only
This commit is contained in:
KnightMiner committed 2020-07-24 12:09:56 -05:00
1 parent bdf1f11a03
commit 8b8f979a4f
12 files changed
+193 -142

No files matched your search

@@ -8,8 +8,8 @@ import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import slimeknights.mantle.network.BookNetwork;
import slimeknights.mantle.client.ClientEvents;
import slimeknights.mantle.network.MantleNetwork;
/**
* Mantle
@@ -35,7 +35,7 @@ public class Mantle {
}
private void commonSetup(final FMLCommonSetupEvent event) {
BookNetwork.registerPackets();
MantleNetwork.registerPackets();
}
/**
@@ -28,8 +28,8 @@ import slimeknights.mantle.client.book.data.content.ContentTextRightImage;
import slimeknights.mantle.client.book.data.content.PageContent;
import slimeknights.mantle.client.book.data.deserializer.HexStringDeserializer;
import slimeknights.mantle.client.book.repository.BookRepository;
import slimeknights.mantle.network.BookNetwork;
import slimeknights.mantle.network.book.UpdateSavedPagePacket;
import slimeknights.mantle.network.MantleNetwork;
import slimeknights.mantle.network.packet.UpdateSavedPagePacket;
import javax.annotation.Nullable;
import java.util.HashMap;
@@ -138,7 +138,7 @@ public class BookLoader implements IResourceManagerReloadListener {
}
BookHelper.writeSavedPage(item, page);
BookNetwork.wrapper.network.sendToServer(new UpdateSavedPagePacket(page));
MantleNetwork.INSTANCE.network.sendToServer(new UpdateSavedPagePacket(page));
}
/**
@@ -1,29 +0,0 @@
package slimeknights.mantle.network;
import io.netty.buffer.ByteBuf;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.network.NetworkEvent;
import java.util.function.Supplier;
public abstract class AbstractPacket {
public abstract void encode(PacketBuffer buf);
public abstract void handle(Supplier<NetworkEvent.Context> context);
protected void writePos(BlockPos pos, ByteBuf buf) {
buf.writeInt(pos.getX());
buf.writeInt(pos.getY());
buf.writeInt(pos.getZ());
}
protected BlockPos readPos(ByteBuf buf) {
int x = buf.readInt();
int y = buf.readInt();
int z = buf.readInt();
return new BlockPos(x, y, z);
}
}
@@ -1,40 +0,0 @@
package slimeknights.mantle.network;
import net.minecraft.client.network.play.ClientPlayNetHandler;
import net.minecraft.network.play.ServerPlayNetHandler;
/**
* Threadsafe integration of the abstract packet.
* Basically if you're doing something that has any influence on the world you should use this.
* (That's ~everything)
*/
public abstract class AbstractPacketThreadsafe extends AbstractPacket {
//TODO fix!
/*
@Override
public final IMessage handleClient(final ClientPlayNetHandler netHandler) {
FMLCommonHandler.instance().getWorldThread(netHandler).addScheduledTask(new Runnable() {
@Override
public void run() {
handleClientSafe(netHandler);
}
});
return null;
}
@Override
public final IMessage handleServer(final ServerPlayNetHandler netHandler) {
FMLCommonHandler.instance().getWorldThread(netHandler).addScheduledTask(new Runnable() {
@Override
public void run() {
handleServerSafe(netHandler);
}
});
return null;
}
public abstract void handleClientSafe(ClientPlayNetHandler netHandler);
public abstract void handleServerSafe(ServerPlayNetHandler netHandler);*/
}
@@ -1,12 +0,0 @@
package slimeknights.mantle.network;
import slimeknights.mantle.network.book.UpdateSavedPagePacket;
public class BookNetwork {
public static final NetworkWrapper wrapper = new NetworkWrapper("mantle:books");
public static void registerPackets() {
wrapper.registerPacket(UpdateSavedPagePacket.class, UpdateSavedPagePacket::encode, UpdateSavedPagePacket::new, UpdateSavedPagePacket::handle);
}
}
@@ -0,0 +1,18 @@
package slimeknights.mantle.network;
import net.minecraftforge.fml.network.NetworkDirection;
import slimeknights.mantle.Mantle;
import slimeknights.mantle.network.packet.FluidUpdatePacket;
import slimeknights.mantle.network.packet.UpdateSavedPagePacket;
public class MantleNetwork {
/** Network instance */
public static final NetworkWrapper INSTANCE = new NetworkWrapper(Mantle.getResource("network"));
/**
* Registers packets into this network
*/
public static void registerPackets() {
INSTANCE.registerPacket(UpdateSavedPagePacket.class, UpdateSavedPagePacket::new, NetworkDirection.PLAY_TO_SERVER);
}
}
@@ -1,14 +1,23 @@
package slimeknights.mantle.network;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.network.IPacket;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.fml.network.NetworkDirection;
import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.network.NetworkEvent.Context;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.PacketDistributor;
import net.minecraftforge.fml.network.simple.SimpleChannel;
import slimeknights.mantle.network.packet.ISimplePacket;
import javax.annotation.Nullable;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -17,31 +26,98 @@ import java.util.function.Supplier;
* A small network implementation/wrapper using AbstractPackets instead of IMessages.
* Instantiate in your mod class and register your packets accordingly.
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class NetworkWrapper {
/** Network instance */
public final SimpleChannel network;
private int id = 0;
private static final String PROTOCOL_VERSION = Integer.toString(1);
public NetworkWrapper(String channelName) {
this.network = NetworkRegistry.ChannelBuilder.named(new ResourceLocation(channelName))
/**
* Creates a new network wrapper
* @param channelName Unique packet channel name
*/
public NetworkWrapper(ResourceLocation channelName) {
this.network = NetworkRegistry.ChannelBuilder.named(channelName)
.clientAcceptedVersions(PROTOCOL_VERSION::equals)
.serverAcceptedVersions(PROTOCOL_VERSION::equals)
.networkProtocolVersion(() -> PROTOCOL_VERSION)
.simpleChannel();
}
public <MSG> void registerPacket(Class<MSG> packetClazz, BiConsumer<MSG, PacketBuffer> encoder, Function<PacketBuffer, MSG> decoder, BiConsumer<MSG, Supplier<NetworkEvent.Context>> messageConsumer) {
this.network.registerMessage(this.id++, packetClazz, encoder, decoder, messageConsumer);
/**
* Registers a new {@link ISimplePacket}
* @param clazz Packet class
* @param decoder Packet decoder, typically the constructor
* @param <MSG> Packet class type
*/
public <MSG extends ISimplePacket> void registerPacket(Class<MSG> clazz, Function<PacketBuffer, MSG> decoder, @Nullable NetworkDirection direction) {
registerPacket(clazz, ISimplePacket::encode, decoder, ISimplePacket::handle, direction);
}
/**
* Registers a new generic packet
* @param clazz Packet class
* @param encoder Encodes a packet to the buffer
* @param decoder Packet decoder, typically the constructor
* @param consumer Logic to handle a packet
* @param direction Network direction for validation. Pass null for no direction
* @param <MSG> Packet class type
*/
public <MSG> void registerPacket(Class<MSG> clazz, BiConsumer<MSG, PacketBuffer> encoder, Function<PacketBuffer, MSG> decoder, BiConsumer<MSG,Supplier<Context>> consumer, @Nullable NetworkDirection direction) {
this.network.registerMessage(this.id++, clazz, encoder, decoder, consumer, Optional.ofNullable(direction));
}
/* Sending packets */
/**
* Sends a packet to the server
* @param msg Packet to send
*/
public void sendToServer(Object msg) {
this.network.sendToServer(msg);
}
public void sendTo(Object msg, ServerPlayerEntity player) {
if (!(player instanceof FakePlayer)) {
this.network.sendTo(msg, player.connection.netManager, NetworkDirection.PLAY_TO_CLIENT);
/**
* Sends a packet to the given packet distributor
* @param target Packet target
* @param message Packet to send
*/
public void send(PacketDistributor.PacketTarget target, Object message) {
network.send(target, message);
}
/**
* Sends a vanilla packet to the given entity
* @param player Player receiving the packet
* @param packet Packet
*/
public void sendVanillaPacket(IPacket<?> packet, Entity player) {
if (player instanceof ServerPlayerEntity && ((ServerPlayerEntity) player).connection != null) {
((ServerPlayerEntity) player).connection.sendPacket(packet);
}
}
/**
* Sends a packet to a player
* @param msg Packet
* @param player Player to send
*/
public void sendTo(Object msg, ServerPlayerEntity player) {
if (!(player instanceof FakePlayer)) {
network.sendTo(msg, player.connection.netManager, NetworkDirection.PLAY_TO_CLIENT);
}
}
/**
* Sends a packet to players near a location
* @param msg Packet to send
* @param serverWorld World instance
* @param position Position within range
*/
public void sendToClientsAround(Object msg, ServerWorld serverWorld, BlockPos position) {
Chunk chunk = serverWorld.getChunkAt(position);
network.send(PacketDistributor.TRACKING_CHUNK.with(() -> chunk), msg);
}
}
@@ -1,46 +0,0 @@
package slimeknights.mantle.network.book;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.Hand;
import net.minecraftforge.fml.network.NetworkEvent;
import slimeknights.mantle.client.book.BookHelper;
import slimeknights.mantle.network.AbstractPacket;
import java.util.function.Supplier;
public class UpdateSavedPagePacket extends AbstractPacket {
private String pageName;
public UpdateSavedPagePacket(String pageName) {
this.pageName = pageName;
}
public UpdateSavedPagePacket(PacketBuffer buffer) {
this.pageName = buffer.readString(32767);
}
@Override
public void encode(PacketBuffer buf) {
buf.writeString(this.pageName);
}
@Override
public void handle(Supplier<NetworkEvent.Context> context) {
context.get().enqueueWork(() -> {
if (context.get().getSender() != null && this.pageName != null) {
PlayerEntity player = context.get().getSender();
if (player != null) {
ItemStack is = player.getHeldItem(Hand.MAIN_HAND);
if (!is.isEmpty()) {
BookHelper.writeSavedPage(is, this.pageName);
}
}
}
});
context.get().setPacketHandled(true);
}
}
@@ -0,0 +1,23 @@
package slimeknights.mantle.network.packet;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.network.NetworkEvent;
import java.util.function.Supplier;
/**
* Packet interface to add common methods for registration
*/
public interface ISimplePacket {
/**
* Encodes a packet for the buffer
* @param buf Buffer instance
*/
void encode(PacketBuffer buf);
/**
* Handles receiving the packet
* @param context Packet context
*/
void handle(Supplier<NetworkEvent.Context> context);
}
@@ -0,0 +1,24 @@
package slimeknights.mantle.network.packet;
import net.minecraftforge.fml.network.NetworkEvent;
import java.util.function.Supplier;
/**
* Packet instance that automatically wraps the logic in {@link NetworkEvent.Context#enqueueWork(Runnable)} for thread safety
*/
public interface IThreadsafePacket extends ISimplePacket {
@Override
default void handle(Supplier<NetworkEvent.Context> supplier) {
NetworkEvent.Context context = supplier.get();
context.enqueueWork(() -> handleThreadsafe(context));
context.setPacketHandled(true);
}
/**
* Handles receiving the packet on the correct thread
* Packet is automatically set to handled as well by the base logic
* @param context Packet context
*/
void handleThreadsafe(NetworkEvent.Context context);
}
@@ -0,0 +1,37 @@
package slimeknights.mantle.network.packet;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.Hand;
import net.minecraftforge.fml.network.NetworkEvent.Context;
import slimeknights.mantle.client.book.BookHelper;
public class UpdateSavedPagePacket implements IThreadsafePacket {
private String pageName;
public UpdateSavedPagePacket(String pageName) {
this.pageName = pageName;
}
public UpdateSavedPagePacket(PacketBuffer buffer) {
this.pageName = buffer.readString(32767);
}
@Override
public void encode(PacketBuffer buf) {
buf.writeString(this.pageName);
}
@Override
public void handleThreadsafe(Context context) {
PlayerEntity player = context.getSender();
if (player != null && this.pageName != null) {
ItemStack is = player.getHeldItem(Hand.MAIN_HAND);
if (!is.isEmpty()) {
BookHelper.writeSavedPage(is, this.pageName);
}
}
}
}
@@ -1,6 +1,6 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
package slimeknights.mantle.network.book;
package slimeknights.mantle.network.packet;
import mcp.MethodsReturnNonnullByDefault;