Some beginnings of a network again.

This commit is contained in:
cpw 2018-06-22 00:43:25 -04:00 committed by LexManos
parent d0ab0e166c
commit 4636365e30
21 changed files with 433 additions and 75 deletions

View file

@ -19,6 +19,7 @@
package net.minecraftforge.common;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.biome.Biome;
import static net.minecraftforge.common.config.Configuration.CATEGORY_CLIENT;
@ -29,12 +30,11 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.minecraftforge.fml.ModLoadingClassLoader;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.SidedExecutor;
import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.fml.WorldPersistenceHooks;
import net.minecraftforge.fml.javafmlmod.FMLModContainer;
import net.minecraftforge.fml.javafmlmod.ModLoadingContext;
import net.minecraftforge.fml.loading.DefaultModInfos;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@ -59,12 +59,9 @@ import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.fluids.UniversalBucket;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.RecipeSorter;
import net.minecraftforge.server.command.ForgeCommand;
import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent;
import net.minecraftforge.fml.common.event.FMLModIdMappingEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
@ -73,10 +70,14 @@ import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.event.FMLServerStoppingEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
{
public static final String VERSION_CHECK_CAT = "version_checking";
private static final Logger LOGGER = LogManager.getLogger("FML");
private static final Marker FORGEMOD = MarkerManager.getMarker("FORGEMOD");
public static int clumpingThreshold = 64;
public static boolean removeErroringEntities = false;
public static boolean removeErroringTileEntities = false;
@ -107,7 +108,6 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
return INSTANCE;
}
private URL updateJSONUrl = null;
public UniversalBucket universalBucket;
public ForgeMod()
@ -116,6 +116,9 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
ModLoadingContext.get().getModEventBus().addListener(this::preInit);
ModLoadingContext.get().getModEventBus().addListener(this::postInit);
ModLoadingContext.get().getModEventBus().addListener(this::onAvailable);
MinecraftForge.EVENT_BUS.addListener(this::serverStarting);
MinecraftForge.EVENT_BUS.addListener(this::playerLogin);
MinecraftForge.EVENT_BUS.addListener(this::serverStopping);
}
public static Configuration getConfig()
@ -128,7 +131,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
ConfigCategory GENERAL = config.getCategory(CATEGORY_GENERAL);
if (GENERAL.containsKey(key))
{
FMLLog.log.debug("Remapping property {} from category general to client", key);
LOGGER.debug(FORGEMOD, "Remapping property {} from category general to client",key);
Property property = GENERAL.get(key);
GENERAL.remove(key);
config.getCategory(CATEGORY_CLIENT).put(key, property);
@ -205,7 +208,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
if (removeErroringEntities)
{
FMLLog.log.warn("Enabling removal of erroring Entities - USE AT YOUR OWN RISK");
LOGGER.warn(FORGEMOD, "Enabling removal of erroring Entities - USE AT YOUR OWN RISK");
}
prop = config.get(Configuration.CATEGORY_GENERAL, "removeErroringTileEntities", false);
@ -216,7 +219,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
if (removeErroringTileEntities)
{
FMLLog.log.warn("Enabling removal of erroring Tile Entities - USE AT YOUR OWN RISK");
LOGGER.warn(FORGEMOD, "Enabling removal of erroring Tile Entities - USE AT YOUR OWN RISK");
}
prop = config.get(Configuration.CATEGORY_GENERAL, "fullBoundingBoxLadders", false);
@ -333,7 +336,10 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
if (event.isWorldRunning() && tmpStairs != disableStairSlabCulling)
{
FMLCommonHandler.instance().reloadRenderers();
SidedExecutor.runOn(Dist.CLIENT,()->{
Minecraft.getMinecraft().renderGlobal.loadRenderers();
return null;
});
}
}
@ -411,13 +417,11 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
FluidRegistry.validateFluidRegistry();
}
@SubscribeEvent
public void serverStarting(FMLServerStartingEvent evt)
{
evt.registerServerCommand(new ForgeCommand());
}
@SubscribeEvent
public void serverStopping(FMLServerStoppingEvent evt)
{
WorldWorkerManager.clear();
@ -445,7 +449,11 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
OreDictionary.rebakeMap();
StatList.reinit();
Ingredient.invalidateAll();
FMLCommonHandler.instance().reloadSearchTrees();
SidedExecutor.runOn(Dist.CLIENT, ()-> {
Minecraft.getMinecraft().populateSearchTreeManager();
Minecraft.getMinecraft().getSearchTreeManager().onResourceManagerReload(Minecraft.getMinecraft().getResourceManager());
return null;
});
}
@Override

View file

@ -19,14 +19,10 @@
package net.minecraftforge.common;
import static net.minecraftforge.common.ForgeVersion.Status.*;
import net.minecraftforge.fml.VersionChecker;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraftforge.fml.common.InjectedModContainer;
import javax.annotation.Nullable;
public class ForgeVersion

View file

@ -36,6 +36,10 @@ import net.minecraft.item.ItemStack;
import net.minecraftforge.common.ForgeHooks.SeedEntry;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.oredict.OreDictionary;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import javax.annotation.Nonnull;
@ -52,9 +56,10 @@ public class MinecraftForge
public static final IEventBus EVENT_BUS = IEventBus.create();
public static final IEventBus TERRAIN_GEN_BUS = IEventBus.create();
public static final IEventBus ORE_GEN_BUS = IEventBus.create();
public static final String MC_VERSION = Loader.MC_VERSION;
static final ForgeInternalHandler INTERNAL_HANDLER = new ForgeInternalHandler();
private static final Logger LOGGER = LogManager.getLogger("FML");
private static final Marker FORGE = MarkerManager.getMarker("FORGE");
/**
* Register a new seed to be dropped when breaking tall grass.
@ -79,7 +84,7 @@ public class MinecraftForge
*/
public static void initialize()
{
FMLLog.log.info("MinecraftForge v{} Initialized", ForgeVersion.getVersion());
LOGGER.info(FORGE,"MinecraftForge v{} Initialized", ForgeVersion.getVersion());
OreDictionary.getOreName(0);

View file

@ -26,20 +26,17 @@ import net.minecraft.network.login.server.SPacketDisconnect;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent;
import net.minecraftforge.fml.common.event.FMLServerStartedEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.event.FMLServerStoppedEvent;
import net.minecraftforge.fml.common.event.FMLServerStoppingEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.network.NetworkHooks;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
@ -119,7 +116,7 @@ public class ServerLifecycleHooks
return false;
}
manager.channel().attr(NetworkRegistry.FML_MARKER).set(packet.getFMLVersion());
NetworkHooks.registerServerChannel(manager, packet);
return true;
}

View file

@ -583,7 +583,7 @@ public class FMLCommonHandler
return false;
}
manager.channel().attr(NetworkRegistry.FML_MARKER).set(packet.hasFMLMarker());
manager.channel().attr(net.minecraftforge.fml.network.NetworkRegistry.FML_MARKER).set(packet.hasFMLMarker());
return true;
}

View file

@ -69,7 +69,6 @@ public class NetworkRegistry
public static final AttributeKey<LogicalSide> CHANNEL_SOURCE = AttributeKey.valueOf("fml:channelSource");
public static final AttributeKey<ModContainer> MOD_CONTAINER = AttributeKey.valueOf("fml:modContainer");
public static final AttributeKey<INetHandler> NET_HANDLER = AttributeKey.valueOf("fml:netHandler");
public static final AttributeKey<String> FML_MARKER = AttributeKey.valueOf("fml:versionMarker");
// Version 1: ServerHello only contains this value as a byte
// Version 2: ServerHello additionally contains a 4 byte (int) dimension for the logging in client

View file

@ -142,7 +142,7 @@ public class NetworkDispatcher extends SimpleChannelInboundHandler<Packet<?>> im
public void serverToClientHandshake(EntityPlayerMP player)
{
this.player = player;
Boolean fml = this.manager.channel().attr(NetworkRegistry.FML_MARKER).get();
Boolean fml = this.manager.channel().attr(net.minecraftforge.fml.network.NetworkRegistry.FML_MARKER).get();
if (fml != null && fml)
{
//FML on client, send server hello

View file

@ -20,7 +20,7 @@
package net.minecraftforge.fml.common.network.simpleimpl;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.network.simple.MessageContext;
/**
* A message handler based on {@link IMessage}. Implement and override {@link #onMessage(IMessage, MessageContext)} to

View file

@ -20,7 +20,7 @@
package net.minecraftforge.fml.common.network.simpleimpl;
import net.minecraftforge.api.distmarker.Dist;
import org.apache.logging.log4j.Level;
import net.minecraftforge.fml.network.simple.MessageContext;
import net.minecraft.network.INetHandler;
import net.minecraftforge.fml.common.FMLLog;

View file

@ -1,25 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.loading.moddiscovery;
public interface IScanPlugin
{
public
}

View file

@ -19,7 +19,23 @@
package net.minecraftforge.fml.network;
import java.util.Arrays;
import java.util.Objects;
public enum ConnectionType
{
MODDED, BUKKIT, VANILLA
MODDED(NetworkHooks.NETVERSION), VANILLA(NetworkHooks.NOVERSION);
private final String versionString;
ConnectionType(String versionString)
{
this.versionString = versionString;
}
public static ConnectionType forVersionFlag(String vers)
{
return Arrays.stream(values()).filter(ct->Objects.equals(ct.versionString, vers)).
findFirst().orElse(ConnectionType.VANILLA);
}
}

View file

@ -21,9 +21,13 @@ package net.minecraftforge.fml.network;
import net.minecraft.entity.Entity;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.handshake.client.C00Handshake;
import net.minecraftforge.fml.common.network.internal.FMLMessage;
import net.minecraft.network.play.client.CPacketCustomPayload;
import net.minecraft.network.play.server.SPacketCustomPayload;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import java.util.Objects;
@ -44,7 +48,7 @@ public class NetworkHooks
public static ConnectionType getConnectionType(final NetHandlerPlayServer connection)
{
return ConnectionType.MODDED;
return ConnectionType.forVersionFlag(connection.netManager.channel().attr(NetworkRegistry.FML_MARKER).get());
}
public static Packet<?> getEntitySpawningPacket(Entity entity)
@ -56,4 +60,29 @@ public class NetworkHooks
}
return null;
}
public static void onServerCustomPayload(final SPacketCustomPayload packet, final NetworkManager manager) {
NetworkRegistry.findTarget(new ResourceLocation(packet.getChannelName())).
ifPresent(ni->ni.dispatch(NetworkInstance.NetworkSide.PLAYSERVER, packet.getBufferData(), manager));
}
public static void onClientCustomPayload(final CPacketCustomPayload packet, final NetworkManager manager) {
NetworkRegistry.findTarget(new ResourceLocation(packet.getChannelName())).
ifPresent(ni->ni.dispatch(NetworkInstance.NetworkSide.PLAYCLIENT, packet.getBufferData(), manager));
}
public static void onServerLoginCustomPayload(final SPacketCustomPayload packet, final NetworkManager manager) {
NetworkRegistry.findTarget(new ResourceLocation(packet.getChannelName())).
ifPresent(ni->ni.dispatch(NetworkInstance.NetworkSide.LOGINSERVER, packet.getBufferData(), manager));
}
public static void onClientLoginCustomPayload(final CPacketCustomPayload packet, final NetworkManager manager) {
NetworkRegistry.findTarget(new ResourceLocation(packet.getChannelName())).
ifPresent(ni->ni.dispatch(NetworkInstance.NetworkSide.LOGINCLIENT, packet.getBufferData(), manager));
}
public static void registerServerChannel(NetworkManager manager, C00Handshake packet)
{
manager.channel().attr(NetworkRegistry.FML_MARKER).set(packet.getFMLVersion());
}
}

View file

@ -0,0 +1,129 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.network;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.IEventListener;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class NetworkInstance
{
public String getChannelName()
{
return channelName.toString();
}
public enum NetworkSide {
PLAYSERVER(NetworkEvent.ServerCustomPayloadEvent::new),
PLAYCLIENT(NetworkEvent.ClientCustomPayloadEvent::new),
LOGINSERVER(NetworkEvent.ServerCustomPayloadEvent::new),
LOGINCLIENT(NetworkEvent.ClientCustomPayloadEvent::new);
private final BiFunction<PacketBuffer, NetworkManager, NetworkEvent> eventSupplier;
NetworkSide(BiFunction<PacketBuffer, NetworkManager, NetworkEvent> eventSupplier)
{
this.eventSupplier = eventSupplier;
}
public NetworkEvent getEvent(final PacketBuffer buffer, final NetworkManager manager) {
return this.eventSupplier.apply(buffer, manager);
}
}
private final ResourceLocation channelName;
private final Supplier<String> networkProtocolVersion;
private final Predicate<String> clientAcceptedVersions;
private final Predicate<String> serverAcceptedVersions;
private final IEventBus networkEventBus;
NetworkInstance(ResourceLocation channelName, Supplier<String> networkProtocolVersion, Predicate<String> clientAcceptedVersions, Predicate<String> serverAcceptedVersions)
{
this.channelName = channelName;
this.networkProtocolVersion = networkProtocolVersion;
this.clientAcceptedVersions = clientAcceptedVersions;
this.serverAcceptedVersions = serverAcceptedVersions;
this.networkEventBus = IEventBus.create(this::handleError);
}
private void handleError(IEventBus iEventBus, Event event, IEventListener[] iEventListeners, int i, Throwable throwable)
{
}
public <T extends NetworkEvent> void addListener(Consumer<T> serverEventListener)
{
this.networkEventBus.addListener(serverEventListener);
}
public void registerObject(final Object object) {
this.networkEventBus.register(object);
}
public void unregisterObject(final Object object) {
this.networkEventBus.unregister(object);
}
void dispatch(final NetworkSide side, final PacketBuffer bufferData, final NetworkManager manager)
{
this.networkEventBus.post(side.getEvent(bufferData,manager));
}
public static class NetworkEvent extends Event {
private final PacketBuffer payload;
private final NetworkManager source;
private NetworkEvent(PacketBuffer payload, NetworkManager source)
{
this.payload = payload;
this.source = source;
}
public PacketBuffer getPayload()
{
return payload;
}
public NetworkManager getSource()
{
return source;
}
public static class ServerCustomPayloadEvent extends NetworkEvent {
ServerCustomPayloadEvent(final PacketBuffer payload, final NetworkManager source) {
super(payload, source);
}
}
public static class ClientCustomPayloadEvent extends NetworkEvent {
ClientCustomPayloadEvent(final PacketBuffer payload, final NetworkManager source) {
super(payload, source);
}
}
}
}

View file

@ -19,15 +19,48 @@
package net.minecraftforge.fml.network;
import io.netty.util.AttributeKey;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.network.simple.SimpleChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class NetworkRegistry
{
public static final NetworkRegistry INSTANCE = new NetworkRegistry();
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker NETREGISTRY = MarkerManager.getMarker("NETREGISTRY");
public static final AttributeKey<String> FML_MARKER = AttributeKey.valueOf("fml:versionMarker");
private static Map<ResourceLocation, NetworkInstance> instances = new HashMap<>();
public static List<String> getNonVanillaNetworkMods()
{
return Collections.emptyList();
}
public static SimpleChannel newSimpleChannel(final ResourceLocation name, Supplier<String> networkProtocolVersion, Predicate<String> clientAcceptedVersions, Predicate<String> serverAcceptedVersions) {
final NetworkInstance networkInstance = new NetworkInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions);
if (instances.containsKey(name)) {
LOGGER.error(NETREGISTRY, "Network channel {} already registered.", name);
throw new IllegalArgumentException("Network Channel {"+ name +"} already registered");
}
instances.put(name, networkInstance);
return new SimpleChannel(networkInstance);
}
static Optional<NetworkInstance> findTarget(ResourceLocation resourceLocation)
{
return Optional.ofNullable(instances.get(resourceLocation));
}
}

View file

@ -0,0 +1,96 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.network.simple;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import it.unimi.dsi.fastutil.shorts.Short2ObjectArrayMap;
import net.minecraft.network.PacketBuffer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
public class IndexedMessageCodec
{
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker SIMPLENET = MarkerManager.getMarker("SIMPLENET");
private final Short2ObjectArrayMap<CodecIndex<?>> indicies = new Short2ObjectArrayMap<>();
private final Object2ObjectArrayMap<Class<?>, CodecIndex<?>> types = new Object2ObjectArrayMap<>();
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public class CodecIndex<MSG>
{
private final Optional<BiConsumer<MSG, PacketBuffer>> encoder;
private final Optional<Function<PacketBuffer, MSG>> decoder;
private final int index;
private final BiConsumer<MSG,Supplier<MessageContext>> messageConsumer;
private final Class<MSG> messageType;
public CodecIndex(int index, Class<MSG> messageType, BiConsumer<MSG, PacketBuffer> encoder, Function<PacketBuffer, MSG> decoder, BiConsumer<MSG, Supplier<MessageContext>> messageConsumer)
{
this.index = index;
this.messageType = messageType;
this.encoder = Optional.ofNullable(encoder);
this.decoder = Optional.ofNullable(decoder);
this.messageConsumer = messageConsumer;
indicies.put((short)(index & 0xff), this);
types.put(messageType, this);
}
}
private static <M> void tryDecode(PacketBuffer payload, Supplier<MessageContext> context, CodecIndex<M> codec)
{
codec.decoder.map(d->d.apply(payload)).ifPresent(m->codec.messageConsumer.accept(m, context));
}
private static <M> void tryEncode(PacketBuffer target, M message, CodecIndex<M> codec) {
codec.encoder.ifPresent(c->c.accept(message, target));
}
public <MSG> void build(MSG message, PacketBuffer target)
{
@SuppressWarnings("unchecked")
CodecIndex<MSG> codecIndex = (CodecIndex<MSG>)types.get(message.getClass());
if (codecIndex == null) {
LOGGER.error(SIMPLENET, "Received invalid message {}", message.getClass().getName());
throw new IllegalArgumentException("Invalid message "+message.getClass().getName());
}
tryEncode(target, message, codecIndex);
}
void consume(final PacketBuffer payload, Supplier<MessageContext> context) {
short discriminator = payload.readUnsignedByte();
final CodecIndex<?> codecIndex = indicies.get(discriminator);
if (codecIndex == null) {
LOGGER.error(SIMPLENET, "Received invalid discriminator byte {}", discriminator);
return;
}
tryDecode(payload, context, codecIndex);
}
<MSG> void addCodecIndex(int index, Class<MSG> messageType, BiConsumer<MSG, PacketBuffer> encoder, Function<PacketBuffer, MSG> decoder, BiConsumer<MSG, Supplier<MessageContext>> messageConsumer) {
new CodecIndex<>(index, messageType, encoder, decoder, messageConsumer);
}
}

View file

@ -17,12 +17,15 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.network.simpleimpl;
package net.minecraftforge.fml.network.simple;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.network.INetHandler;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.network.NetworkManager;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.network.NetworkInstance;
/**
* Context for the {@link IMessageHandler}
@ -35,21 +38,26 @@ public class MessageContext {
* The {@link INetHandler} for this message. It could be a client or server handler, depending
* on the {@link #side} received.
*/
public final INetHandler netHandler;
private final INetHandler netHandler;
/**
* The Dist this message has been received on
* The {@link NetworkInstance.NetworkSide} this message has been received on
*/
public final Dist side;
private final NetworkInstance.NetworkSide side;
/**
* @param netHandler
* @param side
*/
MessageContext(INetHandler netHandler, Dist side)
MessageContext(NetworkManager netHandler, NetworkInstance.NetworkSide side)
{
this.netHandler = netHandler;
this.netHandler = netHandler.getNetHandler();
this.side = side;
}
public NetworkInstance.NetworkSide getSide() {
return side;
}
public NetHandlerPlayServer getServerHandler()
{
return (NetHandlerPlayServer) netHandler;

View file

@ -0,0 +1,71 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.network.simple;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.client.Minecraft;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.client.CPacketCustomPayload;
import net.minecraftforge.fml.network.NetworkInstance;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
public class SimpleChannel
{
private final NetworkInstance instance;
private final IndexedMessageCodec indexedCodec;
public SimpleChannel(NetworkInstance instance)
{
this.instance = instance;
this.indexedCodec = new IndexedMessageCodec();
instance.addListener(this::serverEventListener);
instance.addListener(this::clientEventListener);
}
private void clientEventListener(final NetworkInstance.NetworkEvent.ClientCustomPayloadEvent clientCustomPayloadEvent)
{
}
private void serverEventListener(final NetworkInstance.NetworkEvent.ServerCustomPayloadEvent serverCustomPayloadEvent)
{
this.indexedCodec.consume(serverCustomPayloadEvent.getPayload(),
()->new MessageContext(serverCustomPayloadEvent.getSource(), NetworkInstance.NetworkSide.PLAYSERVER));
}
public <MSG> void encodeMessage(MSG message, final PacketBuffer target) {
this.indexedCodec.build(message, target);
}
public <MSG> void registerMessage(int index, Class<MSG> messageType, BiConsumer<MSG, PacketBuffer> encoder, Function<PacketBuffer, MSG> decoder, BiConsumer<MSG, Supplier<MessageContext>> messageConsumer) {
this.indexedCodec.addCodecIndex(index, messageType, encoder, decoder, messageConsumer);
}
public <MSG> void sendToServer(MSG message)
{
final PacketBuffer bufIn = new PacketBuffer(Unpooled.buffer());
encodeMessage(message, bufIn);
final CPacketCustomPayload payload = new CPacketCustomPayload(instance.getChannelName(), bufIn);
Minecraft.getMinecraft().getConnection().sendPacket(payload);
}
}

View file

@ -23,12 +23,13 @@ import io.netty.channel.Channel;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.network.NetworkManager;
import net.minecraft.util.text.TextComponentBase;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.translation.I18n;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.network.ConnectionType;
import net.minecraftforge.fml.network.NetworkHooks;
public class TextComponentHelper
{
@ -52,13 +53,8 @@ public class TextComponentHelper
if (sender instanceof EntityPlayerMP)
{
EntityPlayerMP playerMP = (EntityPlayerMP) sender;
NetHandlerPlayServer connection = playerMP.connection;
if (connection != null)
{
NetworkManager netManager = connection.netManager;
Channel channel = netManager.channel();
return !channel.attr(NetworkRegistry.FML_MARKER).get();
}
NetHandlerPlayServer channel = playerMP.connection;
return NetworkHooks.getConnectionType(channel) == ConnectionType.VANILLA;
}
return false;
}

View file

@ -51,7 +51,7 @@ import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.network.simple.MessageContext;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.common.registry.GameRegistry;

View file

@ -20,7 +20,7 @@
package net.minecraftforge.fml.test.simplenet;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.network.simple.MessageContext;
public class SimpleNetHandler1 implements IMessageHandler<SimpleNetTestMessage1, SimpleNetTestMessage2>
{

View file

@ -20,7 +20,7 @@
package net.minecraftforge.fml.test.simplenet;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.network.simple.MessageContext;
public class SimpleNetHandler2 implements IMessageHandler<SimpleNetTestMessage2, SimpleNetTestMessage1>
{