Rewrite networking.

This commit is contained in:
LexManos committed 2023-09-10 20:27:15 -07:00
1 parent 3edefbe33e
commit 4649f7af36
103 files changed
+4399 -5303

No files matched your search

@@ -145,6 +145,7 @@ import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions;
import net.minecraftforge.client.extensions.common.IClientItemExtensions;
import net.minecraftforge.client.extensions.common.IClientMobEffectExtensions;
import net.minecraftforge.client.gui.ClientTooltipComponentManager;
import net.minecraftforge.client.gui.ModMismatchDisconnectedScreen;
import net.minecraftforge.client.gui.overlay.GuiOverlayManager;
import net.minecraftforge.client.model.data.ModelData;
import net.minecraftforge.client.textures.ForgeTextureMetadata;
@@ -165,7 +166,8 @@ import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.forge.snapshots.ForgeSnapshotsModClient;
import net.minecraftforge.gametest.ForgeGameTestHooks;
import net.minecraftforge.network.NetworkConstants;
import net.minecraftforge.network.NetworkContext;
import net.minecraftforge.network.NetworkInitialization;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.ServerStatusPing;
import net.minecraftforge.registries.GameData;
@@ -201,8 +203,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApiStatus.Internal
public class ForgeHooksClient
{
public class ForgeHooksClient {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker CLIENTHOOKS = MarkerManager.getMarker("CLIENTHOOKS");
@@ -218,21 +219,18 @@ public class ForgeHooksClient
guiLayers.forEach(screen -> screen.resize(minecraft, width, height));
}
public static void clearGuiLayers(Minecraft minecraft)
{
public static void clearGuiLayers(Minecraft minecraft) {
while(guiLayers.size() > 0)
popGuiLayerInternal(minecraft);
}
private static void popGuiLayerInternal(Minecraft minecraft)
{
private static void popGuiLayerInternal(Minecraft minecraft) {
if (minecraft.screen != null)
minecraft.screen.removed();
minecraft.screen = guiLayers.pop();
}
public static void pushGuiLayer(Minecraft minecraft, Screen screen)
{
public static void pushGuiLayer(Minecraft minecraft, Screen screen) {
if (minecraft.screen != null)
guiLayers.push(minecraft.screen);
minecraft.screen = Objects.requireNonNull(screen);
@@ -240,10 +238,8 @@ public class ForgeHooksClient
minecraft.getNarrator().sayNow(screen.getNarrationMessage());
}
public static void popGuiLayer(Minecraft minecraft)
{
if (guiLayers.size() == 0)
{
public static void popGuiLayer(Minecraft minecraft) {
if (guiLayers.size() == 0) {
minecraft.setScreen(null);
return;
}
@@ -253,22 +249,19 @@ public class ForgeHooksClient
minecraft.getNarrator().sayNow(minecraft.screen.getNarrationMessage());
}
public static float getGuiFarPlane()
{
public static float getGuiFarPlane() {
// 1000 units for the overlay background,
// and 10000 units for each layered Screen,
return 1000.0F + 10000.0F * (1 + guiLayers.size());
}
public static String getArmorTexture(Entity entity, ItemStack armor, String _default, EquipmentSlot slot, String type)
{
public static String getArmorTexture(Entity entity, ItemStack armor, String _default, EquipmentSlot slot, String type) {
String result = armor.getItem().getArmorTexture(armor, entity, slot, type);
return result != null ? result : _default;
}
public static boolean onDrawHighlight(LevelRenderer context, Camera camera, HitResult target, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource)
{
public static boolean onDrawHighlight(LevelRenderer context, Camera camera, HitResult target, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource) {
switch (target.getType()) {
case BLOCK:
if (!(target instanceof BlockHitResult blockTarget)) return false;
@@ -287,40 +280,33 @@ public class ForgeHooksClient
stage.dispatch(levelRenderer, poseStack, projectionMatrix, renderTick, camera, frustum);
}
public static boolean renderSpecificFirstPersonHand(InteractionHand hand, PoseStack poseStack, MultiBufferSource bufferSource, int packedLight, float partialTick, float interpPitch, float swingProgress, float equipProgress, ItemStack stack)
{
public static boolean renderSpecificFirstPersonHand(InteractionHand hand, PoseStack poseStack, MultiBufferSource bufferSource, int packedLight, float partialTick, float interpPitch, float swingProgress, float equipProgress, ItemStack stack) {
return MinecraftForge.EVENT_BUS.post(new RenderHandEvent(hand, poseStack, bufferSource, packedLight, partialTick, interpPitch, swingProgress, equipProgress, stack));
}
public static boolean renderSpecificFirstPersonArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm)
{
public static boolean renderSpecificFirstPersonArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) {
return MinecraftForge.EVENT_BUS.post(new RenderArmEvent(poseStack, multiBufferSource, packedLight, player, arm));
}
public static void onTextureStitchedPost(TextureAtlas map)
{
public static void onTextureStitchedPost(TextureAtlas map) {
ModLoader.get().postEvent(new TextureStitchEvent.Post(map));
}
public static void onBlockColorsInit(BlockColors blockColors)
{
public static void onBlockColorsInit(BlockColors blockColors) {
ModLoader.get().postEvent(new RegisterColorHandlersEvent.Block(blockColors));
}
public static void onItemColorsInit(ItemColors itemColors, BlockColors blockColors)
{
public static void onItemColorsInit(ItemColors itemColors, BlockColors blockColors) {
ModLoader.get().postEvent(new RegisterColorHandlersEvent.Item(itemColors, blockColors));
}
public static Model getArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlot slot, HumanoidModel<?> _default)
{
public static Model getArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlot slot, HumanoidModel<?> _default) {
return IClientItemExtensions.of(itemStack).getGenericArmorModel(entityLiving, itemStack, slot, _default);
}
/** Copies humanoid model properties from the original model to another, used for armor models */
@SuppressWarnings("unchecked")
public static <T extends LivingEntity> void copyModelProperties(HumanoidModel<T> original, HumanoidModel<?> replacement)
{
public static <T extends LivingEntity> void copyModelProperties(HumanoidModel<T> original, HumanoidModel<?> replacement) {
// this function does not make use of the <T> generic, so the unchecked cast should be safe
original.copyPropertiesTo((HumanoidModel<T>)replacement);
replacement.head.visible = original.head.visible;
@@ -333,35 +319,27 @@ public class ForgeHooksClient
}
//This properly moves the domain, if provided, to the front of the string before concatenating
public static String fixDomain(String base, String complex)
{
public static String fixDomain(String base, String complex) {
int idx = complex.indexOf(':');
if (idx == -1)
{
return base + complex;
}
String name = complex.substring(idx + 1, complex.length());
if (idx > 1)
{
if (idx > 1) {
String domain = complex.substring(0, idx);
return domain + ':' + base + name;
}
else
{
} else {
return base + name;
}
}
public static float getFieldOfViewModifier(Player entity, float fovModifier)
{
public static float getFieldOfViewModifier(Player entity, float fovModifier) {
ComputeFovModifierEvent fovModifierEvent = new ComputeFovModifierEvent(entity, fovModifier);
MinecraftForge.EVENT_BUS.post(fovModifierEvent);
return fovModifierEvent.getNewFovModifier();
}
public static double getFieldOfView(GameRenderer renderer, Camera camera, double partialTick, double fov, boolean usedConfiguredFov)
{
public static double getFieldOfView(GameRenderer renderer, Camera camera, double partialTick, double fov, boolean usedConfiguredFov) {
ViewportEvent.ComputeFov event = new ViewportEvent.ComputeFov(renderer, camera, partialTick, fov, usedConfiguredFov);
MinecraftForge.EVENT_BUS.post(event);
return event.getFOV();
@@ -370,19 +348,16 @@ public class ForgeHooksClient
/**
* Initialization of Forge Renderers.
*/
static
{
static {
//FluidRegistry.renderIdFluid = RenderingRegistry.getNextAvailableRenderId();
//RenderingRegistry.registerBlockHandler(RenderBlockFluid.instance);
}
public static void renderMainMenu(TitleScreen gui, GuiGraphics guiGraphics, Font font, int width, int height, int alpha)
{
public static void renderMainMenu(TitleScreen gui, GuiGraphics guiGraphics, Font font, int width, int height, int alpha) {
VersionChecker.Status status = ForgeVersion.getStatus();
ForgeSnapshotsModClient.renderMainMenuWarning(status, gui, guiGraphics, font, width, height, alpha);
forgeStatusLine = switch(status)
{
forgeStatusLine = switch(status) {
// case FAILED -> " Version check failed";
// case UP_TO_DATE -> "Forge up to date";
// case AHEAD -> "Using non-recommended Forge build, issues may arise.";
@@ -393,15 +368,13 @@ public class ForgeHooksClient
public static String forgeStatusLine;
@Nullable
public static SoundInstance playSound(SoundEngine manager, SoundInstance sound)
{
public static SoundInstance playSound(SoundEngine manager, SoundInstance sound) {
PlaySoundEvent e = new PlaySoundEvent(manager, sound);
MinecraftForge.EVENT_BUS.post(e);
return e.getSound();
}
public static void drawScreen(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick)
{
public static void drawScreen(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
guiGraphics.pose().pushPose();
guiLayers.forEach(layer -> {
// Prevent the background layers from thinking the mouse is over their controls and showing them as highlighted.
@@ -412,15 +385,13 @@ public class ForgeHooksClient
guiGraphics.pose().popPose();
}
private static void drawScreenInternal(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick)
{
private static void drawScreenInternal(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
if (!MinecraftForge.EVENT_BUS.post(new ScreenEvent.Render.Pre(screen, guiGraphics, mouseX, mouseY, partialTick)))
screen.renderWithTooltip(guiGraphics, mouseX, mouseY, partialTick);
MinecraftForge.EVENT_BUS.post(new ScreenEvent.Render.Post(screen, guiGraphics, mouseX, mouseY, partialTick));
}
public static Vector3f getFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, float fogRed, float fogGreen, float fogBlue)
{
public static Vector3f getFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, float fogRed, float fogGreen, float fogBlue) {
// Modify fog color depending on the fluid
FluidState state = level.getFluidState(camera.getBlockPosition());
Vector3f fluidFogColor = new Vector3f(fogRed, fogGreen, fogBlue);
@@ -434,48 +405,41 @@ public class ForgeHooksClient
return fluidFogColor;
}
public static void onFogRender(FogRenderer.FogMode mode, FogType type, Camera camera, float partialTick, float renderDistance, float nearDistance, float farDistance, FogShape shape)
{
public static void onFogRender(FogRenderer.FogMode mode, FogType type, Camera camera, float partialTick, float renderDistance, float nearDistance, float farDistance, FogShape shape) {
// Modify fog rendering depending on the fluid
FluidState state = camera.getEntity().level().getFluidState(camera.getBlockPosition());
if (camera.getPosition().y < (double)((float)camera.getBlockPosition().getY() + state.getHeight(camera.getEntity().level(), camera.getBlockPosition())))
IClientFluidTypeExtensions.of(state).modifyFogRender(camera, mode, renderDistance, partialTick, nearDistance, farDistance, shape);
ViewportEvent.RenderFog event = new ViewportEvent.RenderFog(mode, type, camera, partialTick, nearDistance, farDistance, shape);
if (MinecraftForge.EVENT_BUS.post(event))
{
if (MinecraftForge.EVENT_BUS.post(event)) {
RenderSystem.setShaderFogStart(event.getNearPlaneDistance());
RenderSystem.setShaderFogEnd(event.getFarPlaneDistance());
RenderSystem.setShaderFogShape(event.getFogShape());
}
}
public static ViewportEvent.ComputeCameraAngles onCameraSetup(GameRenderer renderer, Camera camera, float partial)
{
public static ViewportEvent.ComputeCameraAngles onCameraSetup(GameRenderer renderer, Camera camera, float partial) {
ViewportEvent.ComputeCameraAngles event = new ViewportEvent.ComputeCameraAngles(renderer, camera, partial, camera.getYRot(), camera.getXRot(), 0);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
public static void onModifyBakingResult(Map<ResourceLocation, BakedModel> models, ModelBakery modelBakery)
{
public static void onModifyBakingResult(Map<ResourceLocation, BakedModel> models, ModelBakery modelBakery) {
ModLoader.get().postEvent(new ModelEvent.ModifyBakingResult(models, modelBakery));
}
public static void onModelBake(ModelManager modelManager, Map<ResourceLocation, BakedModel> models, ModelBakery modelBakery)
{
public static void onModelBake(ModelManager modelManager, Map<ResourceLocation, BakedModel> models, ModelBakery modelBakery) {
ModLoader.get().postEvent(new ModelEvent.BakingCompleted(modelManager, Collections.unmodifiableMap(models), modelBakery));
}
public static BakedModel handleCameraTransforms(PoseStack poseStack, BakedModel model, ItemDisplayContext cameraTransformType, boolean applyLeftHandTransform)
{
public static BakedModel handleCameraTransforms(PoseStack poseStack, BakedModel model, ItemDisplayContext cameraTransformType, boolean applyLeftHandTransform) {
model = model.applyTransform(cameraTransformType, poseStack, applyLeftHandTransform);
return model;
}
@SuppressWarnings("deprecation")
public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn)
{
public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn) {
IClientFluidTypeExtensions props = IClientFluidTypeExtensions.of(fluidStateIn);
ResourceLocation overlayTexture = props.getOverlayTexture(fluidStateIn, level, pos);
return new TextureAtlasSprite[] {
@@ -486,13 +450,11 @@ public class ForgeHooksClient
}
@SuppressWarnings("deprecation")
public static Material getBlockMaterial(ResourceLocation loc)
{
public static Material getBlockMaterial(ResourceLocation loc) {
return new Material(TextureAtlas.LOCATION_BLOCKS, loc);
}
public static void fillNormal(int[] faceData, Direction facing)
{
public static void fillNormal(int[] faceData, Direction facing) {
fillNormal(faceData, facing, false);
}
@@ -500,8 +462,7 @@ public class ForgeHooksClient
* internal, relies on fixed format of FaceBakery
*/
// TODO Do we need this?
public static void fillNormal(int[] faceData, Direction facing, boolean calculateNormals)
{
public static void fillNormal(int[] faceData, Direction facing, boolean calculateNormals) {
Vector3f v2;
if (calculateNormals || ForgeConfig.CLIENT.calculateAllNormals.get()) {
Vector3f v1 = getVertexPos(faceData, 3);
@@ -512,9 +473,8 @@ public class ForgeHooksClient
v2.sub(t2);
v2.cross(v1);
v2.normalize();
} else {
} else
v2 = new Vector3f(facing.getNormal().getX(), facing.getNormal().getY(), facing.getNormal().getZ());
}
int x = ((byte) Math.round(v2.x() * 127)) & 0xFF;
int y = ((byte) Math.round(v2.y() * 127)) & 0xFF;
int z = ((byte) Math.round(v2.z() * 127)) & 0xFF;
@@ -522,13 +482,10 @@ public class ForgeHooksClient
int normal = x | (y << 0x08) | (z << 0x10);
for(int i = 0; i < 4; i++)
{
faceData[i * 8 + 7] = normal;
}
}
private static Vector3f getVertexPos(int[] data, int vertex)
{
private static Vector3f getVertexPos(int[] data, int vertex) {
int idx = vertex * 8;
float x = Float.intBitsToFloat(data[idx]);
@@ -538,8 +495,7 @@ public class ForgeHooksClient
return new Vector3f(x, y, z);
}
public static boolean calculateFaceWithoutAO(BlockAndTintGetter getter, BlockState state, BlockPos pos, BakedQuad quad, boolean isFaceCubic, float[] brightness, int[] lightmap)
{
public static boolean calculateFaceWithoutAO(BlockAndTintGetter getter, BlockState state, BlockPos pos, BakedQuad quad, boolean isFaceCubic, float[] brightness, int[] lightmap) {
if (quad.hasAmbientOcclusion())
return false;
@@ -550,22 +506,17 @@ public class ForgeHooksClient
return true;
}
public static void loadEntityShader(Entity entity, GameRenderer entityRenderer)
{
if (entity != null)
{
public static void loadEntityShader(Entity entity, GameRenderer entityRenderer) {
if (entity != null) {
ResourceLocation shader = EntitySpectatorShaderManager.get(entity.getType());
if (shader != null)
{
entityRenderer.loadEffect(shader);
}
}
}
private static int slotMainHand = 0;
public static boolean shouldCauseReequipAnimation(@NotNull ItemStack from, @NotNull ItemStack to, int slot)
{
public static boolean shouldCauseReequipAnimation(@NotNull ItemStack from, @NotNull ItemStack to, int slot) {
boolean fromInvalid = from.isEmpty();
boolean toInvalid = to.isEmpty();
@@ -573,92 +524,77 @@ public class ForgeHooksClient
if (fromInvalid || toInvalid) return true;
boolean changed = false;
if (slot != -1)
{
if (slot != -1) {
changed = slot != slotMainHand;
slotMainHand = slot;
}
return from.getItem().shouldCauseReequipAnimation(from, to, changed);
}
public static CustomizeGuiOverlayEvent.BossEventProgress onCustomizeBossEventProgress(GuiGraphics guiGraphics, Window window, LerpingBossEvent bossInfo, int x, int y, int increment)
{
public static CustomizeGuiOverlayEvent.BossEventProgress onCustomizeBossEventProgress(GuiGraphics guiGraphics, Window window, LerpingBossEvent bossInfo, int x, int y, int increment) {
CustomizeGuiOverlayEvent.BossEventProgress evt = new CustomizeGuiOverlayEvent.BossEventProgress(window, guiGraphics,
Minecraft.getInstance().getPartialTick(), bossInfo, x, y, increment);
MinecraftForge.EVENT_BUS.post(evt);
return evt;
}
public static ScreenshotEvent onScreenshot(NativeImage image, File screenshotFile)
{
public static ScreenshotEvent onScreenshot(NativeImage image, File screenshotFile) {
ScreenshotEvent event = new ScreenshotEvent(image, screenshotFile);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
public static void onClientChangeGameType(PlayerInfo info, GameType currentGameMode, GameType newGameMode)
{
if (currentGameMode != newGameMode)
{
public static void onClientChangeGameType(PlayerInfo info, GameType currentGameMode, GameType newGameMode) {
if (currentGameMode != newGameMode) {
ClientPlayerChangeGameTypeEvent evt = new ClientPlayerChangeGameTypeEvent(info, currentGameMode, newGameMode);
MinecraftForge.EVENT_BUS.post(evt);
}
}
public static void onMovementInputUpdate(Player player, Input movementInput)
{
public static void onMovementInputUpdate(Player player, Input movementInput) {
MinecraftForge.EVENT_BUS.post(new MovementInputUpdateEvent(player, movementInput));
}
public static boolean onScreenKeyPressedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers)
{
public static boolean onScreenKeyPressedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyPressed.Pre(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onScreenKeyPressedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers)
{
public static boolean onScreenKeyPressedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyPressed.Post(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onScreenKeyReleasedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers)
{
public static boolean onScreenKeyReleasedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyReleased.Pre(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onScreenKeyReleasedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers)
{
public static boolean onScreenKeyReleasedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyReleased.Post(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onScreenCharTypedPre(Screen guiScreen, char codePoint, int modifiers)
{
public static boolean onScreenCharTypedPre(Screen guiScreen, char codePoint, int modifiers) {
Event event = new ScreenEvent.CharacterTyped.Pre(guiScreen, codePoint, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static void onScreenCharTypedPost(Screen guiScreen, char codePoint, int modifiers)
{
public static void onScreenCharTypedPost(Screen guiScreen, char codePoint, int modifiers) {
Event event = new ScreenEvent.CharacterTyped.Post(guiScreen, codePoint, modifiers);
MinecraftForge.EVENT_BUS.post(event);
}
public static void onRecipesUpdated(RecipeManager mgr)
{
public static void onRecipesUpdated(RecipeManager mgr) {
Event event = new RecipesUpdatedEvent(mgr);
MinecraftForge.EVENT_BUS.post(event);
}
public static void onKeyInput(int key, int scanCode, int action, int modifiers)
{
public static void onKeyInput(int key, int scanCode, int action, int modifiers) {
MinecraftForge.EVENT_BUS.post(new InputEvent.Key(key, scanCode, action, modifiers));
}
public static InputEvent.InteractionKeyMappingTriggered onClickInput(int button, KeyMapping keyBinding, InteractionHand hand)
{
public static InputEvent.InteractionKeyMappingTriggered onClickInput(int button, KeyMapping keyBinding, InteractionHand hand) {
InputEvent.InteractionKeyMappingTriggered event = new InputEvent.InteractionKeyMappingTriggered(button, keyBinding, hand);
MinecraftForge.EVENT_BUS.post(event);
return event;
@@ -676,15 +612,13 @@ public class ForgeHooksClient
public static void renderPistonMovedBlocks(BlockPos pos, BlockState state, PoseStack stack, MultiBufferSource bufferSource, Level level, boolean checkSides, int packedOverlay, BlockRenderDispatcher blockRenderer) {
var model = blockRenderer.getBlockModel(state);
for (var renderType : model.getRenderTypes(state, RandomSource.create(state.getSeed(pos)), ModelData.EMPTY))
{
for (var renderType : model.getRenderTypes(state, RandomSource.create(state.getSeed(pos)), ModelData.EMPTY)) {
VertexConsumer vertexConsumer = bufferSource.getBuffer(RenderTypeHelper.getMovingBlockRenderType(renderType));
blockRenderer.getModelRenderer().tesselateBlock(level, model, state, pos, stack, vertexConsumer, checkSides, RandomSource.create(), state.getSeed(pos), packedOverlay, ModelData.EMPTY, renderType);
}
}
public static boolean shouldRenderEffect(MobEffectInstance effectInstance)
{
public static boolean shouldRenderEffect(MobEffectInstance effectInstance) {
return IClientMobEffectExtensions.of(effectInstance).isVisibleInInventory(effectInstance);
}
@@ -701,24 +635,16 @@ public class ForgeHooksClient
}
@Nullable
public static TextureAtlasSprite loadTextureAtlasSprite(
ResourceLocation atlasName,
SpriteContents contents,
int atlasWidth, int atlasHeight,
int spriteX, int spriteY, int mipmapLevel
)
{
public static TextureAtlasSprite loadTextureAtlasSprite(ResourceLocation atlasName, SpriteContents contents, int atlasWidth, int atlasHeight, int spriteX, int spriteY, int mipmapLevel) {
if (contents.forgeMeta == null || contents.forgeMeta.getLoader() == null)
return null;
return contents.forgeMeta.getLoader().makeSprite(atlasName, contents, atlasWidth, atlasHeight, spriteX, spriteY, mipmapLevel);
}
private static final Map<ModelLayerLocation, Supplier<LayerDefinition>> layerDefinitions = new HashMap<>();
public static void registerLayerDefinition(ModelLayerLocation layerLocation, Supplier<LayerDefinition> supplier)
{
public static void registerLayerDefinition(ModelLayerLocation layerLocation, Supplier<LayerDefinition> supplier) {
layerDefinitions.put(layerLocation, supplier);
}
@@ -726,15 +652,14 @@ public class ForgeHooksClient
layerDefinitions.forEach((k, v) -> builder.put(k, v.get()));
}
public static void processForgeListPingData(ServerStatus packet, ServerData target)
{
packet.forgeData().ifPresentOrElse(forgeData ->
{
public static void processForgeListPingData(ServerStatus packet, ServerData target) {
packet.forgeData().ifPresentOrElse(forgeData -> {
final Map<String, String> mods = forgeData.getRemoteModData();
final Map<ResourceLocation, ServerStatusPing.ChannelData> remoteChannels = forgeData.getRemoteChannels();
final int fmlver = forgeData.getFMLNetworkVersion();
boolean fmlNetMatches = fmlver == NetworkConstants.FMLNETVERSION;
int wantedVer = NetworkInitialization.getVersion();
boolean fmlNetMatches = fmlver == wantedVer;
boolean channelsMatch = NetworkRegistry.checkListPingCompatibilityForClient(remoteChannels);
AtomicBoolean result = new AtomicBoolean(true);
final List<String> extraClientMods = new ArrayList<>();
@@ -742,15 +667,14 @@ public class ForgeHooksClient
mc.getCustomExtension(IExtensionPoint.DisplayTest.class).ifPresent(ext-> {
boolean foundModOnServer = ext.remoteVersionTest().test(mods.get(modid), true);
result.compareAndSet(true, foundModOnServer);
if (!foundModOnServer) {
if (!foundModOnServer)
extraClientMods.add(modid);
}
})
);
boolean modsMatch = result.get();
final Map<String, String> extraServerMods = mods.entrySet().stream().
filter(e -> !Objects.equals(NetworkConstants.IGNORESERVERONLY, e.getValue())).
filter(e -> !Objects.equals(IExtensionPoint.DisplayTest.IGNORESERVERONLY, e.getValue())).
filter(e -> !ModList.get().isLoaded(e.getKey())).
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
@@ -764,20 +688,19 @@ public class ForgeHooksClient
.map(e -> e.getKey() + "@" + e.getValue())
.collect(Collectors.joining(", ")));
}
if (!modsMatch) {
extraReason = "fml.menu.multiplayer.modsincompatible";
LOGGER.info(CLIENTHOOKS, "Client has mods that are missing on server: {}", extraClientMods);
}
if (!channelsMatch) {
extraReason = "fml.menu.multiplayer.networkincompatible";
}
if (fmlver < NetworkConstants.FMLNETVERSION) {
if (!channelsMatch)
extraReason = "fml.menu.multiplayer.networkincompatible";
if (fmlver < wantedVer)
extraReason = "fml.menu.multiplayer.serveroutdated";
}
if (fmlver > NetworkConstants.FMLNETVERSION) {
if (fmlver > wantedVer)
extraReason = "fml.menu.multiplayer.clientoutdated";
}
target.forgeData = new ExtendedServerListData("FML", extraServerMods.isEmpty() && fmlNetMatches && channelsMatch && modsMatch, mods.size(), extraReason, forgeData.isTruncated());
}, () -> target.forgeData = new ExtendedServerListData("VANILLA", NetworkRegistry.canConnectToVanillaServer(),0, null));
}
@@ -803,9 +726,7 @@ public class ForgeHooksClient
}
}
if (target.forgeData.truncated())
{
tooltip += "\n" + ForgeI18n.parseMessage("fml.menu.multiplayer.truncated");
}
break;
case "VANILLA":
if (target.forgeData.isCompatible()) {
@@ -830,19 +751,15 @@ public class ForgeHooksClient
}
}
private static Connection getClientConnection()
{
private static Connection getClientConnection() {
return Minecraft.getInstance().getConnection()!=null ? Minecraft.getInstance().getConnection().getConnection() : null;
}
public static void handleClientLevelClosing(ClientLevel level)
{
public static void handleClientLevelClosing(ClientLevel level) {
Connection client = getClientConnection();
// ONLY revert a non-local connection
if (client != null && !client.isMemoryConnection())
{
GameData.revertToFrozen();
}
}
public static void firePlayerLogin(MultiPlayerGameMode pc, LocalPlayer player, Connection networkManager) {
@@ -870,15 +787,13 @@ public class ForgeHooksClient
}
@Nullable
public static Component onClientChat(ChatType.Bound boundChatType, Component message, UUID sender)
{
public static Component onClientChat(ChatType.Bound boundChatType, Component message, UUID sender) {
ClientChatReceivedEvent event = new ClientChatReceivedEvent(boundChatType, message, sender);
return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage();
}
@Nullable
public static Component onClientPlayerChat(ChatType.Bound boundChatType, Component message, PlayerChatMessage playerChatMessage, UUID sender)
{
public static Component onClientPlayerChat(ChatType.Bound boundChatType, Component message, PlayerChatMessage playerChatMessage, UUID sender) {
ClientChatReceivedEvent.Player event = new ClientChatReceivedEvent.Player(boundChatType, message, playerChatMessage, sender);
return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage();
}
@@ -888,15 +803,13 @@ public class ForgeHooksClient
private static final ChatType.Bound SYSTEM_CHAT_TYPE_BOUND = SYSTEM_CHAT_TYPE.bind(Component.literal("System"));
@Nullable
public static Component onClientSystemChat(Component message, boolean overlay)
{
public static Component onClientSystemChat(Component message, boolean overlay) {
ClientChatReceivedEvent.System event = new ClientChatReceivedEvent.System(SYSTEM_CHAT_TYPE_BOUND, message, overlay);
return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage();
}
@NotNull
public static String onClientSendMessage(String message)
{
public static String onClientSendMessage(String message) {
ClientChatEvent event = new ClientChatEvent(message);
return MinecraftForge.EVENT_BUS.post(event) ? "" : event.getMessage();
}
@@ -906,58 +819,49 @@ public class ForgeHooksClient
* for the input {@link RenderType}.
*/
@NotNull
public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull)
{
public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull) {
return RenderTypeHelper.getEntityRenderType(chunkRenderType, cull);
}
@Mod.EventBusSubscriber(value = Dist.CLIENT, modid="forge", bus= Mod.EventBusSubscriber.Bus.MOD)
public static class ClientEvents
{
public static class ClientEvents {
@Nullable
private static ShaderInstance rendertypeEntityTranslucentUnlitShader;
public static ShaderInstance getEntityTranslucentUnlitShader()
{
public static ShaderInstance getEntityTranslucentUnlitShader() {
return Objects.requireNonNull(rendertypeEntityTranslucentUnlitShader, "Attempted to call getEntityTranslucentUnlitShader before shaders have finished loading.");
}
@SubscribeEvent
public static void registerShaders(RegisterShadersEvent event) throws IOException
{
public static void registerShaders(RegisterShadersEvent event) throws IOException {
event.registerShader(new ShaderInstance(event.getResourceProvider(), new ResourceLocation("forge","rendertype_entity_unlit_translucent"), DefaultVertexFormat.NEW_ENTITY), (p_172645_) -> {
rendertypeEntityTranslucentUnlitShader = p_172645_;
});
}
}
public static Font getTooltipFont(@NotNull ItemStack stack, Font fallbackFont)
{
public static Font getTooltipFont(@NotNull ItemStack stack, Font fallbackFont) {
Font stackFont = IClientItemExtensions.of(stack).getFont(stack, IClientItemExtensions.FontContext.TOOLTIP);
return stackFont == null ? fallbackFont : stackFont;
}
public static RenderTooltipEvent.Pre onRenderTooltipPre(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, @NotNull List<ClientTooltipComponent> components, @NotNull Font fallbackFont, @NotNull ClientTooltipPositioner positioner)
{
public static RenderTooltipEvent.Pre onRenderTooltipPre(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, @NotNull List<ClientTooltipComponent> components, @NotNull Font fallbackFont, @NotNull ClientTooltipPositioner positioner) {
var preEvent = new RenderTooltipEvent.Pre(stack, graphics, x, y, screenWidth, screenHeight, getTooltipFont(stack, fallbackFont), components, positioner);
MinecraftForge.EVENT_BUS.post(preEvent);
return preEvent;
}
public static RenderTooltipEvent.Color onRenderTooltipColor(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, @NotNull Font font, @NotNull List<ClientTooltipComponent> components)
{
public static RenderTooltipEvent.Color onRenderTooltipColor(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, @NotNull Font font, @NotNull List<ClientTooltipComponent> components) {
var colorEvent = new RenderTooltipEvent.Color(stack, graphics, x, y, font, 0xf0100010, 0x505000FF, 0x5028007f, components);
MinecraftForge.EVENT_BUS.post(colorEvent);
return colorEvent;
}
public static List<ClientTooltipComponent> gatherTooltipComponents(ItemStack stack, List<? extends FormattedText> textElements, int mouseX, int screenWidth, int screenHeight, Font fallbackFont)
{
public static List<ClientTooltipComponent> gatherTooltipComponents(ItemStack stack, List<? extends FormattedText> textElements, int mouseX, int screenWidth, int screenHeight, Font fallbackFont) {
return gatherTooltipComponents(stack, textElements, Optional.empty(), mouseX, screenWidth, screenHeight, fallbackFont);
}
public static List<ClientTooltipComponent> gatherTooltipComponents(ItemStack stack, List<? extends FormattedText> textElements, Optional<TooltipComponent> itemComponent, int mouseX, int screenWidth, int screenHeight, Font fallbackFont)
{
public static List<ClientTooltipComponent> gatherTooltipComponents(ItemStack stack, List<? extends FormattedText> textElements, Optional<TooltipComponent> itemComponent, int mouseX, int screenWidth, int screenHeight, Font fallbackFont) {
Font font = getTooltipFont(stack, fallbackFont);
List<Either<FormattedText, TooltipComponent>> elements = textElements.stream()
.map((Function<FormattedText, Either<FormattedText, TooltipComponent>>) Either::left)
@@ -977,11 +881,9 @@ public class ForgeHooksClient
boolean needsWrap = false;
int tooltipX = mouseX + 12;
if (tooltipX + tooltipTextWidth + 4 > screenWidth)
{
if (tooltipX + tooltipTextWidth + 4 > screenWidth) {
tooltipX = mouseX - 16 - tooltipTextWidth;
if (tooltipX < 4) // if the tooltip doesn't fit on the screen
{
if (tooltipX < 4) { // if the tooltip doesn't fit on the screen
if (mouseX > screenWidth / 2)
tooltipTextWidth = mouseX - 12 - 8;
else
@@ -990,15 +892,13 @@ public class ForgeHooksClient
}
}
if (event.getMaxWidth() > 0 && tooltipTextWidth > event.getMaxWidth())
{
if (event.getMaxWidth() > 0 && tooltipTextWidth > event.getMaxWidth()) {
tooltipTextWidth = event.getMaxWidth();
needsWrap = true;
}
int tooltipTextWidthF = tooltipTextWidth;
if (needsWrap)
{
if (needsWrap) {
return event.getTooltipElements().stream()
.flatMap(either -> either.map(
text -> splitLine(text, font, tooltipTextWidthF),
@@ -1014,115 +914,83 @@ public class ForgeHooksClient
.toList();
}
private static Stream<ClientTooltipComponent> splitLine(FormattedText text, Font font, int maxWidth)
{
private static Stream<ClientTooltipComponent> splitLine(FormattedText text, Font font, int maxWidth) {
if (text instanceof Component component && component.getString().isEmpty())
{
return Stream.of(component.getVisualOrderText()).map(ClientTooltipComponent::create);
}
return font.split(text, maxWidth).stream().map(ClientTooltipComponent::create);
}
public static Comparator<ParticleRenderType> makeParticleRenderTypeComparator(List<ParticleRenderType> renderOrder)
{
public static Comparator<ParticleRenderType> makeParticleRenderTypeComparator(List<ParticleRenderType> renderOrder) {
Comparator<ParticleRenderType> vanillaComparator = Comparator.comparingInt(renderOrder::indexOf);
return (typeOne, typeTwo) ->
{
return (typeOne, typeTwo) -> {
boolean vanillaOne = renderOrder.contains(typeOne);
boolean vanillaTwo = renderOrder.contains(typeTwo);
if (vanillaOne && vanillaTwo)
{
return vanillaComparator.compare(typeOne, typeTwo);
}
if (!vanillaOne && !vanillaTwo)
{
return Integer.compare(System.identityHashCode(typeOne), System.identityHashCode(typeTwo));
}
return vanillaOne ? -1 : 1;
};
}
public static ScreenEvent.RenderInventoryMobEffects onScreenPotionSize(Screen screen, int availableSpace, boolean compact, int horizontalOffset)
{
public static ScreenEvent.RenderInventoryMobEffects onScreenPotionSize(Screen screen, int availableSpace, boolean compact, int horizontalOffset) {
final ScreenEvent.RenderInventoryMobEffects event = new ScreenEvent.RenderInventoryMobEffects(screen, availableSpace, compact, horizontalOffset);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
public static boolean onToastAdd(Toast toast)
{
public static boolean onToastAdd(Toast toast) {
return MinecraftForge.EVENT_BUS.post(new ToastAddEvent(toast));
}
public static boolean isBlockInSolidLayer(BlockState state)
{
public static boolean isBlockInSolidLayer(BlockState state) {
var model = Minecraft.getInstance().getBlockRenderer().getBlockModel(state);
return model.getRenderTypes(state, RandomSource.create(), ModelData.EMPTY).contains(RenderType.solid());
}
public static void createWorldConfirmationScreen(Runnable doConfirmedWorldLoad)
{
public static void createWorldConfirmationScreen(Runnable doConfirmedWorldLoad) {
Component title = Component.translatable("selectWorld.backupQuestion.experimental");
Component msg = Component.translatable("selectWorld.backupWarning.experimental")
.append("\n\n")
.append(Component.translatable("forge.selectWorld.backupWarning.experimental.additional"));
Screen screen = new ConfirmScreen(confirmed ->
{
Screen screen = new ConfirmScreen(confirmed -> {
if (confirmed)
{
doConfirmedWorldLoad.run();
}
else
{
Minecraft.getInstance().setScreen(null);
}
}, title, msg, CommonComponents.GUI_PROCEED, CommonComponents.GUI_CANCEL);
Minecraft.getInstance().setScreen(screen);
}
public static boolean renderFireOverlay(Player player, PoseStack mat)
{
public static boolean renderFireOverlay(Player player, PoseStack mat) {
return renderBlockOverlay(player, mat, RenderBlockScreenEffectEvent.OverlayType.FIRE, Blocks.FIRE.defaultBlockState(), player.blockPosition());
}
public static boolean renderWaterOverlay(Player player, PoseStack mat)
{
public static boolean renderWaterOverlay(Player player, PoseStack mat) {
return renderBlockOverlay(player, mat, RenderBlockScreenEffectEvent.OverlayType.WATER, Blocks.WATER.defaultBlockState(), player.blockPosition());
}
public static boolean renderBlockOverlay(Player player, PoseStack mat, RenderBlockScreenEffectEvent.OverlayType type, BlockState block, BlockPos pos)
{
public static boolean renderBlockOverlay(Player player, PoseStack mat, RenderBlockScreenEffectEvent.OverlayType type, BlockState block, BlockPos pos) {
return MinecraftForge.EVENT_BUS.post(new RenderBlockScreenEffectEvent(player, mat, type, block, pos));
}
public static int getMaxMipmapLevel(int width, int height)
{
public static int getMaxMipmapLevel(int width, int height) {
return Math.min(
Mth.log2(Math.max(1, width)),
Mth.log2(Math.max(1, height))
);
}
public static ResourceLocation getShaderImportLocation(String basePath, boolean isRelative, String importPath)
{
public static ResourceLocation getShaderImportLocation(String basePath, boolean isRelative, String importPath) {
final var loc = new ResourceLocation(importPath);
final var normalised = FileUtil.normalizeResourcePath(
(isRelative ? basePath : "shaders/include/") + loc.getPath());
return new ResourceLocation(loc.getNamespace(), normalised);
}
// Use ForgeHooks.onCreativeModeTabBuildContents()
// since calling this will crash if called on server
@Deprecated(forRemoval = true, since = "1.20.1")
public static void onCreativeModeTabBuildContents(CreativeModeTab tab, ResourceKey<CreativeModeTab> tabKey, CreativeModeTab.DisplayItemsGenerator originalGenerator, CreativeModeTab.ItemDisplayParameters params, CreativeModeTab.Output output)
{
// Bounce to ForgeHooks.onCreativeModeBuildContents(...)
ForgeHooks.onCreativeModeTabBuildContents(tab, tabKey, originalGenerator, params, output);
}
/**
* This function is a clone of {@link Direction#getNearest(float, float, float)} designed to return a consistent
* direction when the normal is at an inflection point (ie 45 degrees) rounding errors
@@ -1138,8 +1006,7 @@ public class ForgeHooksClient
* @param nZ Z component of the normal
* @return the nearest Direction to the passed in normal, biased slightly in favor of the order of declaration
*/
public static Direction getNearestStable(float nX, float nY, float nZ)
{
public static Direction getNearestStable(float nX, float nY, float nZ) {
if (ForgeConfig.CLIENT.stabilizeDirectionGetNearest.get()) {
Direction ret = Direction.NORTH;
float sum = Float.MIN_VALUE;
@@ -1151,21 +1018,17 @@ public class ForgeHooksClient
}
}
return ret;
} else {
} else
return Direction.getNearest(nX, nY, nZ);
}
}
// Make sure the below method is only ever called once (by forge).
private static boolean initializedClientHooks = false;
// Runs during Minecraft construction, before initial resource loading.
@ApiStatus.Internal
public static void initClientHooks(Minecraft mc, ReloadableResourceManager resourceManager)
{
public static void initClientHooks(Minecraft mc, ReloadableResourceManager resourceManager) {
if (initializedClientHooks)
{
throw new IllegalStateException("Client hooks initialized more than once");
}
initializedClientHooks = true;
ForgeGameTestHooks.registerGametests();
@@ -1184,4 +1047,12 @@ public class ForgeHooksClient
ItemDecoratorHandler.init();
PresetEditorManager.init();
}
public static boolean onClientDisconnect(Connection connection, Minecraft mc, Screen parent, Component message) {
var mismatch = NetworkContext.get(connection).getMismatchs();
if (mismatch == null)
return false;
mc.setScreen(new ModMismatchDisconnectedScreen(parent, CommonComponents.CONNECT_FAILED, message, mismatch));
return true;
}
}
@@ -0,0 +1,94 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.event;
import java.util.Map;
import org.jetbrains.annotations.Nullable;
import net.minecraft.client.MouseHandler;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererProvider.Context;
import net.minecraft.client.resources.PlayerSkin.Model;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.ModLoader;
public class ForgeEventFactoryClient {
private static boolean post(Event e) {
return MinecraftForge.EVENT_BUS.post(e);
}
private static <E extends Event> E fire(E e) {
MinecraftForge.EVENT_BUS.post(e);
return e;
}
public static void gatherLayers(Map<EntityType<?>, EntityRenderer<?>> renderers, Map<Model, EntityRenderer<? extends Player>> playerRenderers, Context context) {
// TODO: Why is this a ModLoader event...
ModLoader.get().postEvent(new EntityRenderersEvent.AddLayers(renderers, playerRenderers, context));
}
public static boolean onScreenMouseReleasedPre(Screen guiScreen, double mouseX, double mouseY, int button) {
return post(new ScreenEvent.MouseButtonReleased.Pre(guiScreen, mouseX, mouseY, button));
}
public static boolean onScreenMouseReleasedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) {
var result = fire(new ScreenEvent.MouseButtonReleased.Post(guiScreen, mouseX, mouseY, button, handled)).getResult();
return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW;
}
public static boolean onScreenMouseClickedPre(Screen guiScreen, double mouseX, double mouseY, int button) {
return post(new ScreenEvent.MouseButtonPressed.Pre(guiScreen, mouseX, mouseY, button));
}
public static boolean onScreenMouseClickedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) {
var result = fire(new ScreenEvent.MouseButtonPressed.Post(guiScreen, mouseX, mouseY, button, handled)).getResult();
return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW;
}
public static boolean onMouseButtonPre(int button, int action, int mods) {
return post(new InputEvent.MouseButton.Pre(button, action, mods));
}
public static void onMouseButtonPost(int button, int action, int mods) {
post(new InputEvent.MouseButton.Post(button, action, mods));
}
public static boolean onScreenMouseScrollPre(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) {
return post(new ScreenEvent.MouseScrolled.Pre(guiScreen, mouseX, mouseY, deltaX, deltaY));
}
public static void onScreenMouseScrollPost(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) {
post(new ScreenEvent.MouseScrolled.Post(guiScreen, mouseX, mouseY, deltaX, deltaY));
}
public static boolean onMouseScroll(MouseHandler mouseHelper, double deltaX, double deltaY) {
return post(new InputEvent.MouseScrollingEvent(deltaX, deltaY, mouseHelper.isLeftPressed(), mouseHelper.isMiddlePressed(), mouseHelper.isRightPressed(), mouseHelper.xpos(), mouseHelper.ypos()));
}
public static boolean onScreenMouseDragPre(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) {
return post(new ScreenEvent.MouseDragged.Pre(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY));
}
public static void onScreenMouseDragPost(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) {
post(new ScreenEvent.MouseDragged.Post(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY));
}
public static @Nullable Screen onScreenOpening(Screen old, Screen screen) {
var event = new ScreenEvent.Opening(old, screen);
if (post(event))
return null;
return event.getNewScreen();
}
public static void onScreenClose(Screen screen) {
post(new ScreenEvent.Closing(screen));
}
}
@@ -10,7 +10,6 @@ import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
@@ -39,46 +38,43 @@ import net.minecraft.util.FormattedCharSequence;
import net.minecraftforge.common.ForgeI18n;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.loading.FMLPaths;
import net.minecraftforge.network.ConnectionData.ModMismatchData;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.NetworkContext.NetworkMismatchData;
import net.minecraftforge.network.packets.ModVersions;
public class ModMismatchDisconnectedScreen extends Screen
{
//TODO: Oh god... Whoever wrote this was on something very very strong.
public class ModMismatchDisconnectedScreen extends Screen {
private final Component reason;
private MultiLineLabel message = MultiLineLabel.EMPTY;
private final Screen parent;
private int textHeight;
private final ModMismatchData modMismatchData;
private final Path modsDir;
private final Path logFile;
private final int listHeight;
private final Map<ResourceLocation, Pair<String, String>> presentModData;
private final List<ResourceLocation> missingModData;
private final Map<ResourceLocation, String> mismatchedModData;
private final NetworkMismatchData data;
private final boolean hasMismatches;
private final List<String> allModIds;
private final Map<String, String> presentModUrls;
private final boolean mismatchedDataFromServer;
public ModMismatchDisconnectedScreen(Screen parentScreen, Component title, Component reason, ModMismatchData modMismatchData)
{
public ModMismatchDisconnectedScreen(Screen parentScreen, Component title, Component reason, NetworkMismatchData data) {
super(title);
this.parent = parentScreen;
this.reason = reason;
this.modMismatchData = modMismatchData;
this.modsDir = FMLPaths.MODSDIR.get();
this.logFile = FMLPaths.GAMEDIR.get().resolve(Paths.get("logs","latest.log"));
this.listHeight = modMismatchData.containsMismatches() ? 140 : 0;
this.mismatchedDataFromServer = modMismatchData.mismatchedDataFromServer();
this.presentModData = modMismatchData.presentModData();
this.missingModData = modMismatchData.mismatchedModData().entrySet().stream().filter(e -> e.getValue().equals(NetworkRegistry.ABSENT.version())).map(Entry::getKey).collect(Collectors.toList());
this.mismatchedModData = modMismatchData.mismatchedModData().entrySet().stream().filter(e -> !e.getValue().equals(NetworkRegistry.ABSENT.version())).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
this.allModIds = presentModData.keySet().stream().map(ResourceLocation::getNamespace).distinct().collect(Collectors.toList());
this.presentModUrls = ModList.get().getMods().stream().filter(info -> allModIds.contains(info.getModId())).map(info -> Pair.of(info.getModId(), (String)info.getConfig().getConfigElement("displayURL").orElse(""))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
this.data = data;
this.hasMismatches = !data.mismatched().isEmpty() || !data.missing().isEmpty();
this.listHeight = hasMismatches ? 140 : 0;
this.allModIds = data.mods().keySet().stream().distinct().collect(Collectors.toList());
this.presentModUrls = ModList.get().getMods().stream()
.filter(info -> allModIds.contains(info.getModId()))
.map(info -> Pair.of(info.getModId(), (String)info.getConfig().getConfigElement("displayURL").orElse("")))
.collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
}
@Override
protected void init()
{
protected void init() {
this.message = MultiLineLabel.create(this.font, this.reason, this.width - 50);
this.textHeight = this.message.getLineCount() * 9;
@@ -86,7 +82,7 @@ public class ModMismatchDisconnectedScreen extends Screen
int listWidth = Math.min(440, this.width - 16);
int upperButtonHeight = Math.min((this.height + this.listHeight + this.textHeight) / 2 + 10, this.height - 50);
int lowerButtonHeight = Math.min((this.height + this.listHeight + this.textHeight) / 2 + 35, this.height - 25);
if (modMismatchData.containsMismatches())
if (hasMismatches)
this.addRenderableWidget(new MismatchInfoPanel(minecraft, listWidth, listHeight, (this.height - this.listHeight) / 2, listLeft));
int buttonWidth = Math.min(210, this.width / 2 - 20);
@@ -102,17 +98,15 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks)
{
public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
this.renderBackground(guiGraphics, mouseX, mouseY, partialTicks);
int textYOffset = modMismatchData.containsMismatches() ? 18 : 0;
int textYOffset = hasMismatches ? 18 : 0;
guiGraphics.drawCenteredString(this.font, this.title, this.width / 2, (this.height - this.listHeight - this.textHeight) / 2 - textYOffset - 9 * 2, 0xAAAAAA);
this.message.renderCentered(guiGraphics, this.width / 2, (this.height - this.listHeight - this.textHeight) / 2 - textYOffset);
super.render(guiGraphics, mouseX, mouseY, partialTicks);
}
class MismatchInfoPanel extends ScrollPanel
{
class MismatchInfoPanel extends ScrollPanel {
private final List<Pair<FormattedCharSequence, Pair<FormattedCharSequence, FormattedCharSequence>>> lineTable;
private final int contentSize;
private final int nameIndent = 10;
@@ -120,41 +114,69 @@ public class ModMismatchDisconnectedScreen extends Screen
private final int nameWidth = tableWidth * 3 / 5;
private final int versionWidth = (tableWidth - nameWidth) / 2;
public MismatchInfoPanel(Minecraft client, int width, int height, int top, int left)
{
public MismatchInfoPanel(Minecraft client, int width, int height, int top, int left) {
super(client, width, height, top, left);
//The raw list of the strings in a table row, the components may still be too long for the final table and will be split up later. The first row element may have a style assigned to it that will be used for the whole content row.
List<Pair<MutableComponent, Pair<String, String>>> rawTable = new ArrayList<>();
if (!missingModData.isEmpty())
{
if (!data.missing().isEmpty()) {
//The header of the section, colored in gray
rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.missingmods.server" : "fml.modmismatchscreen.missingmods.client")).withStyle(ChatFormatting.GRAY), null));
rawTable.add(Pair.of(
Component.literal(ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.missingmods.server" : "fml.modmismatchscreen.missingmods.client")).withStyle(ChatFormatting.GRAY),
null
));
//This table section contains the mod name and mod version of each mod that has a missing remote counterpart (if the mod is missing on the server, the client mod version is displayed, and vice versa)
rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE), Pair.of("", ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.youneed"))));
rawTable.add(Pair.of(
Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE),
Pair.of(
"",
ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.youneed")
)
));
int i = 0;
for (ResourceLocation mod : missingModData) {
rawTable.add(Pair.of(toModNameComponent(mod, presentModData.get(mod).getLeft(), i), Pair.of("", presentModData.getOrDefault(mod, Pair.of("", "")).getRight())));
for (ResourceLocation mod : data.missing()) {
rawTable.add(Pair.of(
toModNameComponent(mod, data.mods().get(mod.getNamespace()).name(), i),
Pair.of(
"",
data.mods().getOrDefault(mod, new ModVersions.Info("", "")).version()
)
));
if (++i >= 10) {
//If too many missing mod entries are present, append a line referencing how to see the full list and stop rendering any more entries
rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", missingModData.size() - i)).withStyle(ChatFormatting.ITALIC), Pair.of("", "")));
rawTable.add(Pair.of(
Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", data.missing().size() - i)).withStyle(ChatFormatting.ITALIC),
Pair.of("", "")
));
break;
}
}
rawTable.add(Pair.of(Component.literal(" "), null)); //padding
}
if (!mismatchedModData.isEmpty())
{
if (!data.mismatched().isEmpty()) {
//The header of the table section, colored in gray
rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.mismatchedmods")).withStyle(ChatFormatting.GRAY), null));
//This table section contains the mod name and both mod versions of each mod that has a mismatching client and server version
rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE), Pair.of(ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.serverhas"), ForgeI18n.parseMessage(mismatchedDataFromServer ? "fml.modmismatchscreen.table.serverhas" : "fml.modmismatchscreen.table.youhave"))));
rawTable.add(Pair.of(
Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.table.modname")).withStyle(ChatFormatting.UNDERLINE),
Pair.of(
ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.table.youhave" : "fml.modmismatchscreen.table.serverhas"),
ForgeI18n.parseMessage(data.fromServer() ? "fml.modmismatchscreen.table.serverhas" : "fml.modmismatchscreen.table.youhave")
)
));
int i = 0;
for (Map.Entry<ResourceLocation, String> modData : mismatchedModData.entrySet()) {
rawTable.add(Pair.of(toModNameComponent(modData.getKey(), presentModData.get(modData.getKey()).getLeft(), i), Pair.of(presentModData.getOrDefault(modData.getKey(), Pair.of("", "")).getRight(), modData.getValue())));
for (var modData : data.mismatched().entrySet()) {
rawTable.add(Pair.of(
toModNameComponent(modData.getKey(), data.mods().get(modData.getKey().getNamespace()).name(), i),
Pair.of(
data.mods().getOrDefault(modData.getKey(), new ModVersions.Info("", "")).version(),
modData.getValue().received()
)
));
if (++i >= 10) {
//If too many mismatched mod entries are present, append a line referencing how to see the full list and stop rendering any more entries
rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", mismatchedModData.size() - i)).withStyle(ChatFormatting.ITALIC), Pair.of("", "")));
rawTable.add(Pair.of(Component.literal(ForgeI18n.parseMessage("fml.modmismatchscreen.additional", data.mismatched().size() - i)).withStyle(ChatFormatting.ITALIC), Pair.of("", "")));
break;
}
}
@@ -172,8 +194,7 @@ public class ModMismatchDisconnectedScreen extends Screen
* @param versions The last two elements of the content row, usually representing the mod versions. If either one or both of them are not given, the first element may take up more space within the table.
* @return A list of table rows consisting of 3 elements each which consist of the same content as was given by the parameters, but split up to fit within the table dimensions.
*/
private List<Pair<FormattedCharSequence, Pair<FormattedCharSequence, FormattedCharSequence>>> splitLineToWidth(MutableComponent name, Pair<String, String> versions)
{
private List<Pair<FormattedCharSequence, Pair<FormattedCharSequence, FormattedCharSequence>>> splitLineToWidth(MutableComponent name, Pair<String, String> versions) {
Style style = name.getStyle();
int versionColumns = versions == null ? 0 : (versions.getLeft().isEmpty() ? (versions.getRight().isEmpty() ? 0 : 1) : 2);
int adaptedNameWidth = nameWidth + versionWidth * (2 - versionColumns) - 4; //the name width may be expanded when the version column string is missing
@@ -183,7 +204,13 @@ public class ModMismatchDisconnectedScreen extends Screen
List<Pair<FormattedCharSequence, Pair<FormattedCharSequence, FormattedCharSequence>>> splitLines = new ArrayList<>();
int rowsOccupied = Math.max(nameLines.size(), Math.max(clientVersionLines.size(), serverVersionLines.size()));
for (int i = 0; i < rowsOccupied; i++) {
splitLines.add(Pair.of(i < nameLines.size() ? nameLines.get(i) : FormattedCharSequence.EMPTY, versions == null ? null : Pair.of(i < clientVersionLines.size() ? clientVersionLines.get(i) : FormattedCharSequence.EMPTY, i < serverVersionLines.size() ? serverVersionLines.get(i) : FormattedCharSequence.EMPTY)));
splitLines.add(Pair.of(
i < nameLines.size() ? nameLines.get(i) : FormattedCharSequence.EMPTY,
versions == null ? null : Pair.of(
i < clientVersionLines.size() ? clientVersionLines.get(i) : FormattedCharSequence.EMPTY,
i < serverVersionLines.size() ? serverVersionLines.get(i) : FormattedCharSequence.EMPTY
)
));
}
return splitLines;
}
@@ -196,8 +223,7 @@ public class ModMismatchDisconnectedScreen extends Screen
* @param color Defines the color of the returned style information. An odd number will result in a yellow, an even one in a gold color. This color variation makes it easier for users to distinguish different mod entries.
* @return A component with the mod name as the main text component, and an assigned style which will be used for the whole content row.
*/
private MutableComponent toModNameComponent(ResourceLocation id, String modName, int color)
{
private MutableComponent toModNameComponent(ResourceLocation id, String modName, int color) {
String modId = id.getNamespace();
String tooltipId = id.getPath().isEmpty() ? id.getNamespace() : id.toString();
return Component.literal(modName).withStyle(color % 2 == 0 ? ChatFormatting.GOLD : ChatFormatting.YELLOW)
@@ -206,8 +232,7 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
protected int getContentHeight()
{
protected int getContentHeight() {
int height = contentSize * (font.lineHeight + 3);
if (height < bottom - top - 4)
@@ -217,8 +242,7 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
protected void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, Tesselator tess, int mouseX, int mouseY)
{
protected void drawPanel(GuiGraphics guiGraphics, int entryRight, int relativeY, Tesselator tess, int mouseX, int mouseY) {
int i = 0;
for (Pair<FormattedCharSequence, Pair<FormattedCharSequence, FormattedCharSequence>> line : lineTable) {
@@ -229,8 +253,7 @@ public class ModMismatchDisconnectedScreen extends Screen
//Only indent the given name if a version string is present. This makes it easier to distinguish table section headers and mod entries
int nameLeft = left + border + (versions == null ? 0 : nameIndent);
guiGraphics.drawString(font, name, nameLeft, relativeY + i * 12, color, false);
if (versions != null)
{
if (versions != null) {
guiGraphics.drawString(font, versions.getLeft(), left + border + nameIndent + nameWidth, relativeY + i * 12, color, false);
guiGraphics.drawString(font, versions.getRight(), left + border + nameIndent + nameWidth + versionWidth, relativeY + i * 12, color, false);
}
@@ -240,24 +263,18 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks)
{
public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
super.render(guiGraphics, mouseX, mouseY, partialTicks);
Style style = getComponentStyleAt(mouseX, mouseY);
if (style != null && style.getHoverEvent() != null)
{
guiGraphics.renderComponentHoverEffect(font, style, mouseX, mouseY);
}
}
public Style getComponentStyleAt(double x, double y)
{
if (this.isMouseOver(x, y))
{
public Style getComponentStyleAt(double x, double y) {
if (this.isMouseOver(x, y)) {
double relativeY = y - this.top + this.scrollDistance - border;
int slotIndex = (int)(relativeY + (border / 2)) / 12;
if (slotIndex < contentSize)
{
if (slotIndex < contentSize) {
//The relative x needs to take the potentially missing indent of the row into account. It does that by checking if the line has a version associated to it
double relativeX = x - left - border - (lineTable.get(slotIndex).getRight() == null ? 0 : nameIndent);
if (relativeX >= 0)
@@ -269,8 +286,7 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
public boolean mouseClicked(final double mouseX, final double mouseY, final int button)
{
public boolean mouseClicked(final double mouseX, final double mouseY, final int button) {
Style style = getComponentStyleAt(mouseX, mouseY);
if (style != null) {
handleComponentClicked(style);
@@ -280,8 +296,7 @@ public class ModMismatchDisconnectedScreen extends Screen
}
@Override
public NarrationPriority narrationPriority()
{
public NarrationPriority narrationPriority() {
return NarrationPriority.NONE;
}
File diff suppressed because it is too large. Load diff
@@ -19,6 +19,7 @@ import net.minecraftforge.event.entity.EntityJoinLevelEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.level.ChunkEvent;
import net.minecraftforge.event.level.LevelEvent;
import net.minecraftforge.event.network.ConnectionStartEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.event.TagsUpdatedEvent;
@@ -26,27 +27,24 @@ import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.TickEvent.ClientTickEvent;
import net.minecraftforge.event.TickEvent.ServerTickEvent;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.network.filters.NetworkFilters;
import net.minecraftforge.common.util.LogicalSidedProvider;
import net.minecraftforge.server.command.ForgeCommand;
import net.minecraftforge.server.command.ConfigCommand;
public class ForgeInternalHandler
{
public class ForgeInternalHandler {
@SubscribeEvent(priority = EventPriority.HIGH)
public void onEntityJoinWorld(EntityJoinLevelEvent event)
{
public void onEntityJoinWorld(EntityJoinLevelEvent event) {
Entity entity = event.getEntity();
if (entity.getClass().equals(ItemEntity.class))
{
if (entity.getClass().equals(ItemEntity.class)) {
ItemStack stack = ((ItemEntity)entity).getItem();
Item item = stack.getItem();
if (item.hasCustomEntity(stack))
{
if (item.hasCustomEntity(stack)) {
Entity newEntity = item.createEntity(event.getLevel(), entity, stack);
if (newEntity != null)
{
if (newEntity != null) {
entity.discard();
event.setCanceled(true);
@SuppressWarnings("resource")
var executor = LogicalSidedProvider.WORKQUEUE.get(event.getLevel().isClientSide ? LogicalSide.CLIENT : LogicalSide.SERVER);
executor.tell(new TickTask(0, () -> event.getLevel().addFreshEntity(newEntity)));
}
@@ -56,59 +54,49 @@ public class ForgeInternalHandler
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onDimensionUnload(LevelEvent.Unload event)
{
public void onDimensionUnload(LevelEvent.Unload event) {
if (event.getLevel() instanceof ServerLevel)
FakePlayerFactory.unloadLevel((ServerLevel) event.getLevel());
}
@SubscribeEvent
public void onServerTick(ServerTickEvent event)
{
public void onServerTick(ServerTickEvent event) {
WorldWorkerManager.tick(event.phase == TickEvent.Phase.START);
}
@SubscribeEvent
public void checkSettings(ClientTickEvent event)
{
public void checkSettings(ClientTickEvent event) {
//if (event.phase == Phase.END)
// CloudRenderer.updateCloudSettings();
}
@SubscribeEvent
public void onChunkUnload(ChunkEvent.Unload event)
{
public void onChunkUnload(ChunkEvent.Unload event) {
if (!event.getLevel().isClientSide())
FarmlandWaterManager.removeTickets(event.getChunk());
}
/*
@SubscribeEvent
public void playerChangeDimension(PlayerEvent.PlayerChangedDimensionEvent event)
{
public void playerChangeDimension(PlayerEvent.PlayerChangedDimensionEvent event) {
if (event.getPlayer() instanceof ServerPlayerEntity)
DimensionManager.rebuildPlayerMap(((ServerPlayerEntity)event.getPlayer()).server.getPlayerList(), true);
}
*/
@SubscribeEvent
public void playerLogin(PlayerEvent.PlayerLoggedInEvent event)
{
public void playerLogin(PlayerEvent.PlayerLoggedInEvent event) {
UsernameCache.setUsername(event.getEntity().getUUID(), event.getEntity().getGameProfile().getName());
}
@SubscribeEvent
public void tagsUpdated(TagsUpdatedEvent event)
{
public void tagsUpdated(TagsUpdatedEvent event) {
if (event.shouldUpdateStaticData())
{
ForgeHooks.updateBurns();
}
}
@SubscribeEvent
public void onCommandsRegister(RegisterCommandsEvent event)
{
public void onCommandsRegister(RegisterCommandsEvent event) {
new ForgeCommand(event.getDispatcher());
ConfigCommand.register(event.getDispatcher());
}
@@ -117,14 +105,12 @@ public class ForgeInternalHandler
private static LootModifierManager INSTANCE;
@SubscribeEvent
public void onResourceReload(AddReloadListenerEvent event)
{
public void onResourceReload(AddReloadListenerEvent event) {
INSTANCE = new LootModifierManager();
event.addListener(INSTANCE);
}
static LootModifierManager getLootModifierManager()
{
static LootModifierManager getLootModifierManager() {
if(INSTANCE == null)
throw new IllegalStateException("Can not retrieve LootModifierManager until resources have loaded once.");
return INSTANCE;
@@ -132,19 +118,20 @@ public class ForgeInternalHandler
*/
@SubscribeEvent
public void resourceReloadListeners(AddReloadListenerEvent event)
{
public void resourceReloadListeners(AddReloadListenerEvent event) {
event.addListener(TierSortingRegistry.getReloadListener());
event.addListener(CreativeModeTabRegistry.getReloadListener());
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void builtinMobSpawnBlocker(EntityJoinLevelEvent event)
{
public void builtinMobSpawnBlocker(EntityJoinLevelEvent event) {
if(event.getEntity() instanceof Mob mob && mob.isSpawnCancelled())
{
event.setCanceled(true);
}
}
@SubscribeEvent
public void onConnectionStart(ConnectionStartEvent event) {
NetworkFilters.injectIfNecessary(event.getConnection());
}
}
@@ -71,7 +71,8 @@ import net.minecraftforge.registries.holdersets.AnyHolderSet;
import net.minecraftforge.registries.holdersets.HolderSetType;
import net.minecraftforge.registries.holdersets.NotHolderSet;
import net.minecraftforge.registries.holdersets.OrHolderSet;
import net.minecraftforge.network.NetworkConstants;
import net.minecraftforge.network.NetworkInitialization;
import net.minecraftforge.network.tasks.ForgeNetworkConfigurationHandler;
import net.minecraftforge.event.server.ServerStoppingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.data.event.GatherDataEvent;
@@ -115,11 +116,9 @@ import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Mod("forge")
public class ForgeMod
{
public class ForgeMod {
public static final String VERSION_CHECK_CAT = "version_checking";
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker FORGEMOD = MarkerManager.getMarker("FORGEMOD");
@@ -260,9 +259,9 @@ public class ForgeMod
.viscosity(0))
{
@Override
public void setItemMovement(ItemEntity entity)
{
if (!entity.isNoGravity()) entity.setDeltaMovement(entity.getDeltaMovement().add(0.0D, -0.04D, 0.0D));
public void setItemMovement(ItemEntity entity) {
if (!entity.isNoGravity())
entity.setDeltaMovement(entity.getDeltaMovement().add(0.0D, -0.04D, 0.0D));
}
});
public static final RegistryObject<FluidType> WATER_TYPE = VANILLA_FLUID_TYPES.register("water", () ->
@@ -278,60 +277,52 @@ public class ForgeMod
.canHydrate(true))
{
@Override
public @Nullable BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog)
{
public @Nullable BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) {
return canFluidLog ? super.getBlockPathType(state, level, pos, mob, true) : null;
}
@Override
public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer)
{
consumer.accept(new IClientFluidTypeExtensions()
{
public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) {
consumer.accept(new IClientFluidTypeExtensions() {
private static final ResourceLocation UNDERWATER_LOCATION = new ResourceLocation("textures/misc/underwater.png"),
WATER_STILL = new ResourceLocation("block/water_still"),
WATER_FLOW = new ResourceLocation("block/water_flow"),
WATER_OVERLAY = new ResourceLocation("block/water_overlay");
@Override
public ResourceLocation getStillTexture()
{
public ResourceLocation getStillTexture() {
return WATER_STILL;
}
@Override
public ResourceLocation getFlowingTexture()
{
public ResourceLocation getFlowingTexture() {
return WATER_FLOW;
}
@Nullable
@Override
public ResourceLocation getOverlayTexture()
{
public ResourceLocation getOverlayTexture() {
return WATER_OVERLAY;
}
@Override
public ResourceLocation getRenderOverlayTexture(Minecraft mc)
{
public ResourceLocation getRenderOverlayTexture(Minecraft mc) {
return UNDERWATER_LOCATION;
}
@Override
public int getTintColor()
{
public int getTintColor() {
return 0xFF3F76E4;
}
@Override
public int getTintColor(FluidState state, BlockAndTintGetter getter, BlockPos pos)
{
public int getTintColor(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
return BiomeColors.getAverageWaterColor(getter, pos) | 0xFF000000;
}
});
}
});
public static final RegistryObject<FluidType> LAVA_TYPE = VANILLA_FLUID_TYPES.register("lava", () ->
new FluidType(FluidType.Properties.create()
.descriptionId("block.minecraft.lava")
@@ -347,35 +338,29 @@ public class ForgeMod
.temperature(1300))
{
@Override
public double motionScale(Entity entity)
{
public double motionScale(Entity entity) {
return entity.level().dimensionType().ultraWarm() ? 0.007D : 0.0023333333333333335D;
}
@Override
public void setItemMovement(ItemEntity entity)
{
public void setItemMovement(ItemEntity entity) {
Vec3 vec3 = entity.getDeltaMovement();
entity.setDeltaMovement(vec3.x * (double)0.95F, vec3.y + (double)(vec3.y < (double)0.06F ? 5.0E-4F : 0.0F), vec3.z * (double)0.95F);
}
@Override
public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer)
{
consumer.accept(new IClientFluidTypeExtensions()
{
public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) {
consumer.accept(new IClientFluidTypeExtensions() {
private static final ResourceLocation LAVA_STILL = new ResourceLocation("block/lava_still"),
LAVA_FLOW = new ResourceLocation("block/lava_flow");
@Override
public ResourceLocation getStillTexture()
{
public ResourceLocation getStillTexture() {
return LAVA_STILL;
}
@Override
public ResourceLocation getFlowingTexture()
{
public ResourceLocation getFlowingTexture() {
return LAVA_FLOW;
}
});
@@ -390,21 +375,18 @@ public class ForgeMod
public static final RegistryObject<Fluid> FLOWING_MILK = RegistryObject.create(new ResourceLocation("flowing_milk"), ForgeRegistries.FLUIDS);
private static ForgeMod INSTANCE;
public static ForgeMod getInstance()
{
public static ForgeMod getInstance() {
return INSTANCE;
}
/**
* Run this method during mod constructor to enable milk and add it to the Minecraft milk bucket
*/
public static void enableMilkFluid()
{
public static void enableMilkFluid() {
enableMilkFluid = true;
}
public ForgeMod()
{
public ForgeMod() {
LOGGER.info(FORGEMOD,"Forge mod loading, version {}, for MC {} with MCP {}", ForgeVersion.getVersion(), MCPVersion.getMCVersion(), MCPVersion.getMCPVersion());
ForgeSnapshotsMod.logStartupWarning();
INSTANCE = this;
@@ -415,7 +397,8 @@ public class ForgeMod
return uuid.toString();
});
LOGGER.debug(FORGEMOD, "Loading Network data for FML net version: {}", NetworkConstants.init());
NetworkInitialization.init();
CrashReportCallables.registerCrashCallable("FML", ForgeVersion::getSpec);
CrashReportCallables.registerCrashCallable("Forge", ()->ForgeVersion.getGroup()+":"+ForgeVersion.getVersion());
@@ -440,7 +423,6 @@ public class ForgeMod
HOLDER_SET_TYPES.register(modEventBus);
VANILLA_FLUID_TYPES.register(modEventBus);
MinecraftForge.EVENT_BUS.addListener(this::serverStopping);
MinecraftForge.EVENT_BUS.addListener(this::missingSoundMapping);
ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, ForgeConfig.clientSpec);
ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, ForgeConfig.serverSpec);
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, ForgeConfig.commonSpec);
@@ -454,6 +436,7 @@ public class ForgeMod
MinecraftForge.EVENT_BUS.register(MinecraftForge.INTERNAL_HANDLER);
MinecraftForge.EVENT_BUS.addListener(this::mappingChanged);
MinecraftForge.EVENT_BUS.addListener(this::registerPermissionNodes);
MinecraftForge.EVENT_BUS.register(new ForgeNetworkConfigurationHandler());
ForgeRegistries.ITEMS.tags().addOptionalTagDefaults(Tags.Items.ENCHANTING_FUELS, Set.of(ForgeRegistries.ITEMS.getDelegateOrThrow(Items.LAPIS_LAZULI)));
@@ -462,28 +445,23 @@ public class ForgeMod
addAlias(ForgeRegistries.ATTRIBUTES, new ResourceLocation("forge", "attack_range"), new ResourceLocation("forge", "entity_reach"));
}
public void preInit(FMLCommonSetupEvent evt)
{
public void preInit(FMLCommonSetupEvent evt) {
VersionChecker.startVersionCheck();
//VanillaPacketSplitter.register();
}
public void loadComplete(FMLLoadCompleteEvent event)
{
public void loadComplete(FMLLoadCompleteEvent event) {
}
public void serverStopping(ServerStoppingEvent evt)
{
public void serverStopping(ServerStoppingEvent evt) {
WorldWorkerManager.clear();
}
public void mappingChanged(IdMappingEvent evt)
{
public void mappingChanged(IdMappingEvent evt) {
Ingredient.invalidateAll();
}
public void gatherData(GatherDataEvent event)
{
public void gatherData(GatherDataEvent event) {
DataGenerator gen = event.getGenerator();
PackOutput packOutput = gen.getPackOutput();
CompletableFuture<HolderLookup.Provider> lookupProvider = event.getLookupProvider();
@@ -509,33 +487,9 @@ public class ForgeMod
gen.addProvider(event.includeClient(), new VanillaSoundDefinitionsProvider(packOutput, existingFileHelper));
}
public void missingSoundMapping(MissingMappingsEvent event)
{
if (event.getKey() != ForgeRegistries.Keys.SOUND_EVENTS)
return;
//Removed in 1.15, see https://minecraft.gamepedia.com/Parrot#History
List<String> removedSounds = Arrays.asList("entity.parrot.imitate.panda", "entity.parrot.imitate.zombie_pigman", "entity.parrot.imitate.enderman", "entity.parrot.imitate.polar_bear", "entity.parrot.imitate.wolf");
for (MissingMappingsEvent.Mapping<SoundEvent> mapping : event.getAllMappings(ForgeRegistries.Keys.SOUND_EVENTS))
{
ResourceLocation regName = mapping.getKey();
if (regName != null && regName.getNamespace().equals("minecraft"))
{
String path = regName.getPath();
if (removedSounds.stream().anyMatch(s -> s.equals(path)))
{
LOGGER.info("Ignoring removed minecraft sound {}", regName);
mapping.ignore();
}
}
}
}
// done in an event instead of deferred to only enable if a mod requests it
public void registerFluids(RegisterEvent event)
{
if (enableMilkFluid)
{
public void registerFluids(RegisterEvent event) {
if (enableMilkFluid) {
// register milk fill, empty sounds (delegates to water fill, empty sounds)
event.register(ForgeRegistries.Keys.SOUND_EVENTS, helper -> {
helper.register(BUCKET_EMPTY_MILK.getId(), SoundEvent.createVariableRangeEvent(BUCKET_EMPTY_MILK.getId()));
@@ -544,28 +498,23 @@ public class ForgeMod
// register fluid type
event.register(ForgeRegistries.Keys.FLUID_TYPES, helper -> helper.register(MILK_TYPE.getId(), new FluidType(
FluidType.Properties.create().density(1024).viscosity(1024)
.sound(SoundActions.BUCKET_FILL, BUCKET_FILL_MILK.get())
.sound(SoundActions.BUCKET_EMPTY, BUCKET_EMPTY_MILK.get())
)
{
FluidType.Properties.create().density(1024).viscosity(1024)
.sound(SoundActions.BUCKET_FILL, BUCKET_FILL_MILK.get())
.sound(SoundActions.BUCKET_EMPTY, BUCKET_EMPTY_MILK.get())
) {
@Override
public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer)
{
consumer.accept(new IClientFluidTypeExtensions()
{
private static final ResourceLocation MILK_STILL = new ResourceLocation("forge", "block/milk_still"),
MILK_FLOW = new ResourceLocation("forge", "block/milk_flowing");
public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) {
consumer.accept(new IClientFluidTypeExtensions() {
private static final ResourceLocation MILK_STILL = new ResourceLocation("forge", "block/milk_still");
private static final ResourceLocation MILK_FLOW = new ResourceLocation("forge", "block/milk_flowing");
@Override
public ResourceLocation getStillTexture()
{
public ResourceLocation getStillTexture() {
return MILK_STILL;
}
@Override
public ResourceLocation getFlowingTexture()
{
public ResourceLocation getFlowingTexture() {
return MILK_FLOW;
}
});
@@ -583,24 +532,20 @@ public class ForgeMod
}
}
public void registerVanillaDisplayContexts(RegisterEvent event)
{
if (event.getRegistryKey().equals(ForgeRegistries.Keys.DISPLAY_CONTEXTS))
{
public void registerVanillaDisplayContexts(RegisterEvent event) {
if (event.getRegistryKey().equals(ForgeRegistries.Keys.DISPLAY_CONTEXTS)) {
IForgeRegistryInternal<ItemDisplayContext> forgeRegistry = (IForgeRegistryInternal<ItemDisplayContext>) event.<ItemDisplayContext>getForgeRegistry();
if (forgeRegistry == null)
throw new IllegalStateException("Item display context was not a forge registry, wtf???");
Arrays.stream(ItemDisplayContext.values())
.filter(Predicate.not(ItemDisplayContext::isModded))
.forEach(ctx -> forgeRegistry.register(ctx.getId(), new ResourceLocation("minecraft", ctx.getSerializedName()), ctx));
.filter(Predicate.not(ItemDisplayContext::isModded))
.forEach(ctx -> forgeRegistry.register(ctx.getId(), new ResourceLocation("minecraft", ctx.getSerializedName()), ctx));
}
}
public void registerRecipeSerializers(RegisterEvent event)
{
if (event.getRegistryKey().equals(ForgeRegistries.Keys.RECIPE_SERIALIZERS))
{
public void registerRecipeSerializers(RegisterEvent event) {
if (event.getRegistryKey().equals(ForgeRegistries.Keys.RECIPE_SERIALIZERS)) {
CraftingHelper.register(AndCondition.Serializer.INSTANCE);
CraftingHelper.register(FalseCondition.Serializer.INSTANCE);
CraftingHelper.register(ItemExistsCondition.Serializer.INSTANCE);
@@ -623,8 +568,7 @@ public class ForgeMod
}
}
public void registerLootData(RegisterEvent event)
{
public void registerLootData(RegisterEvent event) {
if (!event.getRegistryKey().equals(Registries.LOOT_CONDITION_TYPE))
return;
@@ -635,8 +579,7 @@ public class ForgeMod
public static final PermissionNode<Boolean> USE_SELECTORS_PERMISSION = new PermissionNode<>("forge", "use_entity_selectors",
PermissionTypes.BOOLEAN, (player, uuid, contexts) -> player != null && player.hasPermissions(Commands.LEVEL_GAMEMASTERS));
public void registerPermissionNodes(PermissionGatherEvent.Nodes event)
{
public void registerPermissionNodes(PermissionGatherEvent.Nodes event) {
event.addNodes(USE_SELECTORS_PERMISSION);
}
@@ -644,8 +587,7 @@ public class ForgeMod
* TODO: Remove when {@link ForgeRegistry#addAlias(ResourceLocation, ResourceLocation)} is elevated to {@link IForgeRegistry}.
*/
@Deprecated(forRemoval = true, since = "1.20")
private static <T> void addAlias(IForgeRegistry<T> registry, ResourceLocation from, ResourceLocation to)
{
private static <T> void addAlias(IForgeRegistry<T> registry, ResourceLocation from, ResourceLocation to) {
ForgeRegistry<T> fReg = (ForgeRegistry<T>) registry;
fReg.addAlias(from, to);
}
@@ -31,26 +31,28 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ClientPlayerNetworkEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.network.CustomPayloadEvent;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.loading.toposort.TopologicalSort;
import net.minecraftforge.network.ChannelBuilder;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;
import net.minecraftforge.network.SimpleChannel;
import net.minecraftforge.server.ServerLifecycleHooks;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.util.*;
import java.util.function.Supplier;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
public class TierSortingRegistry
{
public class TierSortingRegistry {
private static final Logger LOGGER = LogManager.getLogger();
private static final ResourceLocation ITEM_TIER_ORDERING_JSON = new ResourceLocation("forge", "item_tier_ordering.json");
@@ -61,8 +63,7 @@ public class TierSortingRegistry
* @param after List of tiers to place this tier after (the tiers in the list will be considered lesser tiers)
* @param before List of tiers to place this tier before (the tiers in the list will be considered better tiers)
*/
public static synchronized Tier registerTier(Tier tier, ResourceLocation name, List<Object> after, List<Object> before)
{
public static synchronized Tier registerTier(Tier tier, ResourceLocation name, List<Object> after, List<Object> before) {
if (tiers.containsKey(name))
throw new IllegalStateException("Duplicate tier name " + name);
@@ -77,8 +78,7 @@ public class TierSortingRegistry
* This list will remain valid
* @return An unmodifiable list of tiers ordered lesser to greater
*/
public static List<Tier> getSortedTiers()
{
public static List<Tier> getSortedTiers() {
return sortedTiersUnmodifiable;
}
@@ -88,8 +88,7 @@ public class TierSortingRegistry
* @return The tier, or null if not registered
*/
@Nullable
public static Tier byName(ResourceLocation name)
{
public static Tier byName(ResourceLocation name) {
return tiers.get(name);
}
@@ -99,8 +98,7 @@ public class TierSortingRegistry
* @return The name for the tier, or null if not registered
*/
@Nullable
public static ResourceLocation getName(Tier tier)
{
public static ResourceLocation getName(Tier tier) {
return tiers.inverse().get(tier);
}
@@ -109,8 +107,7 @@ public class TierSortingRegistry
* @param tier The tier to query
* @return True if isCorrectTierForDrops should be called for the tier
*/
public static boolean isTierSorted(Tier tier)
{
public static boolean isTierSorted(Tier tier) {
return getName(tier) != null;
}
@@ -120,8 +117,7 @@ public class TierSortingRegistry
* @param state The state to test against
* @return True if the tier is good enough
*/
public static boolean isCorrectTierForDrops(Tier tier, BlockState state)
{
public static boolean isCorrectTierForDrops(Tier tier, BlockState state) {
if (!isTierSorted(tier))
return isCorrectTierVanilla(tier, state);
@@ -138,8 +134,7 @@ public class TierSortingRegistry
* @param tier The tier
* @return All the lower tiers
*/
public static List<Tier> getTiersLowerThan(Tier tier)
{
public static List<Tier> getTiersLowerThan(Tier tier) {
if (!isTierSorted(tier)) return List.of();
return sortedTiers.stream().takeWhile(t -> t != tier).toList();
}
@@ -149,41 +144,27 @@ public class TierSortingRegistry
/**
* Fallback for when a tier isn't in the registry, copy of the logic in {@link DiggerItem#isCorrectToolForDrops}
*/
private static boolean isCorrectTierVanilla(Tier tier, BlockState state)
{
private static boolean isCorrectTierVanilla(Tier tier, BlockState state) {
@SuppressWarnings("deprecation")
int i = tier.getLevel();
if (i < 3 && state.is(BlockTags.NEEDS_DIAMOND_TOOL))
{
return false;
}
else if (i < 2 && state.is(BlockTags.NEEDS_IRON_TOOL))
{
return false;
}
else if (i < 1 && state.is(BlockTags.NEEDS_STONE_TOOL))
{
return false;
}
return true;
}
private static void processTier(Tier tier, ResourceLocation name, List<Object> afters, List<Object> befores)
{
private static void processTier(Tier tier, ResourceLocation name, List<Object> afters, List<Object> befores) {
tiers.put(name, tier);
for(Object after : afters)
{
ResourceLocation other = getTierName(after);
edges.put(other, name);
}
edges.put(getTierName(after), name);
for(Object before : befores)
{
ResourceLocation other = getTierName(before);
edges.put(name, other);
}
edges.put(name, getTierName(before));
}
private static ResourceLocation getTierName(Object entry)
{
private static ResourceLocation getTierName(Object entry) {
if (entry instanceof String s)
return new ResourceLocation(s);
if (entry instanceof ResourceLocation rl)
@@ -218,63 +199,55 @@ public class TierSortingRegistry
private static final List<Tier> sortedTiersUnmodifiable = Collections.unmodifiableList(sortedTiers);
private static final ResourceLocation CHANNEL_NAME = new ResourceLocation("forge:tier_sorting");
private static final String PROTOCOL_VERSION = "1.0";
private static final SimpleChannel SYNC_CHANNEL = NetworkRegistry.newSimpleChannel(
CHANNEL_NAME, () -> "1.0",
versionFromServer -> PROTOCOL_VERSION.equals(versionFromServer) || (allowVanilla() && NetworkRegistry.ACCEPTVANILLA.equals(versionFromServer)),
versionFromClient -> PROTOCOL_VERSION.equals(versionFromClient) || (allowVanilla() && NetworkRegistry.ACCEPTVANILLA.equals(versionFromClient))
);
private static final SimpleChannel SYNC_CHANNEL = ChannelBuilder
.named(CHANNEL_NAME)
.networkProtocolVersion(1)
.acceptedVersions((s, v) -> v == 1 || allowVanilla()) // Accepts vanilla unless we've got custom tiers
.simpleChannel()
.messageBuilder(SyncPacket.class, NetworkDirection.PLAY_TO_CLIENT)
.encoder(SyncPacket::encode)
.decoder(TierSortingRegistry::receive)
.consumerNetworkThread(TierSortingRegistry::handle)
.add();
static boolean allowVanilla()
{
static boolean allowVanilla() {
return !hasCustomTiers;
}
/*package private*/
static void init()
{
SYNC_CHANNEL.registerMessage(0, SyncPacket.class, SyncPacket::encode, TierSortingRegistry::receive, TierSortingRegistry::handle, Optional.of(NetworkDirection.PLAY_TO_CLIENT));
static void init() {
MinecraftForge.EVENT_BUS.addListener(TierSortingRegistry::playerLoggedIn);
if (FMLEnvironment.dist == Dist.CLIENT) ClientEvents.init();
if (FMLEnvironment.dist == Dist.CLIENT)
ClientEvents.init();
}
/*package private*/
static PreparableReloadListener getReloadListener()
{
return new SimplePreparableReloadListener<JsonObject>()
{
static PreparableReloadListener getReloadListener() {
return new SimplePreparableReloadListener<JsonObject>() {
final Gson gson = (new GsonBuilder()).create();
@NotNull
@Override
protected JsonObject prepare(@NotNull ResourceManager resourceManager, ProfilerFiller p)
{
protected JsonObject prepare(@NotNull ResourceManager resourceManager, ProfilerFiller p) {
Optional<Resource> res = resourceManager.getResource(ITEM_TIER_ORDERING_JSON);
if (res.isEmpty())
return new JsonObject();
try (Reader reader = res.get().openAsReader())
{
try (var reader = res.get().openAsReader()) {
return gson.fromJson(reader, JsonObject.class);
}
catch (IOException e)
{
} catch (IOException e) {
LOGGER.error("Could not read Tier sorting file " + ITEM_TIER_ORDERING_JSON, e);
return new JsonObject();
}
}
@Override
protected void apply(@NotNull JsonObject data, @NotNull ResourceManager resourceManager, ProfilerFiller p)
{
try
{
if (data.size() > 0)
{
protected void apply(@NotNull JsonObject data, @NotNull ResourceManager resourceManager, ProfilerFiller p) {
try {
if (data.size() > 0) {
JsonArray order = GsonHelper.getAsJsonArray(data, "order");
List<Tier> customOrder = new ArrayList<>();
for (JsonElement entry : order)
{
for (JsonElement entry : order) {
ResourceLocation id = new ResourceLocation(entry.getAsString());
Tier tier = byName(id);
if (tier == null) throw new IllegalStateException("Tier not found with name " + id);
@@ -288,9 +261,7 @@ public class TierSortingRegistry
setTierOrder(customOrder);
return;
}
}
catch(Exception e)
{
} catch(Exception e) {
LOGGER.error("Error parsing Tier sorting file " + ITEM_TIER_ORDERING_JSON, e);
}
@@ -299,15 +270,12 @@ public class TierSortingRegistry
};
}
@SuppressWarnings("UnstableApiUsage")
private static void recalculateItemTiers()
{
private static void recalculateItemTiers() {
final MutableGraph<Tier> graph = GraphBuilder.directed().nodeOrder(ElementOrder.<Tier>insertion()).build();
for(Tier tier : tiers.values())
{
graph.addNode(tier);
}
edges.forEach((key, value) -> {
if (tiers.containsKey(key) && tiers.containsKey(value))
graph.putEdge(tiers.get(key), tiers.get(value));
@@ -317,80 +285,65 @@ public class TierSortingRegistry
setTierOrder(tierList);
}
private static void setTierOrder(List<Tier> tierList)
{
private static void setTierOrder(List<Tier> tierList) {
runInServerThreadIfPossible(hasServer -> {
sortedTiers.clear();
sortedTiers.addAll(tierList);
if(hasServer) syncToAll();
if (hasServer)
syncToAll();
});
}
private static void runInServerThreadIfPossible(BooleanConsumer runnable)
{
private static void runInServerThreadIfPossible(BooleanConsumer runnable) {
MinecraftServer server = ServerLifecycleHooks.getCurrentServer();
if (server != null) server.execute(() -> runnable.accept(true));
else runnable.accept(false);
if (server != null)
server.execute(() -> runnable.accept(true));
else
runnable.accept(false);
}
private static void syncToAll()
{
for(ServerPlayer serverPlayer : ServerLifecycleHooks.getCurrentServer().getPlayerList().getPlayers())
{
private static void syncToAll() {
for (ServerPlayer serverPlayer : ServerLifecycleHooks.getCurrentServer().getPlayerList().getPlayers())
syncToPlayer(serverPlayer);
}
}
private static void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent event)
{
private static void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) {
if (event.getEntity() instanceof ServerPlayer serverPlayer)
{
syncToPlayer(serverPlayer);
}
}
private static void syncToPlayer(ServerPlayer serverPlayer)
{
private static void syncToPlayer(ServerPlayer serverPlayer) {
if (SYNC_CHANNEL.isRemotePresent(serverPlayer.connection.getConnection()) && !serverPlayer.connection.getConnection().isMemoryConnection())
{
SYNC_CHANNEL.send(PacketDistributor.PLAYER.with(() -> serverPlayer), new SyncPacket(sortedTiers.stream().map(TierSortingRegistry::getName).toList()));
}
SYNC_CHANNEL.send(new SyncPacket(sortedTiers.stream().map(TierSortingRegistry::getName).toList()), PacketDistributor.PLAYER.with(serverPlayer));
}
private static SyncPacket receive(FriendlyByteBuf buffer)
{
private static SyncPacket receive(FriendlyByteBuf buffer) {
int count = buffer.readVarInt();
List<ResourceLocation> list = new ArrayList<>();
for(int i=0;i<count;i++)
for(int i = 0; i < count; i++)
list.add(buffer.readResourceLocation());
return new SyncPacket(list);
}
private static void handle(SyncPacket packet, Supplier<NetworkEvent.Context> context)
{
private static void handle(SyncPacket packet, CustomPayloadEvent.Context context) {
setTierOrder(packet.tiers.stream().map(TierSortingRegistry::byName).toList());
context.get().setPacketHandled(true);
context.setPacketHandled(true);
}
private record SyncPacket(List<ResourceLocation> tiers)
{
private void encode(FriendlyByteBuf buffer)
{
private record SyncPacket(List<ResourceLocation> tiers) {
private void encode(FriendlyByteBuf buffer) {
buffer.writeVarInt(tiers.size());
for(ResourceLocation loc : tiers)
buffer.writeResourceLocation(loc);
}
}
private static class ClientEvents
{
public static void init()
{
private static class ClientEvents {
public static void init() {
MinecraftForge.EVENT_BUS.addListener(ClientEvents::clientLogInToServer);
}
private static void clientLogInToServer(ClientPlayerNetworkEvent.LoggingIn event)
{
private static void clientLogInToServer(ClientPlayerNetworkEvent.LoggingIn event) {
if (event.getConnection() == null || !event.getConnection().isMemoryConnection())
recalculateItemTiers();
}
@@ -19,11 +19,9 @@ import java.util.Objects;
/**
* Extension-Interface providing methods for writing registry-id's instead of their registry-names.
*/
public interface IForgeFriendlyByteBuf
{
private FriendlyByteBuf self()
{
return (FriendlyByteBuf) this;
public interface IForgeFriendlyByteBuf {
private FriendlyByteBuf self() {
return (FriendlyByteBuf)this;
}
/**
@@ -33,8 +31,7 @@ public interface IForgeFriendlyByteBuf
* @param entry The entry who's registryName is to be written
* @param <T> The type of the entry.
*/
default <T> void writeRegistryIdUnsafe(@NotNull IForgeRegistry<T> registry, @NotNull T entry)
{
default <T> void writeRegistryIdUnsafe(@NotNull IForgeRegistry<T> registry, @NotNull T entry) {
ForgeRegistry<T> forgeRegistry = (ForgeRegistry<T>) registry;
int id = forgeRegistry.getID(entry);
self().writeVarInt(id);
@@ -46,8 +43,7 @@ public interface IForgeFriendlyByteBuf
* @param registry The registry containing the entry represented by this key
* @param entryKey The registry-name of an entry in this {@link IForgeRegistry}
*/
default void writeRegistryIdUnsafe(@NotNull IForgeRegistry<?> registry, @NotNull ResourceLocation entryKey)
{
default void writeRegistryIdUnsafe(@NotNull IForgeRegistry<?> registry, @NotNull ResourceLocation entryKey) {
ForgeRegistry<?> forgeRegistry = (ForgeRegistry<?>) registry;
int id = forgeRegistry.getID(entryKey);
self().writeVarInt(id);
@@ -58,8 +54,7 @@ public interface IForgeFriendlyByteBuf
* read id, that the registry's default value will be returned.
* @param registry The registry containing the entry
*/
default <T> T readRegistryIdUnsafe(@NotNull IForgeRegistry<T> registry)
{
default <T> T readRegistryIdUnsafe(@NotNull IForgeRegistry<T> registry) {
ForgeRegistry<T> forgeRegistry = (ForgeRegistry<T>) registry;
int id = self().readVarInt();
return forgeRegistry.getValue(id);
@@ -77,8 +72,7 @@ public interface IForgeFriendlyByteBuf
* @throws NullPointerException if the registry or entry was null
* @throws IllegalArgumentException if the registry does not contain the specified value
*/
default <T> void writeRegistryId(@NotNull IForgeRegistry<T> registry, @NotNull T entry)
{
default <T> void writeRegistryId(@NotNull IForgeRegistry<T> registry, @NotNull T entry) {
Objects.requireNonNull(registry, "Cannot write a null registry key!");
Objects.requireNonNull(entry,"Cannot write a null registry entry!");
ResourceLocation name = registry.getRegistryName();
@@ -94,8 +88,7 @@ public interface IForgeFriendlyByteBuf
* @param <T> The type of the registry-entry. Notice that this should match the actual type written to the buffer.
* @throws NullPointerException if the registry could not be found.
*/
default <T> T readRegistryId()
{
default <T> T readRegistryId() {
ResourceLocation location = self().readResourceLocation(); //TODO change to reading a varInt once registries use id's
ForgeRegistry<T> registry = RegistryManager.ACTIVE.getRegistry(location);
return registry.getValue(self().readVarInt());
@@ -107,8 +100,7 @@ public interface IForgeFriendlyByteBuf
* @throws IllegalArgumentException if the retrieved entries registryType doesn't match the one passed in.
* @throws NullPointerException if the registry could not be found.
*/
default <T> T readRegistryIdSafe(Class<? super T> registrySuperType)
{
default <T> T readRegistryIdSafe(Class<? super T> registrySuperType) {
T value = readRegistryId();
if (!registrySuperType.isAssignableFrom(value.getClass()))
throw new IllegalArgumentException("Attempted to read an registryValue of the wrong type from the Buffer!");
@@ -121,11 +113,10 @@ public interface IForgeFriendlyByteBuf
*
* @param stack FluidStack to be written to the packet buffer.
*/
default void writeFluidStack(FluidStack stack)
{
if (stack.isEmpty()) {
default void writeFluidStack(FluidStack stack) {
if (stack.isEmpty())
self().writeBoolean(false);
} else {
else {
self().writeBoolean(true);
stack.writeToPacket(self());
}
@@ -134,8 +125,7 @@ public interface IForgeFriendlyByteBuf
/**
* Reads a FluidStack from this buffer.
*/
default FluidStack readFluidStack()
{
default FluidStack readFluidStack() {
return !self().readBoolean() ? FluidStack.EMPTY : FluidStack.readFromPacket(self());
}
}
@@ -12,12 +12,10 @@ import net.minecraft.world.inventory.MenuType;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.IContainerFactory;
public interface IForgeMenuType<T>
{
static <T extends AbstractContainerMenu> MenuType<T> create(IContainerFactory<T> factory)
{
public interface IForgeMenuType<T> {
static <T extends AbstractContainerMenu> MenuType<T> create(IContainerFactory<T> factory) {
return new MenuType<>(factory, FeatureFlags.DEFAULT_FLAGS);
}
T create(int windowId, Inventory playerInv, FriendlyByteBuf extraData);
}
@@ -0,0 +1,79 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.extensions;
import java.util.function.Consumer;
import io.netty.buffer.Unpooled;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.MenuProvider;
import net.minecraftforge.client.ConfigScreenHandler;
import net.minecraftforge.event.ForgeEventFactory;
import net.minecraftforge.network.NetworkInitialization;
import net.minecraftforge.network.packets.OpenContainer;
public interface IForgeServerPlayer {
private ServerPlayer self() {
return (ServerPlayer)this;
}
/**
* Request to open a GUI on the client, from the server
*
* Refer to {@link ConfigScreenHandler.ConfigScreenFactory} for how to provide a function to consume
* these GUI requests on the client.
*
* @param player The player to open the GUI for
* @param containerSupplier A supplier of container properties including the registry name of the container
* @param pos A block pos, which will be encoded into the auxillary data for this request
*/
default void openMenu(MenuProvider containerSupplier, BlockPos pos) {
openMenu(containerSupplier, buf -> buf.writeBlockPos(pos));
}
/**
* Request to open a GUI on the client, from the server
*
* Refer to {@link ConfigScreenHandler.ConfigScreenFactory} for how to provide a function to consume
* these GUI requests on the client.
*
* The maximum size for #extraDataWriter is 32600 bytes.
*
* @param player The player to open the GUI for
* @param containerSupplier A supplier of container properties including the registry name of the container
* @param extraDataWriter Consumer to write any additional data the GUI needs
*/
@SuppressWarnings("resource")
default void openMenu(MenuProvider containerSupplier, Consumer<FriendlyByteBuf> extraDataWriter) {
var player = self();
if (player.level().isClientSide) return;
player.doCloseContainer();
player.nextContainerCounter();
int openContainerId = player.containerCounter;
FriendlyByteBuf extraData = new FriendlyByteBuf(Unpooled.buffer());
extraDataWriter.accept(extraData);
extraData.readerIndex(0); // reset to beginning in case modders read for whatever reason
FriendlyByteBuf output = new FriendlyByteBuf(Unpooled.buffer());
output.writeVarInt(extraData.readableBytes());
output.writeBytes(extraData);
if (output.readableBytes() > 32600 || output.readableBytes() < 1)
throw new IllegalArgumentException("Invalid PacketBuffer for openGui, found "+ output.readableBytes()+ " bytes");
var c = containerSupplier.createMenu(openContainerId, player.getInventory(), player);
if (c == null)
return;
var msg = new OpenContainer(c.getType(), openContainerId, containerSupplier.getDisplayName(), output);
NetworkInitialization.PLAY.send(msg, player.connection.getConnection());
player.containerMenu = c;
player.initMenu(player.containerMenu);
ForgeEventFactory.onPlayerOpenContainer(player, c);
}
}
@@ -18,11 +18,8 @@ import io.netty.buffer.ByteBuf;
* Length: 34
*</PRE>
*/
public class HexDumper
{
public static String dump(ByteBuf data)
{
public class HexDumper {
public static String dump(ByteBuf data) {
int current = data.readerIndex();
data.readerIndex(0);
Instance inst = new Instance(current, data.readableBytes());
@@ -34,29 +31,25 @@ public class HexDumper
return inst.finish();
}
public static String dump(byte[] data)
{
public static String dump(byte[] data) {
return dump(data, -1);
}
public static String dump(byte[] data, int marker)
{
public static String dump(byte[] data, int marker) {
Instance inst = new Instance(marker, data.length);
for (int x = 0; x < data.length; x++)
inst.add(data[x]);
return inst.finish();
}
private static class Instance
{
private static class Instance {
private static final String HEX = "0123456789ABCDEF";
private final int marked;
private final StringBuilder buf;
private char[] ascii = new char[16];
private int index = 0;
private Instance(int marked, int size)
{
private Instance(int marked, int size) {
this.marked = marked;
int lines = ((size + 15) / 16);
this.buf = new StringBuilder((size * 3) //Hex
@@ -68,16 +61,13 @@ public class HexDumper
ascii[x] = ' ';
}
public void add(byte data)
{
public void add(byte data) {
if (index == 0 && marked != -1)
buf.append(index == marked ? '<' : ' ');
if (index != 0 && index % 16 == 0)
{
if (index != 0 && index % 16 == 0) {
buf.append('\t');
for (int x = 0; x < 16; x++)
{
for (int x = 0; x < 16; x++) {
buf.append(ascii[x]);
ascii[x] = ' ';
}
@@ -96,11 +86,9 @@ public class HexDumper
index++;
}
public String finish()
{
public String finish() {
int padding = 16 - (index % 16);
if (padding > 0)
{
if (padding > 0) {
for (int x = 0; x < padding * 3; x++)
buf.append(' ');
buf.append('\t');
@@ -0,0 +1,63 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.util;
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 io.netty.buffer.Unpooled;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket;
import net.minecraftforge.network.ICustomPacket;
/*
* This is a utility class that just dumps packets to the logger.
* If people care I can make this a public API. Makes life a lot easier
* when debugging network things. But it doesn't have a proper API cuz I haven't felt like designing one.
*/
public class PacketLogger {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker MARKER = MarkerManager.getMarker("PACKETLOG");
private final Connection connection;
public boolean enabled = false;
public PacketLogger(Connection connection) {
this.connection = connection;
}
public void send(Packet<?> packet) {
common(connection.getReceiving(), connection.getSending(), packet);
}
public void recv( Packet<?> packet) {
common(connection.getReceiving(), connection.getReceiving(), packet);
}
private void common(PacketFlow side, PacketFlow flow, Packet<?> packet) {
if (!enabled) return;
if (packet instanceof ClientboundFinishConfigurationPacket)
enabled = false;
if (packet instanceof ICustomPacket) {
var data = new FriendlyByteBuf(Unpooled.buffer());
packet.write(data);
LOGGER.info(MARKER, "{} {} {}\n{}", side, dir(flow), packet.getClass().getName(), HexDumper.dump(data));
} else {
LOGGER.info(MARKER, "{} {} {}", side, dir(flow), packet.getClass().getName());
}
}
private static String dir(PacketFlow flow) {
return flow == PacketFlow.CLIENTBOUND ? "S->C" : "C->S";
}
}
@@ -6,21 +6,18 @@
package net.minecraftforge.event;
import java.io.File;
import java.util.*;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import com.mojang.authlib.GameProfile;
import com.mojang.blaze3d.platform.Window;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.advancements.AdvancementHolder;
import net.minecraft.advancements.AdvancementProgress;
import net.minecraft.client.MouseHandler;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererProvider.Context;
import net.minecraft.client.resources.PlayerSkin.Model;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.core.Holder;
import net.minecraft.core.RegistryAccess;
@@ -58,6 +55,7 @@ import net.minecraft.world.entity.monster.Zombie;
import net.minecraft.world.entity.animal.Animal;
import net.minecraft.world.entity.player.Player;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ConfigurationTask;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.item.crafting.RecipeType;
@@ -77,6 +75,7 @@ import net.minecraft.sounds.SoundEvent;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.phys.HitResult;
import net.minecraft.network.Connection;
import net.minecraft.network.chat.Component;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.GameRules;
@@ -88,9 +87,6 @@ import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.storage.ServerLevelData;
import net.minecraft.world.level.storage.PlayerDataStorage;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.event.EntityRenderersEvent;
import net.minecraftforge.client.event.InputEvent;
import net.minecraftforge.client.event.ScreenEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.ToolAction;
import net.minecraftforge.common.capabilities.CapabilityDispatcher;
@@ -153,12 +149,13 @@ import net.minecraftforge.event.level.ExplosionEvent;
import net.minecraftforge.event.level.PistonEvent;
import net.minecraftforge.event.level.SaplingGrowTreeEvent;
import net.minecraftforge.event.level.SleepFinishedTimeEvent;
import net.minecraftforge.event.network.ChannelRegistrationChangeEvent;
import net.minecraftforge.event.network.ConnectionStartEvent;
import net.minecraftforge.event.network.GatherLoginConfigurationTasksEvent;
import net.minecraftforge.event.level.LevelEvent;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.Event.Result;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.ModLoader;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -799,70 +796,19 @@ public class ForgeEventFactory {
public static void onChunkDataSave(ChunkAccess chunk, LevelAccessor world, CompoundTag data) {
post(new ChunkDataEvent.Save(chunk, world, data));
}
public static void gatherLayers(Map<EntityType<?>, EntityRenderer<?>> renderers, Map<Model, EntityRenderer<? extends Player>> playerRenderers, Context context) {
// TODO: Why is this a ModLoader event...
ModLoader.get().postEvent(new EntityRenderersEvent.AddLayers(renderers, playerRenderers, context));
}
public static boolean onScreenMouseReleasedPre(Screen guiScreen, double mouseX, double mouseY, int button) {
return post(new ScreenEvent.MouseButtonReleased.Pre(guiScreen, mouseX, mouseY, button));
}
public static boolean onScreenMouseReleasedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) {
var result = fire(new ScreenEvent.MouseButtonReleased.Post(guiScreen, mouseX, mouseY, button, handled)).getResult();
return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW;
}
public static boolean onScreenMouseClickedPre(Screen guiScreen, double mouseX, double mouseY, int button) {
return post(new ScreenEvent.MouseButtonPressed.Pre(guiScreen, mouseX, mouseY, button));
}
public static boolean onScreenMouseClickedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) {
var result = fire(new ScreenEvent.MouseButtonPressed.Post(guiScreen, mouseX, mouseY, button, handled)).getResult();
return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW;
}
public static boolean onMouseButtonPre(int button, int action, int mods) {
return post(new InputEvent.MouseButton.Pre(button, action, mods));
}
public static void onMouseButtonPost(int button, int action, int mods) {
post(new InputEvent.MouseButton.Post(button, action, mods));
}
public static boolean onScreenMouseScrollPre(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) {
return post(new ScreenEvent.MouseScrolled.Pre(guiScreen, mouseX, mouseY, deltaX, deltaY));
}
public static void onScreenMouseScrollPost(Screen guiScreen, double mouseX, double mouseY, double deltaX, double deltaY) {
post(new ScreenEvent.MouseScrolled.Post(guiScreen, mouseX, mouseY, deltaX, deltaY));
}
public static boolean onMouseScroll(MouseHandler mouseHelper, double deltaX, double deltaY) {
return post(new InputEvent.MouseScrollingEvent(deltaX, deltaY, mouseHelper.isLeftPressed(), mouseHelper.isMiddlePressed(), mouseHelper.isRightPressed(), mouseHelper.xpos(), mouseHelper.ypos()));
}
public static boolean onScreenMouseDragPre(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) {
return post(new ScreenEvent.MouseDragged.Pre(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY));
}
public static void onScreenMouseDragPost(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) {
post(new ScreenEvent.MouseDragged.Post(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY));
}
public static @Nullable Screen onScreenOpening(Screen old, Screen screen) {
var event = new ScreenEvent.Opening(old, screen);
if (post(event))
return null;
return event.getNewScreen();
}
public static void onScreenClose(Screen screen) {
post(new ScreenEvent.Closing(screen));
}
public static void onGameShuttingDown() {
post(new GameShuttingDownEvent());
}
public static void gatherLoginConfigTasks(Connection connection, Consumer<ConfigurationTask> add) {
post(new GatherLoginConfigurationTasksEvent(connection, add));
}
public static void onConnectionStart(Connection connection) {
post(new ConnectionStartEvent(connection));
}
public static void onChannelRegistrationChange(Connection connection, ChannelRegistrationChangeEvent.Type changeType, HashSet<ResourceLocation> changed) {
post(new ChannelRegistrationChangeEvent(connection, changeType, changed));
}
}
@@ -1,64 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.event.entity.player;
import com.mojang.authlib.GameProfile;
import net.minecraft.network.Connection;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.Event;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
/**
* This event is fired on the server when a connection has started the Forge handshake,
* Forge will wait for all enqueued work to be completed before proceeding further with the login process.
* <br>
* This event can be used to delay the player login until any necessary work such as preloading user data has completed.
* <br>
* This event is fired on the {@link MinecraftForge#EVENT_BUS}.
*/
public class PlayerNegotiationEvent extends Event
{
private final Connection connection;
private final GameProfile profile;
private final List<Future<Void>> futures;
public PlayerNegotiationEvent(Connection connection, GameProfile profile, List<Future<Void>> futures)
{
this.connection = connection;
this.profile = profile;
this.futures = futures;
}
/**
* Enqueue work to be completed asynchronously before the login proceeds.
*/
public void enqueueWork(Runnable runnable)
{
enqueueWork(CompletableFuture.runAsync(runnable));
}
/**
* Enqueue work to be completed asynchronously before the login proceeds.
*/
public void enqueueWork(Future<Void> future)
{
futures.add(future);
}
public Connection getConnection()
{
return connection;
}
public GameProfile getProfile()
{
return profile;
}
}
@@ -0,0 +1,47 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.event.network;
import java.util.Collections;
import java.util.Set;
import net.minecraft.network.Connection;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.eventbus.api.Event;
/**
* Fired when the channel registration (see minecraft custom channel documentation) changes.
*
* It seems plausible that this will fire multiple times for the same state, depending on what the server is doing.
* It just directly dispatches upon receipt.
*/
public class ChannelRegistrationChangeEvent extends Event {
public enum Type {
REGISTER, UNREGISTER;
}
private final Connection source;
private final Type changeType;
private final Set<ResourceLocation> channels;
public ChannelRegistrationChangeEvent(Connection source, Type changeType, Set<ResourceLocation> channels) {
this.source = source;
this.changeType = changeType;
this.channels = Collections.unmodifiableSet(channels);
}
public Type getType() {
return changeType;
}
public Connection getSource() {
return source;
}
public Set<ResourceLocation> getChannels() {
return channels;
}
}
@@ -0,0 +1,36 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.event.network;
import org.jetbrains.annotations.ApiStatus;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraftforge.eventbus.api.Event;
/**
* Fired when a network connection is started, either on the server when it receives the
* ClientIntentionPacket or on the client when the channel is first activated. This is
* intended to allow modders to attach things to the channel that can be used in the future.
*
* As this is a blocking event modders can also do things like load data. Need some example uses.
*/
public class ConnectionStartEvent extends Event {
private final Connection connection;
@ApiStatus.Internal
public ConnectionStartEvent(Connection connection) {
this.connection = connection;
}
public Connection getConnection() {
return this.connection;
}
public boolean isClient() {
return this.connection.getSending() == PacketFlow.SERVERBOUND;
}
}
@@ -0,0 +1,134 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.event.network;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.network.PacketListener;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.util.thread.BlockableEventLoop;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.network.ICustomPacket;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.common.util.LogicalSidedProvider;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.CompletableFuture;
// TODO make this not an event, and instead move it to a callback in the Channel itself.
// But also expose it as a generic listener event for anyone who cares about it but is outside out channel control system.
public class CustomPayloadEvent extends Event {
private final ResourceLocation channel;
private final FriendlyByteBuf payload;
private final Context source;
private final int loginIndex;
public CustomPayloadEvent(ResourceLocation channel, FriendlyByteBuf payload, Context source, int loginIndex) {
this.channel = channel;
this.payload = payload;
this.source = source;
this.loginIndex = loginIndex;
}
public CustomPayloadEvent(ICustomPacket<?> payload, Context source) {
this(payload.getName(), payload.getInternalData(), source, payload.getIndex());
}
public ResourceLocation getChannel() {
return this.channel;
}
public FriendlyByteBuf getPayload() {
return payload;
}
public int getLoginIndex() {
return loginIndex;
}
public Context getSource() {
return source;
}
/**
* Context for {@link CustomPayloadEvent}
*/
public static class Context {
/**
* The {@link Connection} for this message.
*/
private final Connection connection;
/**
* The {@link NetworkDirection} this message has been received on.
*/
private final NetworkDirection networkDirection;
private boolean packetHandled;
public Context(Connection connection, NetworkDirection networkDirection) {
this.connection = connection;
this.networkDirection = networkDirection;
}
public boolean isClientSide() {
return getConnection().getReceiving() == PacketFlow.CLIENTBOUND;
}
public boolean isServerSide() {
return !isClientSide();
}
public NetworkDirection getDirection() {
return networkDirection;
}
public Connection getConnection() {
return connection;
}
public <T> Attribute<T> attr(AttributeKey<T> key) {
return connection.channel().attr(key);
}
public void setPacketHandled(boolean packetHandled) {
this.packetHandled = packetHandled;
}
public boolean getPacketHandled() {
return packetHandled;
}
public CompletableFuture<Void> enqueueWork(Runnable runnable) {
BlockableEventLoop<?> executor = LogicalSidedProvider.WORKQUEUE.get(getDirection().getReceptionSide());
// Must check ourselves as Minecraft will sometimes delay tasks even when they are received on the client thread
// Same logic as ThreadTaskExecutor#runImmediately without the join
if (!executor.isSameThread())
return executor.submitAsync(runnable); // Use the internal method so thread check isn't done twice
else {
runnable.run();
return CompletableFuture.completedFuture(null);
}
}
/**
* When available, gets the sender for packets that are sent from a client to the server.
*/
@Nullable
public ServerPlayer getSender() {
PacketListener netHandler = connection.getPacketListener();
if (netHandler instanceof ServerGamePacketListenerImpl handler)
return handler.player;
return null;
}
}
}
@@ -0,0 +1,34 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.event.network;
import java.util.function.Consumer;
import net.minecraft.network.Connection;
import net.minecraft.server.network.ConfigurationTask;
import net.minecraftforge.eventbus.api.Event;
/**
* Gathers tasks that need to be run during the initial login configuration.
* @see net.minecraft.server.network.ServerConfigurationPacketListenerImpl#startConfiguration() startConfiguration
*/
public class GatherLoginConfigurationTasksEvent extends Event {
private final Connection connection;
private final Consumer<ConfigurationTask> add;
public GatherLoginConfigurationTasksEvent(Connection connection, Consumer<ConfigurationTask> add) {
this.connection = connection;
this.add = add;
}
public Connection getConnection() {
return this.connection;
}
public void addTask(ConfigurationTask task) {
this.add.accept(task);
}
}
@@ -1,82 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.logging;
import io.netty.buffer.ByteBuf;
public class PacketDump
{
public static String getContentDump(ByteBuf buffer)
{
int currentLength = buffer.readableBytes();
StringBuffer returnString = new StringBuffer((currentLength * 3) + // The
// hex
(currentLength) + // The ascii
(currentLength / 4) + // The tabs/\n's
30); // The text
// returnString.append("Buffer contents:\n");
int i, j; // Loop variables
for (i = 0; i < currentLength; i++)
{
if ((i != 0) && (i % 16 == 0))
{
// If it's a multiple of 16 and i isn't null, show the ascii
returnString.append('\t');
for (j = i - 16; j < i; j++)
{
if (buffer.getByte(j) < 0x20 || buffer.getByte(j) > 0x7F)
returnString.append('.');
else
returnString.append((char) buffer.getByte(j));
}
// Add a linefeed after the string
returnString.append("\n");
}
returnString.append(Integer.toString((buffer.getByte(i) & 0xF0) >> 4, 16) + Integer.toString((buffer.getByte(i) & 0x0F) >> 0, 16));
returnString.append(' ');
}
// Add padding spaces if it's not a multiple of 16
if (i != 0 && i % 16 != 0)
{
for (j = 0; j < ((16 - (i % 16)) * 3); j++)
{
returnString.append(' ');
}
}
// Add the tab for alignment
returnString.append('\t');
// Add final characters at right, after padding
// If it was at the end of a line, print out the full line
if (i > 0 && (i % 16) == 0)
{
j = i - 16;
} else
{
j = (i - (i % 16));
}
for (; i >= 0 && j < i; j++)
{
if (buffer.getByte(j) < 0x20 || buffer.getByte(j) > 0x7F)
returnString.append('.');
else
returnString.append((char) buffer.getByte(j));
}
// Finally, tidy it all up with a newline
returnString.append('\n');
returnString.append("Length: " + currentLength);
return returnString.toString();
}
}
@@ -0,0 +1,163 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import java.util.Objects;
import java.util.function.IntPredicate;
import net.minecraft.network.Connection;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketFlow;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.event.network.CustomPayloadEvent;
import net.minecraftforge.network.packets.LoginWrapper;
public abstract class Channel<MSG> {
protected final NetworkInstance instance;
protected Channel(NetworkInstance instance) {
this.instance = instance;
}
public ResourceLocation getName() {
return instance.getChannelName();
}
public int getProtocolVersion() {
return instance.getNetworkProtocolVersion();
}
/**
* Returns true if the channel is present in the given connection.
*/
public boolean isRemotePresent(Connection connection) {
return NetworkContext.get(connection).getRemoteChannels().contains(getName());
}
protected abstract FriendlyByteBuf toBuffer(MSG message);
// Package private so we can call from ourselves.
Packet<?> toVanillaPacket(Connection connection, MSG message) {
var protocol = connection.getProtocol();
var serverbound = connection.getSending() == PacketFlow.SERVERBOUND;
var data = toBuffer(message);
if (protocol == ConnectionProtocol.LOGIN) {
// Login Protocol C->S packets do not contain the plugin channel name. As they are meant to be replies.
// So fuck it lets just wrap in our own packet that DOES include the channel name
if (serverbound) {
if (this != NetworkInitialization.LOGIN)
return NetworkInitialization.LOGIN.toVanillaPacket(connection, new LoginWrapper(getName(), data));
else
return NetworkDirection.LOGIN_TO_SERVER.buildPacket(data, getName()).getThis();
}
return NetworkDirection.LOGIN_TO_CLIENT.buildPacket(data, getName()).getThis();
} else if (protocol == ConnectionProtocol.PLAY || protocol == ConnectionProtocol.CONFIGURATION) {
var dir = serverbound ? NetworkDirection.PLAY_TO_SERVER : NetworkDirection.PLAY_TO_CLIENT;
return dir.buildPacket(toBuffer(message), getName()).getThis();
} else
throw new IllegalStateException("Unsupported protocol " + protocol.name() + " in Forge Networking Channel");
}
public void send(MSG msg, Connection connection) {
connection.send(toVanillaPacket(connection, msg));
}
/**
* Send a message to the {@link PacketDistributor.PacketTarget} from a {@link PacketDistributor} instance.
*
* <pre>
* channel.send(message, PacketDistributor.PLAYER.with(()->player))
* </pre>
*
* @param target The curried target from a PacketDistributor
* @param message The message to send
* @param <MSG> The type of the message
*/
public void send(MSG msg, PacketDistributor.PacketTarget target) {
target.send(target.direction().buildPacket(toBuffer(msg), getName()).getThis());
}
public void reply(MSG msg, CustomPayloadEvent.Context context) {
send(msg, context.getConnection());
}
@FunctionalInterface
public static interface VersionTest {
public static final VersionTest ACCEPT_MISSING = (status, version) -> status == Status.MISSING;
public static final VersionTest ACCEPT_VANILLA = (status, version) -> status == Status.VANILLA;
public static VersionTest exact(int version) {
return (status, remoteVersion) -> status == Status.PRESENT && version == remoteVersion;
}
public enum Status {
/**
* This value is used when the connection has not specified that it is modded,
* and has not sent a channel list. So we must assume that it is a unmodified vanilla environment.
*/
VANILLA,
/**
* This is used when we are on a modded connection that has sent a channel version
* list, but that list does not contain this channel.
*/
MISSING,
/**
* This is used when we are on a modded connection, the channel version list has been received
* and this channel is in the list. This is the only time that the version parameter of accept
* is valid.
*/
PRESENT;
}
/**
* Tests is the specified version is compatible with this channel.
* This determines if a we can communicate with a remote end.
*
* The status parameter specifies wither or not the remote knows about
* out channel or not. If the value is {@link Status#MISSING MISSING}
* or {@link Status#VANILLA VANILLA} then the version parameter is meaningless.
*
* If the status is {@link Status#PRESSENT PRESSENT} then the version
* parameter is the version presented by the remote connection.
*
* @return true if we should allow the connection
*/
boolean accepts(Status status, int version);
/**
* Returns a instance that represents the logical negation of this
* instance.
*/
default VersionTest negate() {
return (status, version) -> !accepts(status, version);
}
/**
* Returns a composed instance that represents a short-circuiting logical
* AND of this instance and another. When evaluating the composed
* instance, if this instance is {@code false}, then the {@code other}
* instance is not evaluated.
*/
default VersionTest and(VersionTest other) {
Objects.requireNonNull(other);
return (status, version) -> accepts(status, version) && other.accepts(status, version);
}
/**
* Returns a composed instance that represents a short-circuiting logical
* OR of this instance and another. When evaluating the composed
* instance, if this instance is {@code true}, then the {@code other}
* instance is not evaluated.
*/
default VersionTest or(VersionTest other) {
Objects.requireNonNull(other);
return (status, version) -> accepts(status, version) || other.accepts(status, version);
}
}
}
@@ -0,0 +1,216 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import io.netty.util.AttributeKey;
import net.minecraft.network.Connection;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.Channel.VersionTest;
/**
* Builder for constructing impl channels using a builder style API.
*/
public class ChannelBuilder {
private final ResourceLocation name;
private int networkProtocolVersion = 0;
private Channel.VersionTest clientAcceptedVersions;
private Channel.VersionTest serverAcceptedVersions;
private Map<AttributeKey<?>, Function<Connection, ?>> attributes = new HashMap<>();
private Consumer<Connection> connectionHandler;
/**
* Creates a new channel builder, The name of the channel must be unique.
* @param channelName The name of the channel
*/
public static ChannelBuilder named(String channelName) {
return named(new ResourceLocation(channelName));
}
/**
* Creates a new channel builder, The name of the channel must be unique.
* @param channelName The name of the channel
*/
public static ChannelBuilder named(ResourceLocation channelName) {
return new ChannelBuilder(channelName);
}
private ChannelBuilder(ResourceLocation name) {
this.name = name;
}
/**
* The impl protocol version for this channel. This will be gathered during login and sent to
* the remote partner, where it will be tested with against the relevant predicate.
* <br />
* Defaults to 0
*
* @see #serverAcceptedVersions(Predicate)
* @see #clientAcceptedVersions(Predicate)
*
* @throws IllegalArgumentException if version is < 0
*
*/
public ChannelBuilder networkProtocolVersion(int version) {
if (version < 0)
throw new IllegalArgumentException("Invalid network protocol: " + version);
this.networkProtocolVersion = version;
return this;
}
/**
* A predicate run on both sides, with the {@link #networkProtocolVersion(int)} from
* the server, the channel on the remote side.
* <br />
* Defaults to only accepting current version and requiring it to be present.
*
* @param test A predicate for testing
* @see VersionTest#accepts(VersionTest.Status, int)
*/
public ChannelBuilder acceptedVersions(VersionTest test) {
return clientAcceptedVersions(test).serverAcceptedVersions(test);
}
/**
* A predicate run on the client, with the {@link #networkProtocolVersion(int)} from
* the server, the channel on the remote side.
* <br />
* Defaults to only accepting current version.
*
* @param test A predicate for testing
* @see VersionTest#accepts(VersionTest.Status, int)
*/
public ChannelBuilder clientAcceptedVersions(VersionTest test) {
this.clientAcceptedVersions = test;
return this;
}
/**
* A predicate run on the server, with the {@link #networkProtocolVersion(int)} from
* the server, the channel on the remote side.
* <br />
* Defaults to only accepting current version.
*
* @param test A predicate for testing
* @see VersionTest#accepts(VersionTest.Status, int)
*/
public ChannelBuilder serverAcceptedVersions(VersionTest test) {
this.serverAcceptedVersions = test;
return this;
}
/**
* Allows a client to connect to a server that is missing this channel.
* And allows a server to accept a client missing this channel.
*
* This includes vanilla connections.
*/
public ChannelBuilder optional() {
return optionalServer().optionalClient();
}
/**
* Allows a client to connect to a server that is missing this channel.
*/
public ChannelBuilder optionalServer() {
return clientAcceptedVersions(VersionTest.ACCEPT_VANILLA.or(VersionTest.ACCEPT_MISSING.or(this.getClientAcceptedVersions())));
}
/**
* Tells the server to accept clients that are missing this channel.
*/
public ChannelBuilder optionalClient() {
return serverAcceptedVersions(VersionTest.ACCEPT_VANILLA.or(VersionTest.ACCEPT_MISSING.or(this.getServerAcceptedVersions())));
}
/**
* Registers a AttributeKey to be filled when a new connection is created.
* This is meant as a simple way to attach data on a per-connection bases.
*
* @param key The key to assign
* @param factory A factory that creates a new instance of the context data
*/
public <T> ChannelBuilder attribute(AttributeKey<T> key, Supplier<T> factory) {
return this.attribute(key, con -> factory.get());
}
/**
* Registers a AttributeKey to be filled when a new connection is created.
* This is meant as a simple way to attach data on a per-connection bases.
*
* @param key The key to assign
* @param factory A factory that creates a new instance of the context data
*/
public <T> ChannelBuilder attribute(AttributeKey<T> key, Function<Connection, T> factory) {
this.attributes.put(key, factory);
return this;
}
/**
* Registers a function that will be called when a new connection is established.
* This is meant to allow you to do basic configuration and add context objects.
* This is equivalent to the {@link net.minecraftforge.event.network.ConnectionStartEvent ConnectionStartEvent}
*/
public ChannelBuilder connectionHandler(Consumer<Connection> handler) {
this.connectionHandler = handler;
return this;
}
/**
* Create the impl instance
* @return the {@link NetworkInstance}
*/
private NetworkInstance createNetworkInstance() {
if (NetworkRegistry.lock) {
NetworkRegistry.LOGGER.error(NetworkRegistry.NETREGISTRY, "Attempted to register channel {} even though registry phase is over", name);
throw new IllegalArgumentException("Registration of impl channels is locked");
}
if (NetworkRegistry.instances.containsKey(name)) {
NetworkRegistry.LOGGER.error(NetworkRegistry.NETREGISTRY, "NetworkDirection channel {} already registered.", name);
throw new IllegalArgumentException("NetworkDirection Channel {"+ name +"} already registered");
}
var networkInstance = new NetworkInstance(name, networkProtocolVersion,
getClientAcceptedVersions(), getServerAcceptedVersions(),
attributes, connectionHandler
);
NetworkRegistry.instances.put(name, networkInstance);
return networkInstance;
}
private VersionTest getClientAcceptedVersions() {
return this.clientAcceptedVersions == null ? VersionTest.exact(this.networkProtocolVersion) : this.clientAcceptedVersions;
}
private VersionTest getServerAcceptedVersions() {
return this.serverAcceptedVersions == null ? VersionTest.exact(this.networkProtocolVersion) : this.serverAcceptedVersions;
}
/**
* Build a new {@link SimpleChannel} with this builder's configuration.
*
* @return A new {@link SimpleChannel}
*/
public SimpleChannel simpleChannel() {
return new SimpleChannel(createNetworkInstance());
}
/**
* Build a new {@link EventNetworkChannel} with this builder's configuration.
* @return A new {@link EventNetworkChannel}
*/
public EventNetworkChannel eventNetworkChannel() {
return new EventNetworkChannel(createNetworkInstance());
}
}
@@ -0,0 +1,131 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import com.mojang.logging.LogUtils;
import io.netty.buffer.Unpooled;
import net.minecraft.ResourceLocationException;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.event.ForgeEventFactory;
import net.minecraftforge.event.network.ChannelRegistrationChangeEvent;
import net.minecraftforge.event.network.CustomPayloadEvent;
import org.jetbrains.annotations.ApiStatus;
import org.slf4j.Logger;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
@ApiStatus.Internal // TODO: Decide what I want to have public, Right now it should just be add/remove channels.
public class ChannelListManager {
private static final Logger LOGGER = LogUtils.getLogger();
static final EventNetworkChannel REGISTER = ChannelBuilder
.named("minecraft:register")
.optional()
.eventNetworkChannel()
.addListener(ChannelListManager::registerListener);
static final EventNetworkChannel UNREGISTER = ChannelBuilder
.named("minecraft:unregister")
.optional()
.eventNetworkChannel()
.addListener(ChannelListManager::unregisterListener);
private static void registerListener(CustomPayloadEvent evt) {
var ctx = evt.getSource();
updateFrom(ctx, evt.getPayload(), ChannelRegistrationChangeEvent.Type.REGISTER);
ctx.setPacketHandled(true);
}
private static void unregisterListener(CustomPayloadEvent evt) {
var ctx = evt.getSource();
updateFrom(ctx, evt.getPayload(), ChannelRegistrationChangeEvent.Type.UNREGISTER);
ctx.setPacketHandled(true);
}
public static void addChannels(Connection connection) {
addChannels(connection, NetworkRegistry.buildChannelVersions().keySet().stream()
.filter(rl -> !"minecraft".equals(rl.getNamespace()))
.toList()
);
}
public static void addChannels(Connection connection, ResourceLocation... channels) {
addChannels(connection, Arrays.asList(channels));
}
public static void addChannels(Connection connection, Collection<ResourceLocation> channels) {
var list = NetworkContext.get(connection);
var toSend = new HashSet<ResourceLocation>();
for (var channel : channels) {
if (list.sentChannels.add(channel))
toSend.add(channel);
}
sendChannels(REGISTER, connection, toSend);
}
public static void removeChannels(Connection connection, ResourceLocation... channels) {
removeChannels(connection, Arrays.asList(channels));
}
public static void removeChannels(Connection connection, Collection<ResourceLocation> channels) {
var list = NetworkContext.get(connection);
var toSend = new HashSet<ResourceLocation>();
for (var channel : channels) {
if (list.sentChannels.remove(channel))
toSend.add(channel);
}
sendChannels(UNREGISTER, connection, toSend);
}
private static void sendChannels(EventNetworkChannel channel, Connection connection, Collection<ResourceLocation> channels) {
var buf = new FriendlyByteBuf(Unpooled.buffer());
for (var c : channels) {
buf.writeBytes(c.toString().getBytes(StandardCharsets.UTF_8));
buf.writeByte(0);
}
channel.send(buf, connection);
}
private static void updateFrom(CustomPayloadEvent.Context source, FriendlyByteBuf buffer, final ChannelRegistrationChangeEvent.Type changeType) {
byte[] data = new byte[Math.max(buffer.readableBytes(), 0)];
buffer.readBytes(data);
var changed = new HashSet<ResourceLocation>();
int last = 0;
for (int cur = 0; cur < data.length; cur++) {
if (data[cur] == '\0') {
var channel = new String(data, last, cur - last, StandardCharsets.UTF_8);
try {
changed.add(new ResourceLocation(channel));
} catch (ResourceLocationException ex) {
// Vanilla packet deserializers now force this to be a resource location, so we should never get this, but just in case.
LOGGER.warn("Invalid channel name received: {}. Ignoring", channel);
}
last = cur + 1;
}
}
ForgeEventFactory.onChannelRegistrationChange(source.getConnection(), changeType, changed);
var list = NetworkContext.get(source.getConnection());
for (var channel : changed) {
boolean fire = changeType == ChannelRegistrationChangeEvent.Type.UNREGISTER
? list.remoteChannels.remove(channel)
: list.remoteChannels.add(channel);
if (fire) {
var target = NetworkRegistry.findTarget(channel);
if (target != null)
target.registrationChange(changeType == ChannelRegistrationChangeEvent.Type.REGISTER);
}
}
}
}
@@ -1,45 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.config.ConfigTracker;
import net.minecraftforge.fml.config.ModConfig;
import org.apache.commons.lang3.tuple.Pair;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class ConfigSync {
public static final ConfigSync INSTANCE = new ConfigSync(ConfigTracker.INSTANCE);
private final ConfigTracker tracker;
private ConfigSync(final ConfigTracker tracker) {
this.tracker = tracker;
}
public List<Pair<String, HandshakeMessages.S2CConfigData>> syncConfigs(boolean isLocal) {
final Map<String, byte[]> configData = tracker.configSets().get(ModConfig.Type.SERVER).stream().collect(Collectors.toMap(ModConfig::getFileName, mc -> {
try {
return Files.readAllBytes(mc.getFullPath());
} catch (IOException e) {
throw new RuntimeException(e);
}
}));
return configData.entrySet().stream().map(e->Pair.of("Config "+e.getKey(), new HandshakeMessages.S2CConfigData(e.getKey(), e.getValue()))).collect(Collectors.toList());
}
public void receiveSyncedConfig(final HandshakeMessages.S2CConfigData s2CConfigData, final Supplier<NetworkEvent.Context> contextSupplier) {
if (!Minecraft.getInstance().isLocalServer()) {
Optional.ofNullable(tracker.fileMap().get(s2CConfigData.getFileName())).ifPresent(mc-> mc.acceptSyncedConfig(s2CConfigData.getBytes()));
}
}
}
@@ -1,203 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.ModList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
public class ConnectionData
{
private ImmutableMap<String, Pair<String, String>> modData;
private ImmutableMap<ResourceLocation, String> channels;
/* package private */ ConnectionData(Map<String, Pair<String, String>> modData, Map<ResourceLocation, String> channels)
{
this.modData = ImmutableMap.copyOf(modData);
this.channels = ImmutableMap.copyOf(channels);
}
/**
* Returns the list of mods present in the remote.
* <b>WARNING: This list is not authoritative.
* A mod missing from the list does not mean the mod isn't there,
* and similarly a mod present in the list does not mean it is there.
* People using hacked clients WILL hack the mod lists to make them look correct.
* Do not use this as an anti-cheat feature!
* </b>
* @return An immutable list of MODIDs
*/
public ImmutableList<String> getModList()
{
return modData.keySet().asList();
}
/**
* Returns a map of mods and respective mod names and versions present in the remote.
* <b>WARNING: This list is not authoritative.
* A mod missing from the list does not mean the mod isn't there,
* and similarly a mod present in the list does not mean it is there.
* People using hacked clients WILL hack the mod lists to make them look correct.
* Do not use this as an anti-cheat feature!
* </b>
* @return An immutable map of MODIDs and their respective mod versions
*/
public ImmutableMap<String, Pair<String, String>> getModData()
{
return modData;
}
/**
* Returns the list of impl channels present in the remote.
* <b>WARNING: This list is not authoritative.
* A channel missing from the list does not mean the remote won't accept packets with that channel ID,
* and similarly a channel present in the list does not mean the remote won't ignore it.
* People using hacked clients WILL hack the channel list to make it look correct.
* Do not use this as an anti-cheat feature!
* </b>
* @return An immutable map of channel IDs and their respective protocol versions.
*/
public ImmutableMap<ResourceLocation, String> getChannels()
{
return channels;
}
/**
* A class for holding the mod mismatch data of a failed handshake.
* Contains a list of mismatched channels, the channels present on the side the handshake failed on, the mods with mismatching registries (if available) and the information of whether the mismatching data's origin is the server.
* @param mismatchedModData The data of the mismatched or missing mods/channels, consisting of the mod or channel id and the version of the respective mod. If the mod version is absent, the entry is assumed to be missing on either side. If it is present, the entry gets treated as a mismatch.
* @param presentModData The data of the channels/mods from the side the mismatch data doesn't originate from, consisting of the mod or channel id and the name and version of the respective mod. This data is useful for a proper comparison against the mismatched channel data. The data is stored like this: [id -> [modName, modVersion]]
* @param mismatchedDataFromServer Whether the mismatched data originates from the server. Note, that the mismatched data origin does not tell us if the actual mismatch check happened on the client or the server.
*/
public record ModMismatchData(Map<ResourceLocation, String> mismatchedModData, Map<ResourceLocation, Pair<String, String>> presentModData, boolean mismatchedDataFromServer)
{
/**
* Creates a ModMismatchData instance from given channel mismatch data, which is processed side-aware depending on the value of mismatchedDataFromServer
* @param mismatchedChannels The list of channels that were listed as mismatches, either because they are missing on one side or because their versions mismatched
* @param connectionData The connection data instance responsible for collecting the server mod data.
* @param mismatchedDataFromServer Whether the mismatched data originates from the server.
*/
public static ModMismatchData channel(Map<ResourceLocation, String> mismatchedChannels, ConnectionData connectionData, boolean mismatchedDataFromServer)
{
Map<ResourceLocation, String> mismatchedChannelData = enhanceWithModVersion(mismatchedChannels, connectionData, mismatchedDataFromServer);
Map<ResourceLocation, Pair<String, String>> presentChannelData = getPresentChannelData(mismatchedChannels.keySet(), connectionData, mismatchedDataFromServer);
return new ModMismatchData(mismatchedChannelData, presentChannelData, mismatchedDataFromServer);
}
/**
* Creates a ModMismatchData instance from given mismatched registry entries. In this case, the mismatched data is always treated as originating from the client because registry entries missing on the server never cause the handshake to fail.
* @param mismatchedRegistryData The list of mismatched registries and the associated mismatched registry entries. The data is stored like this: "registryNamespace:registryPath" -> "entryNamespace:entryPath"
* @param connectionData The connection data instance responsible for collecting the server mod data.
*/
public static ModMismatchData registry(Multimap<ResourceLocation, ResourceLocation> mismatchedRegistryData, ConnectionData connectionData)
{
List<ResourceLocation> mismatchedRegistryMods = mismatchedRegistryData.values().stream().map(ResourceLocation::getNamespace).distinct().map(id -> new ResourceLocation(id, "")).toList();
Map<ResourceLocation, String> mismatchedRegistryModData = mismatchedRegistryMods.stream().map(id -> ModList.get().getModContainerById(id.getNamespace()).map(modContainer -> Pair.of(id, modContainer.getModInfo().getVersion().toString())).orElse(Pair.of(id, NetworkRegistry.ABSENT.version()))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
Map<ResourceLocation, Pair<String, String>> presentModData = getServerSidePresentModData(mismatchedRegistryModData.keySet(), connectionData);
return new ModMismatchData(mismatchedRegistryModData, presentModData, false);
}
/**
* @return true if this ModMismatchData instance contains channel or registry mismatches
*/
public boolean containsMismatches()
{
return mismatchedModData != null && !mismatchedModData.isEmpty();
}
/**
* Enhances a map of mismatched channels with the corresponding mod version.
* @param mismatchedChannels The original mismatched channel list, containing the id and version of the mismatched channel.
* @param connectionData The connection data instance responsible for collecting the server mod data.
* @param mismatchedDataFromServer Whether the mismatched data originates from the server. The given mismatched channel list gets processed side-aware depending on the value of this parameter.
* @return A map containing the id of the channel and the version of the corresponding mod, or NetworkRegistry.ABSENT if the channel is missing.
*/
private static Map<ResourceLocation, String> enhanceWithModVersion(Map<ResourceLocation, String> mismatchedChannels, ConnectionData connectionData, boolean mismatchedDataFromServer)
{
Map<String, String> mismatchedModVersions;
if (mismatchedDataFromServer) //enhance with data from the server
{
mismatchedModVersions = connectionData != null ? connectionData.getModData().entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> e.getValue().getRight())) : Map.of();
}
else //enhance with data from the client
{
mismatchedModVersions = ModList.get().getMods().stream().map(info -> Pair.of(info.getModId(), info.getVersion().toString())).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
}
return mismatchedChannels.keySet().stream().map(channel -> Pair.of(channel, mismatchedChannels.get(channel).equals(NetworkRegistry.ABSENT.version()) ? NetworkRegistry.ABSENT.version() : mismatchedModVersions.getOrDefault(channel.getNamespace(), NetworkRegistry.ABSENT.version()))).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
}
/**
* Queries the channel data from the side the mismatched data isn't from, in order to provide a map of all the present channels for a proper comparison against the mismatched channel data.
* @param mismatchedChannelsFilter A filter that gets used in order to only query the data of mismatched mods, because that's the only one we need for a proper comparison between mismatched and present mods.
* @param connectionData The connection data instance responsible for collecting the server mod data.
* @param mismatchedDataFromServer Whether the mismatched data originates from the server. The data gets queried from the side that the mismatch data does not originate from.
* @return The data of all relevant present channels, containing the channel id and the name and version of the corresponding mod.
*/
private static Map<ResourceLocation, Pair<String, String>> getPresentChannelData(Set<ResourceLocation> mismatchedChannelsFilter, ConnectionData connectionData, boolean mismatchedDataFromServer)
{
Map<ResourceLocation, String> channelData;
if (mismatchedDataFromServer) //mismatch data comes from the server, use client channel data
{
channelData = NetworkRegistry.buildChannelVersions();
}
else //mismatch data comes from the client, use server channel data
{
channelData = connectionData != null ? connectionData.getChannels() : Map.of();
}
return channelData.keySet().stream().filter(mismatchedChannelsFilter::contains).map(id -> getPresentModDataFromChannel(id, connectionData, mismatchedDataFromServer)).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
}
/**
* Queries the mod data from a given channel id from the side the mismatched data isn't from.
* @param channel The id of the channel the mod data should be queried for.
* @param connectionData The connection data instance responsible for collecting the server mod data.
* @param mismatchedDataFromServer Whether the mismatched data originates from the server. The data gets queried from the side that the mismatch data does not originate from.
* @return The mod data corresponding to the channel id, containing the channel id and the name and version of the corresponding mod.
*/
private static Pair<ResourceLocation, Pair<String, String>> getPresentModDataFromChannel(ResourceLocation channel, ConnectionData connectionData, boolean mismatchedDataFromServer)
{
if (mismatchedDataFromServer)
{
return ModList.get().getModContainerById(channel.getNamespace()).map(modContainer -> Pair.of(channel, Pair.of(modContainer.getModInfo().getDisplayName(), modContainer.getModInfo().getVersion().toString()))).orElse(Pair.of(channel, Pair.of(channel.getNamespace(), "")));
}
else
{
Map<String, Pair<String, String>> modData = connectionData != null ? connectionData.getModData() : Map.of();
Pair<String, String> modDataFromChannel = modData.getOrDefault(channel.getNamespace(), Pair.of(channel.getNamespace(), ""));
return Pair.of(channel, modDataFromChannel.getLeft().isEmpty() ? Pair.of(channel.getNamespace(), modDataFromChannel.getRight()) : modDataFromChannel);
}
}
/**
* Queries the mod data from the server side. Useful in case of a registry mismatch, which always gets detected on the client.
* @param mismatchedModsFilter A filter that gets used in order to only query the data of mismatched mods, because that's the only one we need for a proper comparison between mismatched and present mods.
* @param connectionData The connection data instance responsible for collecting the server mod data.
* @return The mod data from the server, containing the channel id and the name and version of the corresponding mod.
*/
private static Map<ResourceLocation, Pair<String, String>> getServerSidePresentModData(Set<ResourceLocation> mismatchedModsFilter, ConnectionData connectionData)
{
Map<String, Pair<String, String>> serverModData = connectionData != null ? connectionData.getModData() : Map.of();
Set<String> modIdFilter = mismatchedModsFilter.stream().map(ResourceLocation::getNamespace).collect(Collectors.toSet());
return serverModData.entrySet().stream().filter(e -> modIdFilter.contains(e.getKey())).collect(Collectors.toMap(e -> new ResourceLocation(e.getKey(), ""), Entry::getValue));
}
}
}
@@ -5,30 +5,7 @@
package net.minecraftforge.network;
import java.util.function.Function;
import org.jetbrains.annotations.ApiStatus;
@SuppressWarnings("unused")
public enum ConnectionType {
MODDED(s -> Integer.valueOf(s.substring(NetworkConstants.FMLNETMARKER.length()))),
VANILLA(s ->0);
private final Function<String, Integer> versionExtractor;
ConnectionType(Function<String, Integer> versionExtractor) {
this.versionExtractor = versionExtractor;
}
public static ConnectionType forVersionFlag(String vers) {
return vers.startsWith(NetworkConstants.FMLNETMARKER) ? MODDED : VANILLA;
}
public int getFMLVersionNumber(final String fmlVersion) {
return versionExtractor.apply(fmlVersion);
}
public boolean isVanilla() {
return this == VANILLA;
}
MODDED,
VANILLA;
}
@@ -16,18 +16,13 @@ import org.slf4j.Logger;
import javax.annotation.Nullable;
import java.net.Inet4Address;
import net.minecraftforge.common.ForgeConfig;
import javax.annotation.Nullable;
import java.net.SocketAddress;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Optional;
public class DualStackUtils
{
public class DualStackUtils {
private static final String INITIAL_PREFER_IPv4_STACK = System.getProperty("java.net.preferIPv4Stack") == null ? "false" : System.getProperty("java.net.preferIPv4Stack");
private static final String INITIAL_PREFER_IPv6_ADDRESSES = System.getProperty("java.net.preferIPv6Addresses") == null ? "false" : System.getProperty("java.net.preferIPv6Addresses");
@@ -48,12 +43,10 @@ public class DualStackUtils
* @param hostAddress The address you want to check
* @return true if IPv6, false if IPv4
*/
public static boolean checkIPv6(final String hostAddress)
{
final Optional<InetSocketAddress> hostAddr =
ServerNameResolver.DEFAULT
.resolveAddress(ServerAddress.parseString(hostAddress))
.map(ResolvedServerAddress::asInetSocketAddress);
public static boolean checkIPv6(final String hostAddress) {
var hostAddr = ServerNameResolver.DEFAULT
.resolveAddress(ServerAddress.parseString(hostAddress))
.map(ResolvedServerAddress::asInetSocketAddress);
if (hostAddr.isPresent()) return checkIPv6(hostAddr.get().getAddress());
else return false;
@@ -65,57 +58,45 @@ public class DualStackUtils
* @param inetAddress The address you want to check
* @return true if IPv6, false if IPv4
*/
public static boolean checkIPv6(final InetAddress inetAddress)
{
public static boolean checkIPv6(final InetAddress inetAddress) {
// only log debug messages if we're not in the server pinger thread, as otherwise it's unclear which IP
// corresponds to which server as soon as you have more than one server in the multiplayer server list
final String currentThreadName = Thread.currentThread().getName();
final boolean shouldLogDebug = !currentThreadName.contains("Server Pinger #");
boolean thread = !Thread.currentThread().getName().contains("Server Pinger #");
if (inetAddress instanceof Inet6Address addr)
{
if (shouldLogDebug)
LOGGER.debug("Detected IPv6 address: \"" + addr.getHostAddress() + "\"");
if (inetAddress instanceof Inet6Address addr) {
debug(thread, "Detected IPv6 address: \"" + addr.getHostAddress() + "\"");
System.setProperty("java.net.preferIPv4Stack", "false");
System.setProperty("java.net.preferIPv6Addresses", "true");
return true;
}
else if (inetAddress instanceof Inet4Address addr)
{
if (shouldLogDebug)
LOGGER.debug("Detected IPv4 address: \"" + addr.getHostAddress() + "\"");
} else if (inetAddress instanceof Inet4Address addr) {
debug(thread, "Detected IPv4 address: \"" + addr.getHostAddress() + "\"");
System.setProperty("java.net.preferIPv4Stack", "true");
System.setProperty("java.net.preferIPv6Addresses", "false");
return false;
}
else
{
if (shouldLogDebug) {
final String addr = inetAddress == null ? "null" : "\"" + inetAddress.getHostAddress() + "\"";
LOGGER.debug("Unable to determine IP version of address: " + addr);
}
if (INITIAL_PREFER_IPv4_STACK.equalsIgnoreCase("false") && INITIAL_PREFER_IPv6_ADDRESSES.equalsIgnoreCase("true"))
{
if (shouldLogDebug)
LOGGER.debug("Assuming IPv6 as Java was explicitly told to prefer it...");
} else {
debug(thread, "Unable to determine IP version of address: " + (inetAddress == null ? "null" : "\"" + inetAddress.getHostAddress() + "\""));
if (INITIAL_PREFER_IPv4_STACK.equalsIgnoreCase("false") && INITIAL_PREFER_IPv6_ADDRESSES.equalsIgnoreCase("true")) {
debug(thread, "Assuming IPv6 as Java was explicitly told to prefer it...");
System.setProperty("java.net.preferIPv4Stack", "false");
System.setProperty("java.net.preferIPv6Addresses", "true");
return true;
}
if (shouldLogDebug)
LOGGER.debug("Assuming IPv4...");
debug(thread, "Assuming IPv4...");
System.setProperty("java.net.preferIPv4Stack", "true");
System.setProperty("java.net.preferIPv6Addresses", "false");
return false;
}
}
private static void debug(boolean shouldLogDebug, String message) {
if (shouldLogDebug)
LOGGER.debug(message);
}
/**
* Get the device's local IP address, taking into account scenarios where the client's network adapter
* supports IPv6 and has it enabled but the router's LAN does not.
@@ -123,17 +104,13 @@ public class DualStackUtils
* @return the client's local IP address or {@code null} if unable to determine it
*/
@Nullable
public static InetAddress getLocalAddress()
{
public static InetAddress getLocalAddress() {
final InetAddress localAddr = new InetSocketAddress(HttpUtil.getAvailablePort()).getAddress();
if (localAddr.isAnyLocalAddress()) return localAddr;
try
{
try {
return InetAddress.getByName("localhost");
}
catch (final UnknownHostException e)
{
} catch (final UnknownHostException e) {
return null;
}
}
@@ -143,8 +120,7 @@ public class DualStackUtils
* @return The multicast group to use for LAN discovery - IPv6 if available, IPv4 otherwise.
*/
public static String getMulticastGroup() {
if (checkIPv6(getLocalAddress())) return "FF75:230::60";
else return "224.0.2.60";
return checkIPv6(getLocalAddress()) ? "FF75:230::60" : "224.0.2.60";
}
/**
@@ -162,9 +138,9 @@ public class DualStackUtils
public static String getAddressString(final SocketAddress address) {
if (address instanceof final InetSocketAddress inetAddress) {
String formatted;
if (inetAddress.isUnresolved()) {
if (inetAddress.isUnresolved())
formatted = inetAddress.getHostName() + "/<unresolved>";
} else {
else {
formatted = InetAddresses.toAddrString(inetAddress.getAddress());
if (inetAddress.getAddress() instanceof Inet6Address)
formatted = '[' + formatted + ']';
@@ -0,0 +1,48 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.event.network.CustomPayloadEvent;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* An event-bus like object on which {@link CustomPayloadEvent}s are posted.
*
* These events are fired from the network thread, and so should not interact with most game state by default.
* {@link CustomPayloadEvent.Context#enqueueWork(Runnable)} can be used to handle the message on the main server or client
* thread.
*
* @see ChannelBuilder#newEventChannel(ResourceLocation, Supplier, Predicate, Predicate)
*/
public class EventNetworkChannel extends Channel<FriendlyByteBuf> {
EventNetworkChannel(NetworkInstance instance) {
super(instance);
}
public <T extends CustomPayloadEvent> EventNetworkChannel addListener(Consumer<T> eventListener) {
instance.addListener(eventListener);
return this;
}
public EventNetworkChannel registerObject(Object object) {
instance.registerObject(object);
return this;
}
public void unregisterObject(Object object) {
instance.unregisterObject(object);
}
@Override
protected FriendlyByteBuf toBuffer(FriendlyByteBuf message) {
return message;
}
}
@@ -0,0 +1,261 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import net.minecraft.network.Connection;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.util.LogMessageAdapter;
import net.minecraftforge.event.network.CustomPayloadEvent;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.config.ConfigTracker;
import net.minecraftforge.network.NetworkContext.NetworkMismatchData;
import net.minecraftforge.network.packets.Acknowledge;
import net.minecraftforge.network.packets.ChannelVersions;
import net.minecraftforge.network.packets.LoginWrapper;
import net.minecraftforge.network.packets.ModVersions;
import net.minecraftforge.network.packets.RegistryList;
import net.minecraftforge.network.packets.RegistryData;
import net.minecraftforge.network.packets.ConfigData;
import net.minecraftforge.network.packets.MismatchData;
import net.minecraftforge.network.tasks.ChannelVersionsTask;
import net.minecraftforge.network.tasks.ModVersionsTask;
import net.minecraftforge.registries.DataPackRegistriesHooks;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
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 it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* TODO: Gathered Payloads
* <p>During client to server initiation, on the <em>server</em>, the {@link CustomPayloadEvent.GatherLoginPayloadsEvent} is fired,
* which solicits all registered channels at the {@link NetworkRegistry} for any
* {@link NetworkRegistry.LoginPayload} they wish to supply.
*/
public class ForgePacketHandler {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker MARKER = MarkerManager.getMarker("FORGE_PACKET_HANDLER");
private Set<ResourceLocation> registriesToReceive;
private Map<ResourceLocation, ForgeRegistry.Snapshot> registrySnapshots = new HashMap<>();
private int nextAckId = 0;
private Int2ObjectMap<BiConsumer<Acknowledge, CustomPayloadEvent.Context>> pendingAcknowledgments = new Int2ObjectOpenHashMap<>();
ForgePacketHandler(Connection connection) {
}
public int expectAck(BiConsumer<Acknowledge, CustomPayloadEvent.Context> consumer) {
int id = this.nextAckId++;
this.pendingAcknowledgments.put(id, consumer);
return id;
}
void handleLoginWrapper(LoginWrapper msg, CustomPayloadEvent.Context ctx) {
ForgeHooks.onCustomPayload(new CustomPayloadEvent(msg.channel(), msg.data(), ctx, -1));
}
void handleClientAck(Acknowledge msg, CustomPayloadEvent.Context ctx) {
ctx.setPacketHandled(true);
var consumer = this.pendingAcknowledgments.remove(msg.token());
if (consumer != null) {
LOGGER.debug(MARKER, "Received acknowledgement {} from client", msg.token());
consumer.accept(msg, ctx);
} else {
LOGGER.error(MARKER, "Received unknown acknowledgement {} from client", msg.token());
ctx.getConnection().disconnect(Component.literal("Illegal Acknowledge packet received, unknown token: " + Integer.toHexString(msg.token())));
}
}
void handleModVersions(ModVersions list, CustomPayloadEvent.Context ctx) {
ctx.setPacketHandled(true);
LOGGER.debug(MARKER, "Received {} connection with modlist [{}]", ctx.isClientSide() ? "server" : "client", list.mods().keySet().stream().sorted().collect(Collectors.joining(", ")));
var nctx = NetworkContext.get(ctx.getConnection());
nctx.modList.clear();
nctx.modList.putAll(list.mods());
if (ctx.isClientSide()) {
NetworkInitialization.PLAY.send(ModVersions.create(), ctx.getConnection());
/*
* Set the modded marker on the channel so we know we got packets
* TODO: NETWORKING: Move modded marker to it's own handler? Its here just because this is the first packet sent from the server to the client
* Or make the marker in Intention packet a generic 'we are modded, negotiate what type' identifier?
*/
LOGGER.debug(MARKER, "Accepted server connection");
nctx.setConnectionType(ConnectionType.MODDED);
} else
nctx.finishTask(ModVersionsTask.TYPE);
}
void handleChannelVersions(ChannelVersions list, CustomPayloadEvent.Context ctx) {
ctx.setPacketHandled(true);
LOGGER.debug(MARKER, "Received {} connection with channels [{}]", ctx.isClientSide() ? "server" : "client", list.channels().keySet().stream().map(ResourceLocation::toString).sorted().collect(Collectors.joining(", ")));
var nctx = NetworkContext.get(ctx.getConnection());
nctx.channelList.clear();
nctx.channelList.putAll(list.channels());
var invalid = NetworkRegistry.validateChannels(list.channels(), ctx.isServerSide());
if (invalid != null) {
LOGGER.error(MARKER, "Terminating connection with {}, mismatched channel list", ctx.isClientSide() ? "server" : "client");
nctx.mismatchData = new NetworkMismatchData(invalid.mismatched(), invalid.missing(), invalid.fromServer(), nctx.getModList());
if (ctx.isServerSide())
NetworkInitialization.PLAY.reply(new MismatchData(nctx.mismatchData), ctx);
ctx.getConnection().disconnect(Component.literal("Connection closed - mismatched mod channel list"));
return;
}
if (ctx.isClientSide())
NetworkInitialization.PLAY.send(new ChannelVersions(), ctx.getConnection());
else
nctx.finishTask(ChannelVersionsTask.TYPE);
}
void handleModMismatchData(MismatchData data, CustomPayloadEvent.Context ctx) {
ctx.setPacketHandled(true);
var nctx = NetworkContext.get(ctx.getConnection());
nctx.mismatchData = new NetworkMismatchData(data.mismatched(), data.missing(), true, nctx.getModList());
LOGGER.error(MARKER, "Channels [{}] rejected their client side version number",
Stream.concat(data.missing().stream(), data.mismatched().keySet().stream()).map(Object::toString).collect(Collectors.joining(", ")));
LOGGER.error(MARKER, "Terminating connection with server, mismatched mod list");
ctx.getConnection().disconnect(Component.literal("Connection closed - mismatched mod channel list"));
}
void handleRegistryList(RegistryList list, CustomPayloadEvent.Context ctx) {
ctx.setPacketHandled(true);
// Validate synced custom datapack registries, client cannot be missing any present on the server.
List<String> missing = new ArrayList<>();
var clientDataPackRegistries = DataPackRegistriesHooks.getSyncedCustomRegistries();
for (var key : list.datapacks()) {
if (!clientDataPackRegistries.contains(key)) {
LOGGER.error(MARKER, "Missing required datapack registry: {}", key.location());
missing.add(key.location().toString());
}
}
if (!missing.isEmpty()) {
ctx.getConnection().disconnect(Component.translatable("fml.menu.multiplayer.missingdatapackregistries", String.join(", ", missing)));
return;
}
NetworkInitialization.PLAY.reply(new Acknowledge(list.token()), ctx);
this.registriesToReceive = new HashSet<>(list.normal());
this.registrySnapshots.clear();
LOGGER.debug(MARKER, "Expecting {} registries: {}", this.registriesToReceive.size(), this.registriesToReceive.stream().map(Object::toString).collect(Collectors.joining(", ")));
}
void handleRegistryData(RegistryData msg, CustomPayloadEvent.Context ctx) {
ctx.setPacketHandled(true);
LOGGER.debug(MARKER,"Received registry data packet for {} token {}", msg.name(), msg.token());
if (!this.registriesToReceive.remove(msg.name())) {
LOGGER.error(MARKER, "Received unexpected registry data packet for {}", msg.name());
ctx.getConnection().disconnect(Component.literal("Illegal Registry Data packet received, unexpected regitry: " + msg.name()));
return;
}
this.registrySnapshots.put(msg.name(), msg.data());
boolean continueHandshake = true;
if (this.registriesToReceive.isEmpty())
continueHandshake = handleRegistryLoading(ctx);
if (!continueHandshake)
LOGGER.error(MARKER, "Connection closed, not continuing handshake");
else
NetworkInitialization.PLAY.reply(new Acknowledge(msg.token()), ctx);
}
private boolean handleRegistryLoading(CustomPayloadEvent.Context ctx) {
var nctx = NetworkContext.get(ctx.getConnection());
// We use a countdown latch to suspend the impl thread pending the client thread processing the registry data
var block = new CountDownLatch(1);
AtomicReference<NetworkMismatchData> errorData = new AtomicReference<>();
ctx.enqueueWork(() -> {
LOGGER.debug(MARKER, "Injecting registry snapshot from server.");
var missingData = GameData.injectSnapshot(registrySnapshots, false, false);
LOGGER.debug(MARKER, "Snapshot injected.");
if (!missingData.isEmpty()) {
LOGGER.error(MARKER, "Missing registry data for connection:\n{}", LogMessageAdapter.adapt(sb ->
missingData.forEach((k, v) -> sb.append("\t").append(k).append(": ").append(v).append('\n'))
));
// The error screen just wants mods, so lets guess based on registry entry namespaces
// TODO: Make this sane... and fully test
var missingMods = missingData.values().stream()
.map(ResourceLocation::getNamespace)
.distinct()
.toList();
var mismatched = new HashMap<ResourceLocation, NetworkMismatchData.Version>();
var missing = new HashSet<ResourceLocation>();
for (var id : missingMods) {
var key = new ResourceLocation(id, "");
var container = ModList.get().getModContainerById(id).get();
if (container != null)
mismatched.put(key, new NetworkMismatchData.Version(container.getModInfo().getVersion().toString(), ""));
else
missing.add(key);
}
errorData.set(new NetworkMismatchData(mismatched, missing, true, nctx.getModList()));
}
block.countDown();
});
LOGGER.debug(MARKER, "Waiting for registries to load.");
try {
block.await();
} catch (InterruptedException e) {
Thread.interrupted();
}
var mismatchData = errorData.get();
if (mismatchData != null) {
LOGGER.error(MARKER, "Failed to load registry, closing connection.");
//Populate the mod mismatch attribute with a new mismatch data instance to indicate that the disconnect happened due to a mod mismatch
nctx.mismatchData = mismatchData;
ctx.getConnection().disconnect(Component.literal("Failed to synchronize registry data from server, closing connection"));
return false;
}
LOGGER.debug(MARKER, "Registry load complete, continuing handshake.");
return true;
}
void handleConfigSync(ConfigData msg, CustomPayloadEvent.Context ctx) {
ctx.setPacketHandled(true);
LOGGER.debug(MARKER, "Received config sync from server for {}", msg.name());
if (!ctx.getConnection().isMemoryConnection()) {
var cfg = ConfigTracker.INSTANCE.fileMap().get(msg.name());
if (cfg != null)
cfg.acceptSyncedConfig(msg.data());
}
}
}
@@ -1,400 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import com.google.common.collect.Multimap;
import com.mojang.authlib.GameProfile;
import net.minecraft.core.Registry;
import net.minecraft.network.Connection;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.network.protocol.login.ClientboundCustomQueryPacket;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.network.ServerLoginPacketListenerImpl;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.LogMessageAdapter;
import net.minecraftforge.event.entity.player.PlayerNegotiationEvent;
import net.minecraftforge.network.ConnectionData.ModMismatchData;
import net.minecraftforge.network.simple.SimpleChannel;
import net.minecraftforge.registries.DataPackRegistriesHooks;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
import org.apache.commons.lang3.tuple.Pair;
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 com.google.common.collect.Maps;
import java.util.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* Instance responsible for handling the overall FML impl handshake.
*
* <p>An instance is created during {@link ClientIntentionPacket} handling, and attached
* to the {@link Connection#channel()} via {@link NetworkConstants#FML_HANDSHAKE_HANDLER}.
*
* <p>The {@link NetworkConstants#handshakeChannel} is a {@link SimpleChannel} with standard messages flowing in both directions.
*
* <p>The {@link #loginWrapper} transforms these messages into {@link ServerboundCustomQueryPacket}
* and {@link ClientboundCustomQueryPacket} compatible messages, by means of wrapping.
*
* <p>The handshake is ticked {@code #tickLogin(NetworkManager)} from the {@link ServerLoginPacketListenerImpl#tick()} method,
* utilizing the {@code ServerLoginPacketListenerImpl.State#NEGOTIATING} state, which is otherwise unused in vanilla code.
*
* <p>During client to server initiation, on the <em>server</em>, the {@link NetworkEvent.GatherLoginPayloadsEvent} is fired,
* which solicits all registered channels at the {@link NetworkRegistry} for any
* {@link NetworkRegistry.LoginPayload} they wish to supply.
*
* <p>The collected {@link NetworkRegistry.LoginPayload} are sent, one per tick, via
* the {@code FMLLoginWrapper#wrapPacket(ResourceLocation, net.minecraft.impl.FriendlyByteBuf)} mechanism to the incoming client connection. Each
* packet is indexed via {@link ServerboundCustomQueryPacket#getTransactionId()}, which is
* the only mechanism available for tracking request/response pairs.
*
* <p>Each packet sent from the server should be replied by the client, though not necessarily in sent order. The reply
* should contain the index of the server's packet it is replying to. The {@link LoginWrapper} class handles indexing
* replies correctly automatically.
*
* <p>Once all packets have been dispatched, we wait for all replies to be received. Once all replies are received, the
* final login phase will commence.
*/
public class HandshakeHandler
{
static final Marker FMLHSMARKER = MarkerManager.getMarker("FMLHANDSHAKE").setParents(NetworkConstants.NETWORK);
private static final Logger LOGGER = LogManager.getLogger();
private static final LoginWrapper loginWrapper = new LoginWrapper();
static {
}
/**
* Create a new handshake instance. Called when connection is first created during the {@link ClientIntentionPacket}
* handling.
*
* @param manager The impl manager for this connection
* @param direction The {@link NetworkDirection} for this connection: {@link NetworkDirection#LOGIN_TO_SERVER} or {@link NetworkDirection#LOGIN_TO_CLIENT}
*/
static void registerHandshake(Connection manager, NetworkDirection direction) {
manager.channel().attr(NetworkConstants.FML_HANDSHAKE_HANDLER).compareAndSet(null, new HandshakeHandler(manager, direction));
}
static boolean tickLogin(Connection networkManager)
{
return networkManager.channel().attr(NetworkConstants.FML_HANDSHAKE_HANDLER).get().tickServer();
}
private List<NetworkRegistry.LoginPayload> messageList;
private List<Integer> sentMessages = new ArrayList<>();
private final NetworkDirection direction;
private final Connection manager;
private int packetPosition;
private Map<ResourceLocation, ForgeRegistry.Snapshot> registrySnapshots;
private Set<ResourceLocation> registriesToReceive;
private Map<ResourceLocation, String> registryHashes;
private boolean negotiationStarted = false;
private final List<Future<Void>> pendingFutures = new ArrayList<>();
private HandshakeHandler(Connection networkManager, NetworkDirection side)
{
this.direction = side;
this.manager = networkManager;
if (networkManager.isMemoryConnection()) {
this.messageList = NetworkRegistry.gatherLoginPayloads(this.direction, true);
LOGGER.debug(FMLHSMARKER, "Starting local connection.");
} else if (NetworkHooks.getConnectionType(()->this.manager)== ConnectionType.VANILLA) {
this.messageList = Collections.emptyList();
LOGGER.debug(FMLHSMARKER, "Starting new vanilla impl connection.");
} else {
this.messageList = NetworkRegistry.gatherLoginPayloads(this.direction, false);
LOGGER.debug(FMLHSMARKER, "Starting new modded impl connection. Found {} messages to dispatch.", this.messageList.size());
}
}
@FunctionalInterface
public interface HandshakeConsumer<MSG extends IntSupplier>
{
void accept(HandshakeHandler handler, MSG msg, Supplier<NetworkEvent.Context> context);
}
/**
* Transforms a two-argument instance method reference into a {@link BiConsumer} based on the {@link #getHandshake(Supplier)} function.
*
* This should only be used for login message types.
*
* @param consumer A two argument instance method reference
* @param <MSG> message type
* @return A {@link BiConsumer} for use in message handling
*/
public static <MSG extends IntSupplier> BiConsumer<MSG, Supplier<NetworkEvent.Context>> biConsumerFor(HandshakeConsumer<MSG> consumer)
{
return (m, c) -> consumer.accept(getHandshake(c), m, c);
}
/**
* Transforms a two-argument instance method reference into a {@link BiConsumer} {@link #biConsumerFor(HandshakeConsumer)}, first calling the {@link #handleIndexedMessage(IntSupplier, Supplier)}
* method to handle index tracking. Used for client to server replies.
*
* This should only be used for login messages.
*
* @param next The method reference to call after index handling
* @param <MSG> message type
* @return A {@link BiConsumer} for use in message handling
*/
public static <MSG extends IntSupplier> BiConsumer<MSG, Supplier<NetworkEvent.Context>> indexFirst(HandshakeConsumer<MSG> next)
{
final BiConsumer<MSG, Supplier<NetworkEvent.Context>> loginIndexedMessageSupplierBiConsumer = biConsumerFor(HandshakeHandler::handleIndexedMessage);
return loginIndexedMessageSupplierBiConsumer.andThen(biConsumerFor(next));
}
/**
* Retrieve the handshake from the {@link NetworkEvent.Context}
*
* @param contextSupplier the {@link NetworkEvent.Context}
* @return The handshake handler for the connection
*/
private static HandshakeHandler getHandshake(Supplier<NetworkEvent.Context> contextSupplier) {
return contextSupplier.get().attr(NetworkConstants.FML_HANDSHAKE_HANDLER).get();
}
void handleServerModListOnClient(HandshakeMessages.S2CModList serverModList, Supplier<NetworkEvent.Context> c)
{
LOGGER.debug(FMLHSMARKER, "Logging into server with mod list [{}]", String.join(", ", serverModList.getModList()));
Map<ResourceLocation, String> mismatchedChannels = NetworkRegistry.validateClientChannels(serverModList.getChannels());
c.get().setPacketHandled(true);
//The connection data needs to be modified before a new ModMismatchData instance could be constructed
NetworkHooks.appendConnectionData(c.get().getNetworkManager(), serverModList.getModList().stream().collect(Collectors.toMap(Function.identity(), s -> Pair.of("", ""))), serverModList.getChannels());
if (!mismatchedChannels.isEmpty()) {
LOGGER.error(FMLHSMARKER, "Terminating connection with server, mismatched mod list");
//Populate the mod mismatch attribute with a new mismatch data instance to indicate that the disconnect happened due to a mod mismatch
c.get().getNetworkManager().channel().attr(NetworkConstants.FML_MOD_MISMATCH_DATA).set(ModMismatchData.channel(mismatchedChannels, NetworkHooks.getConnectionData(c.get().getNetworkManager()), true));
c.get().getNetworkManager().disconnect(Component.literal("Connection closed - mismatched mod channel list"));
return;
}
// Validate synced custom datapack registries, client cannot be missing any present on the server.
List<String> missingDataPackRegistries = new ArrayList<>();
Set<ResourceKey<? extends Registry<?>>> clientDataPackRegistries = DataPackRegistriesHooks.getSyncedCustomRegistries();
for (ResourceKey<? extends Registry<?>> key : serverModList.getCustomDataPackRegistries())
{
if (!clientDataPackRegistries.contains(key))
{
ResourceLocation location = key.location();
LOGGER.error(FMLHSMARKER, "Missing required datapack registry: {}", location);
missingDataPackRegistries.add(key.location().toString());
}
}
if (!missingDataPackRegistries.isEmpty())
{
c.get().getNetworkManager().disconnect(Component.translatable("fml.menu.multiplayer.missingdatapackregistries", String.join(", ", missingDataPackRegistries)));
return;
}
NetworkConstants.handshakeChannel.reply(new HandshakeMessages.C2SModListReply(), c.get());
LOGGER.debug(FMLHSMARKER, "Accepted server connection");
// Set the modded marker on the channel so we know we got packets
c.get().getNetworkManager().channel().attr(NetworkConstants.FML_NETVERSION).set(NetworkConstants.NETVERSION);
this.registriesToReceive = new HashSet<>(serverModList.getRegistries());
this.registrySnapshots = Maps.newHashMap();
LOGGER.debug(ForgeRegistry.REGISTRIES, "Expecting {} registries: {}", ()->this.registriesToReceive.size(), ()->this.registriesToReceive);
}
void handleModData(HandshakeMessages.S2CModData serverModData, Supplier<NetworkEvent.Context> c)
{
c.get().getNetworkManager().channel().attr(NetworkConstants.FML_CONNECTION_DATA).set(new ConnectionData(serverModData.getMods(), new HashMap<>()));
c.get().setPacketHandled(true);
}
<MSG extends IntSupplier> void handleIndexedMessage(MSG message, Supplier<NetworkEvent.Context> c)
{
LOGGER.debug(FMLHSMARKER, "Received client indexed reply {} of type {}", message.getAsInt(), message.getClass().getName());
boolean removed = this.sentMessages.removeIf(i-> i == message.getAsInt());
if (!removed) {
LOGGER.error(FMLHSMARKER, "Recieved unexpected index {} in client reply", message.getAsInt());
}
}
void handleClientModListOnServer(HandshakeMessages.C2SModListReply clientModList, Supplier<NetworkEvent.Context> c)
{
LOGGER.debug(FMLHSMARKER, "Received client connection with modlist [{}]", String.join(", ", clientModList.getModList()));
Map<ResourceLocation, String> mismatchedChannels = NetworkRegistry.validateServerChannels(clientModList.getChannels());
c.get().getNetworkManager().channel().attr(NetworkConstants.FML_CONNECTION_DATA)
.set(new ConnectionData(clientModList.getModList().stream().collect(Collectors.toMap(Function.identity(), s -> Pair.of("", ""))), clientModList.getChannels()));
c.get().setPacketHandled(true);
if (!mismatchedChannels.isEmpty()) {
LOGGER.error(FMLHSMARKER, "Terminating connection with client, mismatched mod list");
NetworkConstants.handshakeChannel.reply(new HandshakeMessages.S2CChannelMismatchData(mismatchedChannels), c.get());
c.get().getNetworkManager().disconnect(Component.literal("Connection closed - mismatched mod channel list"));
return;
}
LOGGER.debug(FMLHSMARKER, "Accepted client connection mod list");
}
void handleModMismatchData(HandshakeMessages.S2CChannelMismatchData modMismatchData, Supplier<NetworkEvent.Context> c)
{
if (!modMismatchData.getMismatchedChannelData().isEmpty())
{
LOGGER.error(FMLHSMARKER, "Channels [{}] rejected their client side version number",
modMismatchData.getMismatchedChannelData().keySet().stream().map(Object::toString).collect(Collectors.joining(",")));
LOGGER.error(FMLHSMARKER, "Terminating connection with server, mismatched mod list");
c.get().setPacketHandled(true);
//Populate the mod mismatch attribute with a new mismatch data instance to indicate that the disconnect happened due to a mod mismatch
c.get().getNetworkManager().channel().attr(NetworkConstants.FML_MOD_MISMATCH_DATA).set(ModMismatchData.channel(modMismatchData.getMismatchedChannelData(), NetworkHooks.getConnectionData(c.get().getNetworkManager()), false));
c.get().getNetworkManager().disconnect(Component.literal("Connection closed - mismatched mod channel list"));
}
}
void handleRegistryMessage(final HandshakeMessages.S2CRegistry registryPacket, final Supplier<NetworkEvent.Context> contextSupplier){
LOGGER.debug(FMLHSMARKER,"Received registry packet for {}", registryPacket.getRegistryName());
this.registriesToReceive.remove(registryPacket.getRegistryName());
this.registrySnapshots.put(registryPacket.getRegistryName(), registryPacket.getSnapshot());
boolean continueHandshake = true;
if (this.registriesToReceive.isEmpty()) {
continueHandshake = handleRegistryLoading(contextSupplier);
}
// The handshake reply isn't sent until we have processed the message
contextSupplier.get().setPacketHandled(true);
if (!continueHandshake) {
LOGGER.error(FMLHSMARKER, "Connection closed, not continuing handshake");
} else {
NetworkConstants.handshakeChannel.reply(new HandshakeMessages.C2SAcknowledge(), contextSupplier.get());
}
}
private boolean handleRegistryLoading(final Supplier<NetworkEvent.Context> contextSupplier) {
// We use a countdown latch to suspend the impl thread pending the client thread processing the registry data
AtomicBoolean successfulConnection = new AtomicBoolean(false);
AtomicReference<Multimap<ResourceLocation, ResourceLocation>> registryMismatches = new AtomicReference<>();
CountDownLatch block = new CountDownLatch(1);
contextSupplier.get().enqueueWork(() -> {
LOGGER.debug(FMLHSMARKER, "Injecting registry snapshot from server.");
final Multimap<ResourceLocation, ResourceLocation> missingData = GameData.injectSnapshot(registrySnapshots, false, false);
LOGGER.debug(FMLHSMARKER, "Snapshot injected.");
if (!missingData.isEmpty()) {
LOGGER.error(FMLHSMARKER, "Missing registry data for impl connection:\n{}", LogMessageAdapter.adapt(sb->
missingData.forEach((reg, entry)-> sb.append("\t").append(reg).append(": ").append(entry).append('\n'))));
}
successfulConnection.set(missingData.isEmpty());
registryMismatches.set(missingData);
block.countDown();
});
LOGGER.debug(FMLHSMARKER, "Waiting for registries to load.");
try {
block.await();
} catch (InterruptedException e) {
Thread.interrupted();
}
if (successfulConnection.get()) {
LOGGER.debug(FMLHSMARKER, "Registry load complete, continuing handshake.");
} else {
LOGGER.error(FMLHSMARKER, "Failed to load registry, closing connection.");
//Populate the mod mismatch attribute with a new mismatch data instance to indicate that the disconnect happened due to a mod mismatch
this.manager.channel().attr(NetworkConstants.FML_MOD_MISMATCH_DATA).set(ModMismatchData.registry(registryMismatches.get(), NetworkHooks.getConnectionData(contextSupplier.get().getNetworkManager())));
this.manager.disconnect(Component.literal("Failed to synchronize registry data from server, closing connection"));
}
return successfulConnection.get();
}
void handleClientAck(final HandshakeMessages.C2SAcknowledge msg, final Supplier<NetworkEvent.Context> contextSupplier) {
LOGGER.debug(FMLHSMARKER, "Received acknowledgement from client");
contextSupplier.get().setPacketHandled(true);
}
void handleConfigSync(final HandshakeMessages.S2CConfigData msg, final Supplier<NetworkEvent.Context> contextSupplier) {
LOGGER.debug(FMLHSMARKER, "Received config sync from server");
ConfigSync.INSTANCE.receiveSyncedConfig(msg, contextSupplier);
contextSupplier.get().setPacketHandled(true);
NetworkConstants.handshakeChannel.reply(new HandshakeMessages.C2SAcknowledge(), contextSupplier.get());
}
/**
* FML will send packets, from Server to Client, from the messages queue until the queue is drained. Each message
* will be indexed, and placed into the "pending acknowledgement" queue.
*
* As indexed packets are received at the server, they will be removed from the "pending acknowledgement" queue.
*
* Once the pending queue is drained, this method returns true - indicating that login processing can proceed to
* the next step.
*
* @return true if there is no more need to tick this login connection.
*/
public boolean tickServer()
{
if (!negotiationStarted) {
GameProfile profile = ((ServerLoginPacketListenerImpl) manager.getPacketListener()).getAuthenticatedProfile();
PlayerNegotiationEvent event = new PlayerNegotiationEvent(manager, profile, pendingFutures);
MinecraftForge.EVENT_BUS.post(event);
negotiationStarted = true;
}
if (packetPosition < messageList.size()) {
NetworkRegistry.LoginPayload message = messageList.get(packetPosition);
LOGGER.debug(FMLHSMARKER, "Sending ticking packet info '{}' to '{}' sequence {}", message.getMessageContext(), message.getChannelName(), packetPosition);
if (message.needsResponse())
sentMessages.add(packetPosition);
loginWrapper.sendServerToClientLoginPacket(message.getChannelName(), message.getData(), packetPosition, this.manager);
packetPosition++;
}
pendingFutures.removeIf(future -> {
if (!future.isDone()) {
return false;
}
try {
future.get();
} catch (ExecutionException ex) {
LOGGER.error("Error during negotiation", ex.getCause());
} catch (CancellationException | InterruptedException ex) {
// no-op
}
return true;
});
// we're done when sentMessages is empty
if (sentMessages.isEmpty() && packetPosition >= messageList.size()-1 && pendingFutures.isEmpty()) {
// clear ourselves - we're done!
this.manager.channel().attr(NetworkConstants.FML_HANDSHAKE_HANDLER).set(null);
LOGGER.debug(FMLHSMARKER, "Handshake complete!");
return true;
}
return false;
}
/**
* Helper method to determine if the S2C packet at the given packet position needs a response in form of a packet handled in {@link HandshakeHandler#handleIndexedMessage} for the handshake to progress.
* @param mgr The impl manager for this connection
* @param packetPosition The packet position of the packet that the status is queried of
* @return true if the packet at the given packet position needs a response and thus may stop the handshake from progressing
*/
public static boolean packetNeedsResponse(Connection mgr, int packetPosition)
{
HandshakeHandler handler = mgr.channel().attr(NetworkConstants.FML_HANDSHAKE_HANDLER).get();
if (handler != null)
{
return handler.sentMessages.contains(packetPosition);
}
return false;
}
}
@@ -1,351 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import net.minecraft.core.Registry;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraftforge.registries.DataPackRegistriesHooks;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.RegistryManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.IntSupplier;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.Maps;
import org.jetbrains.annotations.Nullable;
public class HandshakeMessages
{
static class LoginIndexedMessage implements IntSupplier
{
private int loginIndex;
void setLoginIndex(final int loginIndex) {
this.loginIndex = loginIndex;
}
int getLoginIndex() {
return loginIndex;
}
@Override
public int getAsInt() {
return getLoginIndex();
}
}
/**
* Server to client "list of mods". Always first handshake message after the data sent by S2CModData.
*/
public static class S2CModList extends LoginIndexedMessage
{
private List<String> mods;
private Map<ResourceLocation, String> channels;
private List<ResourceLocation> registries;
private final List<ResourceKey<? extends Registry<?>>> dataPackRegistries;
public S2CModList()
{
this.mods = ModList.get().getMods().stream().map(IModInfo::getModId).collect(Collectors.toList());
this.channels = NetworkRegistry.buildChannelVersions();
this.registries = RegistryManager.getRegistryNamesForSyncToClient();
this.dataPackRegistries = List.copyOf(DataPackRegistriesHooks.getSyncedCustomRegistries());
}
private S2CModList(List<String> mods, Map<ResourceLocation, String> channels, List<ResourceLocation> registries, List<ResourceKey<? extends Registry<?>>> dataPackRegistries)
{
this.mods = mods;
this.channels = channels;
this.registries = registries;
this.dataPackRegistries = dataPackRegistries;
}
public static S2CModList decode(FriendlyByteBuf input)
{
List<String> mods = new ArrayList<>();
int len = input.readVarInt();
for (int x = 0; x < len; x++)
mods.add(input.readUtf(0x100));
Map<ResourceLocation, String> channels = new HashMap<>();
len = input.readVarInt();
for (int x = 0; x < len; x++)
channels.put(input.readResourceLocation(), input.readUtf(0x100));
List<ResourceLocation> registries = new ArrayList<>();
len = input.readVarInt();
for (int x = 0; x < len; x++)
registries.add(input.readResourceLocation());
List<ResourceKey<? extends Registry<?>>> dataPackRegistries = input.readCollection(ArrayList::new, buf -> ResourceKey.createRegistryKey(buf.readResourceLocation()));
return new S2CModList(mods, channels, registries, dataPackRegistries);
}
public void encode(FriendlyByteBuf output)
{
output.writeVarInt(mods.size());
mods.forEach(m -> output.writeUtf(m, 0x100));
output.writeVarInt(channels.size());
channels.forEach((k, v) -> {
output.writeResourceLocation(k);
output.writeUtf(v, 0x100);
});
output.writeVarInt(registries.size());
registries.forEach(output::writeResourceLocation);
Set<ResourceKey<? extends Registry<?>>> dataPackRegistries = DataPackRegistriesHooks.getSyncedCustomRegistries();
output.writeCollection(dataPackRegistries, (buf, key) -> buf.writeResourceLocation(key.location()));
}
public List<String> getModList() {
return mods;
}
public List<ResourceLocation> getRegistries() {
return this.registries;
}
public Map<ResourceLocation, String> getChannels() {
return this.channels;
}
/**
* @return list of ids of non-vanilla syncable datapack registries on the server.
*/
public List<ResourceKey<? extends Registry<?>>> getCustomDataPackRegistries() {
return this.dataPackRegistries;
}
}
/**
* Prefixes S2CModList by sending additional data about the mods installed on the server to the client
* The mod data is stored as follows: [modId -> [modName, modVersion]]
*/
public static class S2CModData extends LoginIndexedMessage
{
private final Map<String, Pair<String, String>> mods;
public S2CModData()
{
this.mods = ModList.get().getMods().stream().collect(Collectors.toMap(IModInfo::getModId, info -> Pair.of(info.getDisplayName(), info.getVersion().toString())));
}
private S2CModData(Map<String, Pair<String, String>> mods)
{
this.mods = mods;
}
public static S2CModData decode(FriendlyByteBuf input)
{
Map<String, Pair<String, String>> mods = input.readMap(o -> o.readUtf(0x100), o -> Pair.of(o.readUtf(0x100), o.readUtf(0x100)));
return new S2CModData(mods);
}
public void encode(FriendlyByteBuf output)
{
output.writeMap(mods, (o, s) -> o.writeUtf(s, 0x100), (o, p) -> {
o.writeUtf(p.getLeft(), 0x100);
o.writeUtf(p.getRight(), 0x100);
});
}
public Map<String, Pair<String, String>> getMods()
{
return mods;
}
}
public static class C2SModListReply extends LoginIndexedMessage
{
private List<String> mods;
private Map<ResourceLocation, String> channels;
private Map<ResourceLocation, String> registries;
public C2SModListReply()
{
this.mods = ModList.get().getMods().stream().map(IModInfo::getModId).collect(Collectors.toList());
this.channels = NetworkRegistry.buildChannelVersions();
this.registries = Maps.newHashMap(); //TODO: Fill with known hashes, which requires keeping a file cache
}
private C2SModListReply(List<String> mods, Map<ResourceLocation, String> channels, Map<ResourceLocation, String> registries)
{
this.mods = mods;
this.channels = channels;
this.registries = registries;
}
public static C2SModListReply decode(FriendlyByteBuf input)
{
List<String> mods = new ArrayList<>();
int len = input.readVarInt();
for (int x = 0; x < len; x++)
mods.add(input.readUtf(0x100));
Map<ResourceLocation, String> channels = new HashMap<>();
len = input.readVarInt();
for (int x = 0; x < len; x++)
channels.put(input.readResourceLocation(), input.readUtf(0x100));
Map<ResourceLocation, String> registries = new HashMap<>();
len = input.readVarInt();
for (int x = 0; x < len; x++)
registries.put(input.readResourceLocation(), input.readUtf(0x100));
return new C2SModListReply(mods, channels, registries);
}
public void encode(FriendlyByteBuf output)
{
output.writeVarInt(mods.size());
mods.forEach(m -> output.writeUtf(m, 0x100));
output.writeVarInt(channels.size());
channels.forEach((k, v) -> {
output.writeResourceLocation(k);
output.writeUtf(v, 0x100);
});
output.writeVarInt(registries.size());
registries.forEach((k, v) -> {
output.writeResourceLocation(k);
output.writeUtf(v, 0x100);
});
}
public List<String> getModList() {
return mods;
}
public Map<ResourceLocation, String> getRegistries() {
return this.registries;
}
public Map<ResourceLocation, String> getChannels() {
return this.channels;
}
}
public static class C2SAcknowledge extends LoginIndexedMessage {
public void encode(FriendlyByteBuf buf) {
}
public static C2SAcknowledge decode(FriendlyByteBuf buf) {
return new C2SAcknowledge();
}
}
public static class S2CRegistry extends LoginIndexedMessage {
private ResourceLocation registryName;
@Nullable
private ForgeRegistry.Snapshot snapshot;
public S2CRegistry(final ResourceLocation name, @Nullable ForgeRegistry.Snapshot snapshot) {
this.registryName = name;
this.snapshot = snapshot;
}
void encode(final FriendlyByteBuf buffer) {
buffer.writeResourceLocation(registryName);
buffer.writeBoolean(hasSnapshot());
if (hasSnapshot())
buffer.writeBytes(snapshot.getPacketData());
}
public static S2CRegistry decode(final FriendlyByteBuf buffer) {
ResourceLocation name = buffer.readResourceLocation();
ForgeRegistry.Snapshot snapshot = null;
if (buffer.readBoolean())
snapshot = ForgeRegistry.Snapshot.read(buffer);
return new S2CRegistry(name, snapshot);
}
public ResourceLocation getRegistryName() {
return registryName;
}
public boolean hasSnapshot() {
return snapshot != null;
}
@Nullable
public ForgeRegistry.Snapshot getSnapshot() {
return snapshot;
}
}
public static class S2CConfigData extends LoginIndexedMessage {
private final String fileName;
private final byte[] fileData;
public S2CConfigData(final String configFileName, final byte[] configFileData) {
this.fileName = configFileName;
this.fileData = configFileData;
}
void encode(final FriendlyByteBuf buffer) {
buffer.writeUtf(this.fileName);
buffer.writeByteArray(this.fileData);
}
public static S2CConfigData decode(final FriendlyByteBuf buffer) {
return new S2CConfigData(buffer.readUtf(32767), buffer.readByteArray());
}
public String getFileName() {
return fileName;
}
public byte[] getBytes() {
return fileData;
}
}
/**
* Notifies the client of a channel mismatch on the server, so a {@link net.minecraftforge.client.gui.ModMismatchDisconnectedScreen} is used to notify the user of the disconnection.
* This packet also sends the data of a channel mismatch (currently, the ids and versions of the mismatched channels) to the client for it to display the correct information in said screen.
*/
public static class S2CChannelMismatchData extends LoginIndexedMessage
{
private final Map<ResourceLocation, String> mismatchedChannelData;
public S2CChannelMismatchData(Map<ResourceLocation, String> mismatchedChannelData)
{
this.mismatchedChannelData = mismatchedChannelData;
}
public static S2CChannelMismatchData decode(FriendlyByteBuf input)
{
Map<ResourceLocation, String> mismatchedMods = input.readMap(i -> new ResourceLocation(i.readUtf(0x100)), i -> i.readUtf(0x100));
return new S2CChannelMismatchData(mismatchedMods);
}
public void encode(FriendlyByteBuf output)
{
output.writeMap(mismatchedChannelData, (o, r) -> o.writeUtf(r.toString(), 0x100), (o, v) -> o.writeUtf(v, 0x100));
}
public Map<ResourceLocation, String> getMismatchedChannelData()
{
return mismatchedChannelData;
}
}
}
@@ -10,13 +10,11 @@ import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.network.FriendlyByteBuf;
public interface IContainerFactory<T extends AbstractContainerMenu> extends MenuType.MenuSupplier<T>
{
public interface IContainerFactory<T extends AbstractContainerMenu> extends MenuType.MenuSupplier<T> {
T create(int windowId, Inventory inv, FriendlyByteBuf data);
@Override
default T create(int p_create_1_, Inventory p_create_2_)
{
return create(p_create_1_, p_create_2_, null);
default T create(int id, Inventory inv) {
return create(id, inv, null);
}
}
@@ -1,75 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import io.netty.buffer.Unpooled;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.event.EventNetworkChannel;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.ApiStatus;
/**
* Wrapper for custom login packets. Transforms unnamed login channel messages into channels dispatched the same
* as regular custom packets.
*/
public class LoginWrapper
{
private static final Logger LOGGER = LogManager.getLogger();
@ApiStatus.Internal
public static final ResourceLocation WRAPPER = new ResourceLocation("fml:loginwrapper");
private EventNetworkChannel wrapperChannel;
LoginWrapper() {
wrapperChannel = NetworkRegistry.ChannelBuilder.named(LoginWrapper.WRAPPER).
clientAcceptedVersions(a->true).
serverAcceptedVersions(a->true).
networkProtocolVersion(()-> NetworkConstants.NETVERSION)
.eventNetworkChannel();
wrapperChannel.addListener(this::wrapperReceived);
}
private <T extends NetworkEvent> void wrapperReceived(final T packet) {
// we don't care about channel registration change events on this channel
if (packet instanceof NetworkEvent.ChannelRegistrationChangeEvent) return;
final NetworkEvent.Context wrappedContext = packet.getSource().get();
final FriendlyByteBuf payload = packet.getPayload();
ResourceLocation targetNetworkReceiver = NetworkConstants.FML_HANDSHAKE_RESOURCE;
FriendlyByteBuf data = null;
if (payload != null) {
targetNetworkReceiver = payload.readResourceLocation();
final int payloadLength = payload.readVarInt();
data = new FriendlyByteBuf(payload.readBytes(payloadLength));
}
final int loginSequence = packet.getLoginIndex();
LOGGER.debug(HandshakeHandler.FMLHSMARKER, "Recieved login wrapper packet event for channel {} with index {}", targetNetworkReceiver, loginSequence);
final NetworkEvent.Context context = new NetworkEvent.Context(wrappedContext.getNetworkManager(), wrappedContext.getDirection(), (rl, buf) -> {
LOGGER.debug(HandshakeHandler.FMLHSMARKER, "Dispatching wrapped packet reply for channel {} with index {}", rl, loginSequence);
wrappedContext.getPacketDispatcher().sendPacket(WRAPPER, this.wrapPacket(rl, buf));
});
final NetworkEvent.LoginPayloadEvent loginPayloadEvent = new NetworkEvent.LoginPayloadEvent(data, () -> context, loginSequence);
NetworkRegistry.findTarget(targetNetworkReceiver).ifPresent(ni -> {
ni.dispatchLoginPacket(loginPayloadEvent);
wrappedContext.setPacketHandled(context.getPacketHandled());
});
}
private FriendlyByteBuf wrapPacket(final ResourceLocation rl, final FriendlyByteBuf buf) {
FriendlyByteBuf pb = new FriendlyByteBuf(Unpooled.buffer(buf.capacity()));
pb.writeResourceLocation(rl);
pb.writeVarInt(buf.readableBytes());
pb.writeBytes(buf);
return pb;
}
void sendServerToClientLoginPacket(final ResourceLocation resourceLocation, final FriendlyByteBuf buffer, final int index, final Connection manager) {
FriendlyByteBuf pb = wrapPacket(resourceLocation, buffer);
manager.send(NetworkDirection.LOGIN_TO_CLIENT.buildPacket(Pair.of(pb, index), WRAPPER).getThis());
}
}
@@ -1,126 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import com.mojang.logging.LogUtils;
import io.netty.buffer.Unpooled;
import io.netty.util.Attribute;
import net.minecraft.ResourceLocationException;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
public class MCRegisterPacketHandler
{
private static final Logger LOGGER = LogUtils.getLogger();
public static final MCRegisterPacketHandler INSTANCE = new MCRegisterPacketHandler();
public static class ChannelList {
private Set<ResourceLocation> locations = new HashSet<>();
private Set<ResourceLocation> remoteLocations = Set.of();
public void updateFrom(final Supplier<NetworkEvent.Context> source, FriendlyByteBuf buffer, final NetworkEvent.RegistrationChangeType changeType) {
byte[] data = new byte[Math.max(buffer.readableBytes(), 0)];
buffer.readBytes(data);
Set<ResourceLocation> oldLocations = this.locations;
this.locations = bytesToResLocation(data);
this.remoteLocations = Set.copyOf(this.locations);
// ensure all locations receive updates, old and new.
oldLocations.addAll(this.locations);
oldLocations.stream()
.map(NetworkRegistry::findTarget)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(t->t.dispatchEvent(new NetworkEvent.ChannelRegistrationChangeEvent(source, changeType)));
}
byte[] toByteArray() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (ResourceLocation rl : locations) {
try {
bos.write(rl.toString().getBytes(StandardCharsets.UTF_8));
bos.write(0);
} catch (IOException e) {
// fake IOE
}
}
return bos.toByteArray();
}
private Set<ResourceLocation> bytesToResLocation(byte[] all) {
HashSet<ResourceLocation> rl = new HashSet<>();
int last = 0;
for (int cur = 0; cur < all.length; cur++) {
if (all[cur] == '\0') {
String s = new String(all, last, cur - last, StandardCharsets.UTF_8);
try {
rl.add(new ResourceLocation(s));
} catch (ResourceLocationException ex) {
LOGGER.warn("Invalid channel name received: {}. Ignoring", s);
}
last = cur + 1;
}
}
return rl;
}
/**
* {@return the unmodifiable set of channel locations sent by the remote side}
* This is useful for interacting with other modloaders via the network to inspect registered network channel IDs.
*/
public Set<ResourceLocation> getRemoteLocations() {
return this.remoteLocations;
}
}
public void addChannels(Set<ResourceLocation> locations, Connection manager) {
getFrom(manager).locations.addAll(locations);
}
void registerListener(NetworkEvent evt) {
final ChannelList channelList = getFrom(evt);
channelList.updateFrom(evt.getSource(), evt.getPayload(), NetworkEvent.RegistrationChangeType.REGISTER);
evt.getSource().get().setPacketHandled(true);
}
void unregisterListener(NetworkEvent evt) {
final ChannelList channelList = getFrom(evt);
channelList.updateFrom(evt.getSource(), evt.getPayload(), NetworkEvent.RegistrationChangeType.UNREGISTER);
evt.getSource().get().setPacketHandled(true);
}
private static ChannelList getFrom(Connection manager) {
return fromAttr(manager.channel().attr(NetworkConstants.FML_MC_REGISTRY));
}
private static ChannelList getFrom(NetworkEvent event) {
return fromAttr(event.getSource().get().attr(NetworkConstants.FML_MC_REGISTRY));
}
private static ChannelList fromAttr(Attribute<ChannelList> attr) {
attr.setIfAbsent(new ChannelList());
return attr.get();
}
public void sendRegistry(Connection manager, final NetworkDirection dir) {
FriendlyByteBuf pb = new FriendlyByteBuf(Unpooled.buffer());
pb.writeBytes(getFrom(manager).toByteArray());
final ICustomPacket<Packet<?>> iPacketICustomPacket = dir.buildPacket(Pair.of(pb, 0), NetworkConstants.MC_REGISTER_RESOURCE);
manager.send(iPacketICustomPacket.getThis());
}
}
@@ -1,54 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import io.netty.util.AttributeKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.IExtensionPoint;
import net.minecraftforge.fml.IExtensionPoint.DisplayTest;
import net.minecraftforge.network.ConnectionData.ModMismatchData;
import net.minecraftforge.network.HandshakeMessages.S2CModList;
import net.minecraftforge.network.event.EventNetworkChannel;
import net.minecraftforge.network.simple.SimpleChannel;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.util.List;
/**
* Constants related to networking
*/
public class NetworkConstants
{
public static final String FMLNETMARKER = "FML";
/**
* Netversion 3: {@link S2CModList} packet may include a list of non-vanilla synced datapack registry ids.
*/
public static final int FMLNETVERSION = 3;
public static final String NETVERSION = FMLNETMARKER + FMLNETVERSION;
public static final String NOVERSION = "NONE";
static final Marker NETWORK = MarkerManager.getMarker("FMLNETWORK");
static final AttributeKey<String> FML_NETVERSION = AttributeKey.valueOf("fml:netversion");
static final AttributeKey<HandshakeHandler> FML_HANDSHAKE_HANDLER = AttributeKey.valueOf("fml:handshake");
static final AttributeKey<MCRegisterPacketHandler.ChannelList> FML_MC_REGISTRY = AttributeKey.valueOf("minecraft:netregistry");
static final AttributeKey<ConnectionData> FML_CONNECTION_DATA = AttributeKey.valueOf("fml:conndata");
static final AttributeKey<ModMismatchData> FML_MOD_MISMATCH_DATA = AttributeKey.valueOf("fml:mismatchdata");
static final ResourceLocation FML_HANDSHAKE_RESOURCE = new ResourceLocation("fml:handshake");
static final ResourceLocation FML_PLAY_RESOURCE = new ResourceLocation("fml:play");
static final ResourceLocation MC_REGISTER_RESOURCE = new ResourceLocation("minecraft:register");
static final ResourceLocation MC_UNREGISTER_RESOURCE = new ResourceLocation("minecraft:unregister");
static final SimpleChannel handshakeChannel = NetworkInitialization.getHandshakeChannel();
static final SimpleChannel playChannel = NetworkInitialization.getPlayChannel();
static final List<EventNetworkChannel> mcRegChannels = NetworkInitialization.buildMCRegistrationChannels();
/**
* Return this value in your {@link DisplayTest} function to be ignored.
*/
public static final String IGNORESERVERONLY = DisplayTest.IGNORESERVERONLY;
public static String init() {
return NetworkConstants.NETVERSION;
}
}
@@ -0,0 +1,157 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.jetbrains.annotations.ApiStatus;
import io.netty.util.AttributeKey;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.minecraft.network.Connection;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.network.ConfigurationTask;
import net.minecraft.server.network.ServerConfigurationPacketListenerImpl;
import net.minecraftforge.network.packets.ModVersions;
public class NetworkContext {
private static final String MARKER = "FORGE";
public static final int NET_VERSION = 0;
private static final AttributeKey<NetworkContext> CHANNEL_KEY = AttributeKey.valueOf("forge:netcontext");
/**
* Gets the associated NetworkContext from the connection, creating a new instance if necessary.
*/
public static NetworkContext get(Connection connection) {
var attr = connection.channel().attr(CHANNEL_KEY);
var ret = attr.get();
if (ret == null) {
synchronized(connection.channel()) {
ret = attr.get();
if (ret == null) {
ret = new NetworkContext(connection);
attr.set(ret);
}
}
}
return ret;
}
private final Connection connection;
private ConnectionType type = ConnectionType.VANILLA;
private int netVersion = 0;
private NetworkContext(Connection connection) {
this.connection = connection;
}
public ConnectionType getType() {
return this.type;
}
public int getNetVersion() {
return this.netVersion;
}
public Set<ResourceLocation> getRemoteChannels() {
return this.remoteChannelsView;
}
/**
* A list of mods and their verisons reported by the other side of the connection.
* The remote side can and does lie about this, so not rely on it for any anti-cheat system.
*/
public Map<String, ModVersions.Info> getModList() {
return this.modListView;
}
/* ===================================================================================
* INTERNAL BELOW THIS
* ===================================================================================
*/
/**
* This is a hint that we are a modded client, This is sent in the first packet the client sends to the server.
* Unfortunately we do not have a modder facing value in this packet, so we have a long standing tradition of
* encoding it on the hostName field, which is a UTF string.
* Forge treats this string a null terminated list. With our value being anywhere in the list.
* Our identifier is currently FORGE, Optionally followed by a number indicating the network version.
* If the version is missing, we assume 0.
*
* TODO: Move out of the Intention packet and into a immediately sent Login custom payload? Which should arrive before we get to config stage?
*/
@ApiStatus.Internal
public static String enhanceHostName(String hostName) {
return String.join("\0", hostName, MARKER);
}
@ApiStatus.Internal
public void processIntention(String hostName) {
this.type = ConnectionType.VANILLA;
this.netVersion = 0;
int idx = hostName.indexOf('\0');
if (idx != -1) {
for (var pt : hostName.split("\0")) {
if (pt.startsWith(MARKER)) {
this.type = ConnectionType.MODDED;
if (pt.length() > MARKER.length())
this.netVersion = Integer.valueOf(pt.substring(MARKER.length()));
}
}
}
}
@ApiStatus.Internal
Set<ResourceLocation> remoteChannels = new HashSet<>();
private Set<ResourceLocation> remoteChannelsView = Collections.unmodifiableSet(this.remoteChannels);
@ApiStatus.Internal
Set<ResourceLocation> sentChannels = new HashSet<>();
@ApiStatus.Internal
Map<String, ModVersions.Info> modList = new HashMap<>();
private Map<String, ModVersions.Info> modListView = Collections.unmodifiableMap(modList);
@ApiStatus.Internal
Map<ResourceLocation, Integer> channelList = new Object2IntOpenHashMap<>();
// TODO Make this official API? This is to allow us to finish a task in the packet handlers and not the task function itself.
@ApiStatus.Internal
public void finishTask(ConfigurationTask.Type task) {
if (this.connection.getPacketListener() instanceof ServerConfigurationPacketListenerImpl cfg)
cfg.finishCurrentTask(task);
else
throw new IllegalStateException("Attempted to finish task " + task + " when packet listener was " + this.connection.getPacketListener().getClass().getName());
}
@ApiStatus.Internal
NetworkMismatchData mismatchData = null;
@ApiStatus.Internal
public NetworkMismatchData getMismatchs() {
return mismatchData;
}
@ApiStatus.Internal
void setConnectionType(ConnectionType type) {
this.type = type;
}
@ApiStatus.Internal
public record NetworkMismatchData(
Map<ResourceLocation, Version> mismatched,
Set<ResourceLocation> missing,
boolean fromServer,
Map<String, ModVersions.Info> mods
) {
public record Version(String received, String had) {}
}
}
@@ -17,35 +17,28 @@ import net.minecraft.network.protocol.login.custom.DiscardedQueryAnswerPayload;
import net.minecraft.network.protocol.login.custom.DiscardedQueryPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.LogicalSide;
import org.apache.commons.lang3.tuple.Pair;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@SuppressWarnings("rawtypes")
public enum NetworkDirection {
PLAY_TO_SERVER(NetworkEvent.ClientCustomPayloadEvent::new, LogicalSide.CLIENT, ServerboundCustomPayloadPacket.class, 1, NetworkDirection::playServerbound),
PLAY_TO_CLIENT(NetworkEvent.ServerCustomPayloadEvent::new, LogicalSide.SERVER, ClientboundCustomPayloadPacket.class, 0, NetworkDirection::playClientbound),
LOGIN_TO_SERVER(NetworkEvent.ClientCustomPayloadLoginEvent::new, LogicalSide.CLIENT, ServerboundCustomQueryAnswerPacket.class, 3, NetworkDirection::loginServerbound),
LOGIN_TO_CLIENT(NetworkEvent.ServerCustomPayloadLoginEvent::new, LogicalSide.SERVER, ClientboundCustomQueryPacket.class, 2, NetworkDirection::loginClientbound);
PLAY_TO_SERVER(LogicalSide.CLIENT, ServerboundCustomPayloadPacket.class, 1, NetworkDirection::playServerbound),
PLAY_TO_CLIENT(LogicalSide.SERVER, ClientboundCustomPayloadPacket.class, 0, NetworkDirection::playClientbound),
LOGIN_TO_SERVER(LogicalSide.CLIENT, ServerboundCustomQueryAnswerPacket.class, 3, NetworkDirection::loginServerbound),
LOGIN_TO_CLIENT(LogicalSide.SERVER, ClientboundCustomQueryPacket.class, 2, NetworkDirection::loginClientbound);
private final BiFunction<ICustomPacket<?>, Supplier<NetworkEvent.Context>, NetworkEvent> eventSupplier;
private final LogicalSide logicalSide;
private final Class<? extends Packet> packetClass;
private final int otherWay;
private final Factory factory;
private static final Reference2ReferenceArrayMap<Class<? extends Packet>, NetworkDirection> packetLookup;
private static final Reference2ReferenceArrayMap<Class<? extends Packet>, NetworkDirection> packetLookup = new Reference2ReferenceArrayMap<>();
private static final NetworkDirection[] values = values();
static {
packetLookup = Stream.of(values()).
collect(Collectors.toMap(NetworkDirection::getPacketClass, Function.identity(), (m1,m2)->m1, Reference2ReferenceArrayMap::new));
for (var value : values)
packetLookup.put(value.getPacketClass(), value);
}
private NetworkDirection(BiFunction<ICustomPacket<?>, Supplier<NetworkEvent.Context>, NetworkEvent> eventSupplier, LogicalSide logicalSide, Class<? extends Packet> clazz, int i, Factory factory) {
this.eventSupplier = eventSupplier;
private NetworkDirection(LogicalSide logicalSide, Class<? extends Packet> clazz, int i, Factory factory) {
this.logicalSide = logicalSide;
this.packetClass = clazz;
this.otherWay = i;
@@ -61,22 +54,20 @@ public enum NetworkDirection {
}
public NetworkDirection reply() {
return NetworkDirection.values()[this.otherWay];
}
public NetworkEvent getEvent(final ICustomPacket<?> buffer, final Supplier<NetworkEvent.Context> manager) {
return this.eventSupplier.apply(buffer, manager);
return values[this.otherWay];
}
public LogicalSide getOriginationSide() {
return logicalSide;
}
public LogicalSide getReceptionSide() { return reply().logicalSide; };
public LogicalSide getReceptionSide() {
return reply().logicalSide;
}
@SuppressWarnings("unchecked")
public <T extends Packet<?>> ICustomPacket<T> buildPacket(Pair<FriendlyByteBuf,Integer> packetData, ResourceLocation channelName) {
return this.factory.create(packetData.getLeft(), packetData.getRight(), channelName);
public <T extends Packet<?>> ICustomPacket<T> buildPacket(FriendlyByteBuf data, ResourceLocation channelName) {
return this.factory.create(data, 0, channelName);
}
private interface Factory<T extends Packet<?>> {
@@ -1,276 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.network.PacketListener;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.thread.BlockableEventLoop;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.common.util.LogicalSidedProvider;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Supplier;
public class NetworkEvent extends Event
{
private final FriendlyByteBuf payload;
private final Supplier<Context> source;
private final int loginIndex;
private NetworkEvent(final ICustomPacket<?> payload, final Supplier<Context> source)
{
this.payload = payload.getInternalData();
this.source = source;
this.loginIndex = payload.getIndex();
}
private NetworkEvent(final FriendlyByteBuf payload, final Supplier<Context> source, final int loginIndex)
{
this.payload = payload;
this.source = source;
this.loginIndex = loginIndex;
}
public NetworkEvent(final Supplier<Context> source) {
this.source = source;
this.payload = null;
this.loginIndex = -1;
}
public FriendlyByteBuf getPayload()
{
return payload;
}
public Supplier<Context> getSource()
{
return source;
}
public int getLoginIndex()
{
return loginIndex;
}
public static class ServerCustomPayloadEvent extends NetworkEvent
{
ServerCustomPayloadEvent(final ICustomPacket<?> payload, final Supplier<Context> source) {
super(payload, source);
}
}
public static class ClientCustomPayloadEvent extends NetworkEvent
{
ClientCustomPayloadEvent(final ICustomPacket<?> payload, final Supplier<Context> source) {
super(payload, source);
}
}
public static class ServerCustomPayloadLoginEvent extends ServerCustomPayloadEvent {
ServerCustomPayloadLoginEvent(ICustomPacket<?> payload, Supplier<Context> source)
{
super(payload, source);
}
}
public static class ClientCustomPayloadLoginEvent extends ClientCustomPayloadEvent {
ClientCustomPayloadLoginEvent(ICustomPacket<?> payload, Supplier<Context> source)
{
super(payload, source);
}
}
public static class GatherLoginPayloadsEvent extends Event {
private final List<NetworkRegistry.LoginPayload> collected;
private final boolean isLocal;
public GatherLoginPayloadsEvent(final List<NetworkRegistry.LoginPayload> loginPayloadList, boolean isLocal) {
this.collected = loginPayloadList;
this.isLocal = isLocal;
}
public void add(FriendlyByteBuf buffer, ResourceLocation channelName, String context) {
collected.add(new NetworkRegistry.LoginPayload(buffer, channelName, context));
}
public void add(FriendlyByteBuf buffer, ResourceLocation channelName, String context, boolean needsResponse)
{
collected.add(new NetworkRegistry.LoginPayload(buffer, channelName, context, needsResponse));
}
public boolean isLocal() {
return isLocal;
}
}
public static class LoginPayloadEvent extends NetworkEvent {
LoginPayloadEvent(final FriendlyByteBuf payload, final Supplier<Context> source, final int loginIndex) {
super(payload, source, loginIndex);
}
}
public enum RegistrationChangeType {
REGISTER, UNREGISTER;
}
/**
* Fired when the channel registration (see minecraft custom channel documentation) changes. Note the payload
* is not exposed. This fires to the resource location that owns the channel, when it's registration changes state.
*
* It seems plausible that this will fire multiple times for the same state, depending on what the server is doing.
* It just directly dispatches upon receipt.
*/
public static class ChannelRegistrationChangeEvent extends NetworkEvent {
private final RegistrationChangeType changeType;
ChannelRegistrationChangeEvent(final Supplier<Context> source, RegistrationChangeType changeType) {
super(source);
this.changeType = changeType;
}
public RegistrationChangeType getRegistrationChangeType() {
return this.changeType;
}
}
/**
* Context for {@link NetworkEvent}
*/
public static class Context
{
/**
* The {@link Connection} for this message.
*/
private final Connection networkManager;
/**
* The {@link NetworkDirection} this message has been received on.
*/
private final NetworkDirection networkDirection;
/**
* The packet dispatcher for this event. Sends back to the origin.
*/
private final PacketDispatcher packetDispatcher;
private boolean packetHandled;
Context(Connection netHandler, NetworkDirection networkDirection, int index)
{
this(netHandler, networkDirection, new PacketDispatcher.NetworkManagerDispatcher(netHandler, index, networkDirection.reply()::buildPacket));
}
Context(Connection networkManager, NetworkDirection networkDirection, final BiConsumer<ResourceLocation, FriendlyByteBuf> packetSink) {
this(networkManager, networkDirection, new PacketDispatcher(packetSink));
}
Context(Connection networkManager, NetworkDirection networkDirection, PacketDispatcher dispatcher) {
this.networkManager = networkManager;
this.networkDirection = networkDirection;
this.packetDispatcher = dispatcher;
}
public NetworkDirection getDirection() {
return networkDirection;
}
public PacketDispatcher getPacketDispatcher() {
return packetDispatcher;
}
public <T> Attribute<T> attr(AttributeKey<T> key) {
return networkManager.channel().attr(key);
}
public void setPacketHandled(boolean packetHandled) {
this.packetHandled = packetHandled;
}
public boolean getPacketHandled()
{
return packetHandled;
}
public CompletableFuture<Void> enqueueWork(Runnable runnable) {
BlockableEventLoop<?> executor = LogicalSidedProvider.WORKQUEUE.get(getDirection().getReceptionSide());
// Must check ourselves as Minecraft will sometimes delay tasks even when they are received on the client thread
// Same logic as ThreadTaskExecutor#runImmediately without the join
if (!executor.isSameThread()) {
return executor.submitAsync(runnable); // Use the internal method so thread check isn't done twice
} else {
runnable.run();
return CompletableFuture.completedFuture(null);
}
}
/**
* When available, gets the sender for packets that are sent from a client to the server.
*/
@Nullable
public ServerPlayer getSender()
{
PacketListener netHandler = networkManager.getPacketListener();
if (netHandler instanceof ServerGamePacketListenerImpl)
{
ServerGamePacketListenerImpl netHandlerPlayServer = (ServerGamePacketListenerImpl) netHandler;
return netHandlerPlayServer.player;
}
return null;
}
public Connection getNetworkManager() {
return networkManager;
}
}
/**
* Dispatcher for sending packets in response to a received packet. Abstracts out the difference between wrapped packets
* and unwrapped packets.
*/
public static class PacketDispatcher {
BiConsumer<ResourceLocation, FriendlyByteBuf> packetSink;
PacketDispatcher(final BiConsumer<ResourceLocation, FriendlyByteBuf> packetSink) {
this.packetSink = packetSink;
}
private PacketDispatcher() {
}
public void sendPacket(ResourceLocation resourceLocation, FriendlyByteBuf buffer) {
packetSink.accept(resourceLocation, buffer);
}
static class NetworkManagerDispatcher extends PacketDispatcher
{
private final Connection manager;
private final int packetIndex;
private final BiFunction<Pair<FriendlyByteBuf, Integer>, ResourceLocation, ICustomPacket<?>> customPacketSupplier;
NetworkManagerDispatcher(Connection manager, int packetIndex, BiFunction<Pair<FriendlyByteBuf, Integer>, ResourceLocation, ICustomPacket<?>> customPacketSupplier) {
super();
this.packetSink = this::dispatchPacket;
this.manager = manager;
this.packetIndex = packetIndex;
this.customPacketSupplier = customPacketSupplier;
}
private void dispatchPacket(final ResourceLocation resourceLocation, final FriendlyByteBuf buffer) {
final ICustomPacket<?> packet = this.customPacketSupplier.apply(Pair.of(buffer, packetIndex), resourceLocation);
this.manager.send(packet.getThis());
}
}
}
}
@@ -1,233 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraftforge.client.ConfigScreenHandler;
import net.minecraftforge.fml.util.thread.EffectiveSide;
import net.minecraftforge.network.ConnectionData.ModMismatchData;
import net.minecraftforge.network.filters.NetworkFilters;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.netty.buffer.Unpooled;
import net.minecraft.world.entity.Entity;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.MenuProvider;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.server.network.ServerLoginPacketListenerImpl;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.core.BlockPos;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerContainerEvent;
import net.minecraftforge.fml.config.ConfigTracker;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
@ApiStatus.Internal
public class NetworkHooks {
private static final Logger LOGGER = LogManager.getLogger();
public static String getFMLVersion(final String ip) {
int idx = ip.indexOf('\0');
if (idx == -1)
return NetworkConstants.NOVERSION;
for (var pt : ip.split("\0")) {
if (pt.startsWith("FML"))
return pt;
}
return NetworkConstants.NOVERSION;
}
public static ConnectionType getConnectionType(final Supplier<Connection> connection) {
return getConnectionType(connection.get().channel());
}
public static ConnectionType getConnectionType(ChannelHandlerContext context) {
return getConnectionType(context.channel());
}
private static ConnectionType getConnectionType(Channel channel) {
return ConnectionType.forVersionFlag(channel.attr(NetworkConstants.FML_NETVERSION).get());
}
@SuppressWarnings("unchecked")
public static Packet<ClientGamePacketListener> getEntitySpawningPacket(Entity entity) {
// ClientboundCustomPayloadPacket is an instance of Packet<ClientGamePacketListener>
return (Packet<ClientGamePacketListener>) NetworkConstants.playChannel.toVanillaPacket(new PlayMessages.SpawnEntity(entity), NetworkDirection.PLAY_TO_CLIENT);
}
public static boolean onCustomPayload(final ICustomPacket<?> packet, final Connection manager) {
return NetworkRegistry.findTarget(packet.getName()).
filter(ni->validateSideForProcessing(packet, ni, manager)).
map(ni->ni.dispatch(packet.getDirection(), packet, manager)).orElse(Boolean.FALSE);
}
private static boolean validateSideForProcessing(final ICustomPacket<?> packet, final NetworkInstance ni, final Connection manager) {
if (packet.getDirection().getReceptionSide() != EffectiveSide.get()) {
manager.disconnect(Component.literal("Illegal packet received, terminating connection"));
return false;
}
return true;
}
public static void validatePacketDirection(final NetworkDirection packetDirection, final Optional<NetworkDirection> expectedDirection, final Connection connection) {
if (packetDirection != expectedDirection.orElse(packetDirection)) {
connection.disconnect(Component.literal("Illegal packet received, terminating connection"));
throw new IllegalStateException("Invalid packet received, aborting connection");
}
}
public static void registerServerLoginChannel(Connection manager, ClientIntentionPacket packet) {
manager.channel().attr(NetworkConstants.FML_NETVERSION).set(NetworkHooks.getFMLVersion(packet.hostName()));
HandshakeHandler.registerHandshake(manager, NetworkDirection.LOGIN_TO_CLIENT);
}
public synchronized static void registerClientLoginChannel(Connection manager) {
manager.channel().attr(NetworkConstants.FML_NETVERSION).set(NetworkConstants.NOVERSION);
HandshakeHandler.registerHandshake(manager, NetworkDirection.LOGIN_TO_SERVER);
}
public synchronized static void sendMCRegistryPackets(Connection manager, String direction) {
NetworkFilters.injectIfNecessary(manager);
final Set<ResourceLocation> resourceLocations = NetworkRegistry.buildChannelVersions().keySet().stream().
filter(rl -> !Objects.equals(rl.getNamespace(), "minecraft")).
collect(Collectors.toSet());
MCRegisterPacketHandler.INSTANCE.addChannels(resourceLocations, manager);
MCRegisterPacketHandler.INSTANCE.sendRegistry(manager, NetworkDirection.valueOf(direction));
}
public static boolean isVanillaConnection(Connection manager) {
if (manager == null || manager.channel() == null) throw new NullPointerException("ARGH! Network Manager is null (" + manager != null ? "CHANNEL" : "MANAGER"+")" );
return getConnectionType(() -> manager) == ConnectionType.VANILLA;
}
public static void handleClientLoginSuccess(Connection manager) {
if (isVanillaConnection(manager)) {
LOGGER.info("Connected to a vanilla server. Catching up missing behaviour.");
ConfigTracker.INSTANCE.loadDefaultServerConfigs();
} else {
LOGGER.info("Connected to a modded server.");
}
}
public static boolean tickNegotiation(Connection manager) {
return HandshakeHandler.tickLogin(manager);
}
/**
* Request to open a GUI on the client, from the server
*
* Refer to {@link ConfigScreenHandler.ConfigScreenFactory} for how to provide a function to consume
* these GUI requests on the client.
*
* @param player The player to open the GUI for
* @param containerSupplier A supplier of container properties including the registry name of the container
*/
public static void openScreen(ServerPlayer player, MenuProvider containerSupplier) {
openScreen(player, containerSupplier, buf -> {});
}
/**
* Request to open a GUI on the client, from the server
*
* Refer to {@link ConfigScreenHandler.ConfigScreenFactory} for how to provide a function to consume
* these GUI requests on the client.
*
* @param player The player to open the GUI for
* @param containerSupplier A supplier of container properties including the registry name of the container
* @param pos A block pos, which will be encoded into the auxillary data for this request
*/
public static void openScreen(ServerPlayer player, MenuProvider containerSupplier, BlockPos pos) {
openScreen(player, containerSupplier, buf -> buf.writeBlockPos(pos));
}
/**
* Request to open a GUI on the client, from the server
*
* Refer to {@link ConfigScreenHandler.ConfigScreenFactory} for how to provide a function to consume
* these GUI requests on the client.
*
* The maximum size for #extraDataWriter is 32600 bytes.
*
* @param player The player to open the GUI for
* @param containerSupplier A supplier of container properties including the registry name of the container
* @param extraDataWriter Consumer to write any additional data the GUI needs
*/
public static void openScreen(ServerPlayer player, MenuProvider containerSupplier, Consumer<FriendlyByteBuf> extraDataWriter) {
if (player.level().isClientSide) return;
player.doCloseContainer();
player.nextContainerCounter();
int openContainerId = player.containerCounter;
FriendlyByteBuf extraData = new FriendlyByteBuf(Unpooled.buffer());
extraDataWriter.accept(extraData);
extraData.readerIndex(0); // reset to beginning in case modders read for whatever reason
FriendlyByteBuf output = new FriendlyByteBuf(Unpooled.buffer());
output.writeVarInt(extraData.readableBytes());
output.writeBytes(extraData);
if (output.readableBytes() > 32600 || output.readableBytes() < 1) {
throw new IllegalArgumentException("Invalid PacketBuffer for openGui, found "+ output.readableBytes()+ " bytes");
}
var c = containerSupplier.createMenu(openContainerId, player.getInventory(), player);
if (c == null)
return;
MenuType<?> type = c.getType();
PlayMessages.OpenContainer msg = new PlayMessages.OpenContainer(type, openContainerId, containerSupplier.getDisplayName(), output);
NetworkConstants.playChannel.sendTo(msg, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT);
player.containerMenu = c;
player.initMenu(player.containerMenu);
MinecraftForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, c));
}
/**
* Updates the current ConnectionData instance with new mod or channel data if the old instance did not have either of these yet,
* or creates a new ConnectionData instance with the new data if the current ConnectionData instance doesn't exist yet.
*/
static void appendConnectionData(Connection mgr, Map<String, Pair<String, String>> modData, Map<ResourceLocation, String> channels) {
ConnectionData oldData = mgr.channel().attr(NetworkConstants.FML_CONNECTION_DATA).get();
oldData = oldData != null ? new ConnectionData(oldData.getModData().isEmpty() ? modData : oldData.getModData(), oldData.getChannels().isEmpty() ? channels : oldData.getChannels()) : new ConnectionData(modData, channels);
mgr.channel().attr(NetworkConstants.FML_CONNECTION_DATA).set(oldData);
}
@Nullable
public static ConnectionData getConnectionData(Connection mgr) {
return mgr.channel().attr(NetworkConstants.FML_CONNECTION_DATA).get();
}
@Nullable
public static ModMismatchData getModMismatchData(Connection mgr) {
return mgr.channel().attr(NetworkConstants.FML_MOD_MISMATCH_DATA).get();
}
@Nullable
public static MCRegisterPacketHandler.ChannelList getChannelList(Connection mgr) {
return mgr.channel().attr(NetworkConstants.FML_MC_REGISTRY).get();
}
}
@@ -5,118 +5,113 @@
package net.minecraftforge.network;
import net.minecraftforge.network.event.EventNetworkChannel;
import net.minecraftforge.network.simple.SimpleChannel;
import net.minecraftforge.registries.RegistryManager;
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 org.jetbrains.annotations.ApiStatus;
import java.util.Arrays;
import java.util.List;
import io.netty.util.AttributeKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.packets.Acknowledge;
import net.minecraftforge.network.packets.ChannelVersions;
import net.minecraftforge.network.packets.LoginWrapper;
import net.minecraftforge.network.packets.OpenContainer;
import net.minecraftforge.network.packets.RegistryList;
import net.minecraftforge.network.packets.RegistryData;
import net.minecraftforge.network.packets.ConfigData;
import net.minecraftforge.network.packets.MismatchData;
import net.minecraftforge.network.packets.ModVersions;
import net.minecraftforge.network.packets.SpawnEntity;
class NetworkInitialization {
@ApiStatus.Internal
public class NetworkInitialization {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker MARKER = MarkerManager.getMarker("FORGE_NETWORK");
public static final ResourceLocation LOGIN_NAME = new ResourceLocation("forge", "login");
public static final ResourceLocation HANDSHAKE_NAME = new ResourceLocation("forge", "handshake");
public static final ResourceLocation PLAY_NAME = new ResourceLocation("forge", "play");
public static final AttributeKey<ForgePacketHandler> CONTEXT = AttributeKey.newInstance(HANDSHAKE_NAME.toString());
public static SimpleChannel getHandshakeChannel() {
SimpleChannel handshakeChannel = NetworkRegistry.ChannelBuilder.
named(NetworkConstants.FML_HANDSHAKE_RESOURCE).
clientAcceptedVersions(a -> true).
serverAcceptedVersions(a -> true).
networkProtocolVersion(() -> NetworkConstants.NETVERSION).
simpleChannel();
public static SimpleChannel LOGIN = ChannelBuilder
.named(LOGIN_NAME)
.optional()
.networkProtocolVersion(0)
.simpleChannel()
handshakeChannel.messageBuilder(HandshakeMessages.C2SAcknowledge.class, 99, NetworkDirection.LOGIN_TO_SERVER).
loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex).
decoder(HandshakeMessages.C2SAcknowledge::decode).
encoder(HandshakeMessages.C2SAcknowledge::encode).
consumerNetworkThread(HandshakeHandler.indexFirst(HandshakeHandler::handleClientAck)).
add();
.messageBuilder(LoginWrapper.class)
.decoder(LoginWrapper::decode)
.encoder(LoginWrapper::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleLoginWrapper)
.add();
handshakeChannel.messageBuilder(HandshakeMessages.S2CModData.class, 5, NetworkDirection.LOGIN_TO_CLIENT).
loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex).
decoder(HandshakeMessages.S2CModData::decode).
encoder(HandshakeMessages.S2CModData::encode).
markAsLoginPacket().
noResponse().
consumerNetworkThread(HandshakeHandler.biConsumerFor(HandshakeHandler::handleModData)).
add();
public static SimpleChannel PLAY = ChannelBuilder
.named(HANDSHAKE_NAME)
.optional()
.networkProtocolVersion(0)
.attribute(CONTEXT, ForgePacketHandler::new)
.simpleChannel()
handshakeChannel.messageBuilder(HandshakeMessages.S2CModList.class, 1, NetworkDirection.LOGIN_TO_CLIENT).
loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex).
decoder(HandshakeMessages.S2CModList::decode).
encoder(HandshakeMessages.S2CModList::encode).
markAsLoginPacket().
consumerNetworkThread(HandshakeHandler.biConsumerFor(HandshakeHandler::handleServerModListOnClient)).
add();
.messageBuilder(Acknowledge.class, NetworkDirection.PLAY_TO_SERVER)
.decoder(Acknowledge::decode)
.encoder(Acknowledge::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleClientAck)
.add()
handshakeChannel.messageBuilder(HandshakeMessages.C2SModListReply.class, 2, NetworkDirection.LOGIN_TO_SERVER).
loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex).
decoder(HandshakeMessages.C2SModListReply::decode).
encoder(HandshakeMessages.C2SModListReply::encode).
consumerNetworkThread(HandshakeHandler.indexFirst(HandshakeHandler::handleClientModListOnServer)).
add();
.messageBuilder(ModVersions.class)
.decoder(ModVersions::decode)
.encoder(ModVersions::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleModVersions)
.add()
handshakeChannel.messageBuilder(HandshakeMessages.S2CRegistry.class, 3, NetworkDirection.LOGIN_TO_CLIENT).
loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex).
decoder(HandshakeMessages.S2CRegistry::decode).
encoder(HandshakeMessages.S2CRegistry::encode).
buildLoginPacketList(RegistryManager::generateRegistryPackets). //TODO: Make this non-static, and store a cache on the client.
consumerNetworkThread(HandshakeHandler.biConsumerFor(HandshakeHandler::handleRegistryMessage)).
add();
.messageBuilder(ChannelVersions.class)
.decoder(ChannelVersions::decode)
.encoder(ChannelVersions::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleChannelVersions)
.add()
handshakeChannel.messageBuilder(HandshakeMessages.S2CConfigData.class, 4, NetworkDirection.LOGIN_TO_CLIENT).
loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex).
decoder(HandshakeMessages.S2CConfigData::decode).
encoder(HandshakeMessages.S2CConfigData::encode).
buildLoginPacketList(ConfigSync.INSTANCE::syncConfigs).
consumerNetworkThread(HandshakeHandler.biConsumerFor(HandshakeHandler::handleConfigSync)).
add();
.messageBuilder(RegistryList.class, NetworkDirection.PLAY_TO_CLIENT)
.decoder(RegistryList::decode)
.encoder(RegistryList::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleRegistryList)
.add()
handshakeChannel.messageBuilder(HandshakeMessages.S2CChannelMismatchData.class, 6, NetworkDirection.LOGIN_TO_CLIENT).
loginIndex(HandshakeMessages.LoginIndexedMessage::getLoginIndex, HandshakeMessages.LoginIndexedMessage::setLoginIndex).
decoder(HandshakeMessages.S2CChannelMismatchData::decode).
encoder(HandshakeMessages.S2CChannelMismatchData::encode).
consumerNetworkThread(HandshakeHandler.biConsumerFor(HandshakeHandler::handleModMismatchData)).
add();
.messageBuilder(RegistryData.class, NetworkDirection.PLAY_TO_CLIENT)
.decoder(RegistryData::decode)
.encoder(RegistryData::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleRegistryData)
.add()
return handshakeChannel;
.messageBuilder(ConfigData.class, NetworkDirection.PLAY_TO_CLIENT)
.decoder(ConfigData::decode)
.encoder(ConfigData::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleConfigSync)
.add()
.messageBuilder(MismatchData.class, NetworkDirection.PLAY_TO_CLIENT)
.decoder(MismatchData::decode)
.encoder(MismatchData::encode)
.consumerNetworkThread(CONTEXT, ForgePacketHandler::handleModMismatchData)
.add()
.messageBuilder(SpawnEntity.class)
.decoder(SpawnEntity::decode)
.encoder(SpawnEntity::encode)
.consumerNetworkThread(SpawnEntity::handle)
.add()
.messageBuilder(OpenContainer.class)
.decoder(OpenContainer::decode)
.encoder(OpenContainer::encode)
.consumerNetworkThread(OpenContainer::handle)
.add();
public static void init() {
for (var channel : new Channel[]{ LOGIN, PLAY, ChannelListManager.REGISTER, ChannelListManager.UNREGISTER})
LOGGER.debug(MARKER, "Registering Network {} v{}", channel.getName(), channel.getProtocolVersion());
}
public static SimpleChannel getPlayChannel() {
SimpleChannel playChannel = NetworkRegistry.ChannelBuilder.
named(NetworkConstants.FML_PLAY_RESOURCE).
clientAcceptedVersions(a -> true).
serverAcceptedVersions(a -> true).
networkProtocolVersion(() -> NetworkConstants.NETVERSION).
simpleChannel();
playChannel.messageBuilder(PlayMessages.SpawnEntity.class, 0).
decoder(PlayMessages.SpawnEntity::decode).
encoder(PlayMessages.SpawnEntity::encode).
consumerNetworkThread(PlayMessages.SpawnEntity::handle).
add();
playChannel.messageBuilder(PlayMessages.OpenContainer.class,1).
decoder(PlayMessages.OpenContainer::decode).
encoder(PlayMessages.OpenContainer::encode).
consumerNetworkThread(PlayMessages.OpenContainer::handle).
add();
return playChannel;
}
public static List<EventNetworkChannel> buildMCRegistrationChannels() {
final EventNetworkChannel mcRegChannel = NetworkRegistry.ChannelBuilder.
named(NetworkConstants.MC_REGISTER_RESOURCE).
clientAcceptedVersions(a -> true).
serverAcceptedVersions(a -> true).
networkProtocolVersion(() -> NetworkConstants.NETVERSION).
eventNetworkChannel();
mcRegChannel.addListener(MCRegisterPacketHandler.INSTANCE::registerListener);
final EventNetworkChannel mcUnregChannel = NetworkRegistry.ChannelBuilder.
named(NetworkConstants.MC_UNREGISTER_RESOURCE).
clientAcceptedVersions(a -> true).
serverAcceptedVersions(a -> true).
networkProtocolVersion(() -> NetworkConstants.NETVERSION).
eventNetworkChannel();
mcUnregChannel.addListener(MCRegisterPacketHandler.INSTANCE::unregisterListener);
return Arrays.asList(mcRegChannel, mcUnregChannel);
public static int getVersion() {
return PLAY.getProtocolVersion();
}
}
@@ -7,50 +7,54 @@ package net.minecraftforge.network;
import net.minecraft.network.Connection;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.event.network.CustomPayloadEvent;
import net.minecraftforge.eventbus.api.BusBuilder;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.IEventListener;
import net.minecraftforge.network.Channel.VersionTest;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.Function;
import org.jetbrains.annotations.ApiStatus;
public class NetworkInstance
{
public ResourceLocation getChannelName()
{
return channelName;
}
import io.netty.util.AttributeKey;
/**
* This is essentially the shared common class for {@link SimpleChannel} and {@link EventNetworkChannel}.
* I've now introduced {@link Channel} as that common modder facing base class. I am basically using this
* as the internal API and {@link Channel} as the public.
*/
@ApiStatus.Internal
public class NetworkInstance {
private final IEventBus networkEventBus; // TODO: Evaluate why we even use event bus for this...
private final ResourceLocation channelName;
private final String networkProtocolVersion;
private final Predicate<String> clientAcceptedVersions;
private final Predicate<String> serverAcceptedVersions;
private final IEventBus networkEventBus;
private final int networkProtocolVersion;
final VersionTest clientAcceptedVersions;
final VersionTest serverAcceptedVersions;
final Map<AttributeKey<?>, Function<Connection, ?>> attributes;
final Consumer<Connection> channelHandler;
final ServerStatusPing.ChannelData pingData;
NetworkInstance(ResourceLocation channelName, Supplier<String> networkProtocolVersion, Predicate<String> clientAcceptedVersions, Predicate<String> serverAcceptedVersions)
{
NetworkInstance(ResourceLocation channelName, int networkProtocolVersion,
VersionTest clientAcceptedVersions, VersionTest serverAcceptedVersions,
Map<AttributeKey<?>, Function<Connection, ?>> attributes, Consumer<Connection> channelHandler
) {
this.channelName = channelName;
this.networkProtocolVersion = networkProtocolVersion.get();
this.networkProtocolVersion = networkProtocolVersion;
this.clientAcceptedVersions = clientAcceptedVersions;
this.serverAcceptedVersions = serverAcceptedVersions;
this.attributes = attributes;
this.channelHandler = channelHandler;
this.networkEventBus = BusBuilder.builder().setExceptionHandler(this::handleError).useModLauncher().build();
this.pingData = new ServerStatusPing.ChannelData(channelName, networkProtocolVersion, this.clientAcceptedVersions.accepts(VersionTest.Status.MISSING, -1));
}
private void handleError(IEventBus iEventBus, Event event, IEventListener[] iEventListeners, int i, Throwable throwable)
{
private void handleError(IEventBus iEventBus, Event event, IEventListener[] iEventListeners, int i, Throwable throwable) {
}
public <T extends NetworkEvent> void addListener(Consumer<T> eventListener)
{
this.networkEventBus.addListener(eventListener);
}
public void addGatherListener(Consumer<NetworkEvent.GatherLoginPayloadsEvent> eventListener)
{
public <T extends CustomPayloadEvent> void addListener(Consumer<T> eventListener) {
this.networkEventBus.addListener(eventListener);
}
@@ -62,42 +66,20 @@ public class NetworkInstance
this.networkEventBus.unregister(object);
}
boolean dispatch(final NetworkDirection side, final ICustomPacket<?> packet, final Connection manager)
{
final NetworkEvent.Context context = new NetworkEvent.Context(manager, side, packet.getIndex());
this.networkEventBus.post(side.getEvent(packet, () -> context));
return context.getPacketHandled();
public boolean dispatch(CustomPayloadEvent event) {
this.networkEventBus.post(event);
return event.getSource().getPacketHandled();
}
String getNetworkProtocolVersion() {
ResourceLocation getChannelName() {
return channelName;
}
int getNetworkProtocolVersion() {
return networkProtocolVersion;
}
boolean tryServerVersionOnClient(final String serverVersion) {
return this.clientAcceptedVersions.test(serverVersion);
}
boolean tryClientVersionOnServer(final String clientVersion) {
return this.serverAcceptedVersions.test(clientVersion);
}
void dispatchGatherLogin(final List<NetworkRegistry.LoginPayload> loginPayloadList, boolean isLocal) {
this.networkEventBus.post(new NetworkEvent.GatherLoginPayloadsEvent(loginPayloadList, isLocal));
}
void dispatchLoginPacket(final NetworkEvent.LoginPayloadEvent loginPayloadEvent) {
this.networkEventBus.post(loginPayloadEvent);
}
void dispatchEvent(final NetworkEvent networkEvent) {
this.networkEventBus.post(networkEvent);
}
public boolean isRemotePresent(Connection manager) {
ConnectionData connectionData = NetworkHooks.getConnectionData(manager);
MCRegisterPacketHandler.ChannelList channelList = NetworkHooks.getChannelList(manager);
return (connectionData != null && connectionData.getChannels().containsKey(channelName))
// if it's not in the fml connection data, let's check if it's sent by another modloader.
|| (channelList != null && channelList.getRemoteLocations().contains(channelName));
void registrationChange(boolean registered) {
// TODO: Expose to listeners?
}
}
@@ -6,435 +6,177 @@
package net.minecraftforge.network;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.event.EventNetworkChannel;
import net.minecraftforge.network.simple.SimpleChannel;
import net.minecraftforge.event.ForgeEventFactory;
import net.minecraftforge.network.Channel.VersionTest;
import net.minecraftforge.network.NetworkContext.NetworkMismatchData;
import net.minecraftforge.registries.DataPackRegistriesHooks;
import org.apache.commons.lang3.tuple.Pair;
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 org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import io.netty.util.Attribute;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.HashSet;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* The impl registry. Tracks channels on behalf of mods.
* Tracks channels created by {@link ChannelBuilder}. This class is not intended for use by modders.
*/
public class NetworkRegistry
{
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker NETREGISTRY = MarkerManager.getMarker("NETREGISTRY");
@ApiStatus.Internal
public class NetworkRegistry {
static final Logger LOGGER = LogManager.getLogger();
static final Marker NETREGISTRY = MarkerManager.getMarker("NETREGISTRY");
private static Map<ResourceLocation, NetworkInstance> instances = Collections.synchronizedMap(new HashMap<>());
/**
* Special value for clientAcceptedVersions and serverAcceptedVersions predicates indicating the other side lacks
* this channel.
*/
public static ServerStatusPing.ChannelData ABSENT = new ServerStatusPing.ChannelData(new ResourceLocation("absent"), "ABSENT \uD83E\uDD14", false);
public static String ACCEPTVANILLA = new String("ALLOWVANILLA \uD83D\uDC93\uD83D\uDC93\uD83D\uDC93");
/**
* Makes a version predicate that accepts connections to vanilla or without the channel.
* @param protocolVersion The protocol version, which will be matched exactly.
* @return A new predicate with the new conditions.
*/
public static Predicate<String> acceptMissingOr(final String protocolVersion)
{
return acceptMissingOr(protocolVersion::equals);
}
/**
* Makes a version predicate that accepts connections to vanilla or without the channel.
* @param versionCheck The main version predicate, which should check the version number of the protocol.
* @return A new predicate with the new conditions.
*/
public static Predicate<String> acceptMissingOr(Predicate<String> versionCheck)
{
return versionCheck.or(ABSENT.version()::equals).or(ACCEPTVANILLA::equals);
}
public static List<String> getServerNonVanillaNetworkMods()
{
return listRejectedVanillaMods(NetworkInstance::tryClientVersionOnServer);
}
public static List<String> getClientNonVanillaNetworkMods()
{
return listRejectedVanillaMods(NetworkInstance::tryServerVersionOnClient);
}
static Map<ResourceLocation, NetworkInstance> instances = Collections.synchronizedMap(new HashMap<>());
public static boolean acceptsVanillaClientConnections() {
return (instances.isEmpty() || getServerNonVanillaNetworkMods().isEmpty()) && DataPackRegistriesHooks.getSyncedCustomRegistries().isEmpty();
return (instances.isEmpty() || listRejectedVanillaMods(n -> n.clientAcceptedVersions).isEmpty()) && DataPackRegistriesHooks.getSyncedCustomRegistries().isEmpty();
}
public static boolean canConnectToVanillaServer() {
return instances.isEmpty() || getClientNonVanillaNetworkMods().isEmpty();
return instances.isEmpty() || listRejectedVanillaMods(n -> n.serverAcceptedVersions).isEmpty();
}
/**
* Create a new {@link SimpleChannel}.
*
* @param name The registry name for this channel. Must be unique
* @param networkProtocolVersion The impl protocol version string that will be offered to the remote side {@link ChannelBuilder#networkProtocolVersion(Supplier)}
* @param clientAcceptedVersions Called on the client with the networkProtocolVersion string from the server {@link ChannelBuilder#clientAcceptedVersions(Predicate)}
* @param serverAcceptedVersions Called on the server with the networkProtocolVersion string from the client {@link ChannelBuilder#serverAcceptedVersions(Predicate)}
* @return A new {@link SimpleChannel}
*
* @see ChannelBuilder#newSimpleChannel(ResourceLocation, Supplier, Predicate, Predicate)
*/
public static SimpleChannel newSimpleChannel(final ResourceLocation name, Supplier<String> networkProtocolVersion, Predicate<String> clientAcceptedVersions, Predicate<String> serverAcceptedVersions) {
return new SimpleChannel(createInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions));
@Nullable
public static NetworkInstance findTarget(ResourceLocation resourceLocation) {
return instances.get(resourceLocation);
}
/**
* Create a new {@link EventNetworkChannel}.
*
* @param name The registry name for this channel. Must be unique
* @param networkProtocolVersion The impl protocol version string that will be offered to the remote side {@link ChannelBuilder#networkProtocolVersion(Supplier)}
* @param clientAcceptedVersions Called on the client with the networkProtocolVersion string from the server {@link ChannelBuilder#clientAcceptedVersions(Predicate)}
* @param serverAcceptedVersions Called on the server with the networkProtocolVersion string from the client {@link ChannelBuilder#serverAcceptedVersions(Predicate)}
* @return A new {@link EventNetworkChannel}
*
* @see ChannelBuilder#newEventChannel(ResourceLocation, Supplier, Predicate, Predicate)
*/
public static EventNetworkChannel newEventChannel(final ResourceLocation name, Supplier<String> networkProtocolVersion, Predicate<String> clientAcceptedVersions, Predicate<String> serverAcceptedVersions) {
return new EventNetworkChannel(createInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions));
}
/**
* Creates the internal {@link NetworkInstance} that tracks the channel data.
* @param name registry name
* @param networkProtocolVersion The protocol version string
* @param clientAcceptedVersions The client accepted predicate
* @param serverAcceptedVersions The server accepted predicate
* @return The {@link NetworkInstance}
* @throws IllegalArgumentException if the name already exists
*/
private static NetworkInstance createInstance(ResourceLocation name, Supplier<String> networkProtocolVersion, Predicate<String> clientAcceptedVersions, Predicate<String> serverAcceptedVersions)
{
if(lock) {
LOGGER.error(NETREGISTRY, "Attempted to register channel {} even though registry phase is over", name);
throw new IllegalArgumentException("Registration of impl channels is locked");
}
if (instances.containsKey(name)) {
LOGGER.error(NETREGISTRY, "NetworkDirection channel {} already registered.", name);
throw new IllegalArgumentException("NetworkDirection Channel {"+ name +"} already registered");
}
final NetworkInstance networkInstance = new NetworkInstance(name, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions);
instances.put(name, networkInstance);
return networkInstance;
}
/**
* Find the {@link NetworkInstance}, if possible
*
* @param resourceLocation The impl instance to lookup
* @return The {@link Optional} {@link NetworkInstance}
*/
static Optional<NetworkInstance> findTarget(ResourceLocation resourceLocation)
{
return Optional.ofNullable(instances.get(resourceLocation));
}
/**
* Construct the Map representation of the channel list, for use during login handshaking
*
* @see HandshakeMessages.S2CModList
* @see HandshakeMessages.C2SModListReply
*/
static Map<ResourceLocation, String> buildChannelVersions() {
return instances.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getNetworkProtocolVersion()));
}
/**
* Construct the Map representation of the channel list, for the client to check against during list ping
*
* @see HandshakeMessages.S2CModList
* @see HandshakeMessages.C2SModListReply
*/
static Map<ResourceLocation, ServerStatusPing.ChannelData> buildChannelVersionsForListPing() {
return instances.entrySet().stream().
filter(p -> !p.getKey().getNamespace().equals("fml")).
collect(Collectors.toMap(Map.Entry::getKey, val -> new ServerStatusPing.ChannelData(val.getKey(), val.getValue().getNetworkProtocolVersion(), val.getValue().tryClientVersionOnServer(ABSENT.version()))));
return instances.entrySet().stream()
.filter(p -> !p.getKey().getNamespace().equals("forge"))
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().pingData));
}
static List<String> listRejectedVanillaMods(BiFunction<NetworkInstance, String, Boolean> testFunction) {
final List<Pair<ResourceLocation, Boolean>> results = instances.values().stream().
map(ni -> {
final String incomingVersion = ACCEPTVANILLA;
final boolean test = testFunction.apply(ni, incomingVersion);
LOGGER.debug(NETREGISTRY, "Channel '{}' : Vanilla acceptance test: {}", ni.getChannelName(), test ? "ACCEPTED" : "REJECTED");
return Pair.of(ni.getChannelName(), test);
}).filter(p->!p.getRight()).toList();
static List<String> listRejectedVanillaMods(Function<NetworkInstance, VersionTest> testFunction) {
var results = new ArrayList<String>();
for (var net : instances.values()) {
boolean test = testFunction.apply(net).accepts(VersionTest.Status.VANILLA, -1);
LOGGER.debug(NETREGISTRY, "Channel '{}' : Vanilla acceptance test: {}", net.getChannelName(), test ? "ACCEPTED" : "REJECTED");
if (!test)
results.add(net.getChannelName().toString());
}
if (!results.isEmpty()) {
LOGGER.error(NETREGISTRY, "Channels [{}] rejected vanilla connections",
results.stream().map(Pair::getLeft).map(Object::toString).collect(Collectors.joining(",")));
return results.stream().map(Pair::getLeft).map(Object::toString).collect(Collectors.toList());
LOGGER.error(NETREGISTRY, "Channels [{}] rejected vanilla connections", String.join(", ", results));
return results;
}
LOGGER.debug(NETREGISTRY, "Accepting channel list from vanilla");
return Collections.emptyList();
}
/**
* Validate the channels from the server on the client. Tests the client predicates against the server
* supplied impl protocol version.
*
* @param channels An @{@link Map} of name->version pairs for testing
* @return a map of mismatched channel ids and versions, or an empty map if all channels accept themselves
*/
static Map<ResourceLocation, String> validateClientChannels(final Map<ResourceLocation, String> channels) {
return validateChannels(channels, "server", NetworkInstance::tryServerVersionOnClient);
}
/**
* Validate the channels from the client on the server. Tests the server predicates against the client
* supplied impl protocol version.
* @param channels An @{@link Map} of name->version pairs for testing
* @return a map of mismatched channel ids and versions, or an empty map if all channels accept themselves
*/
static Map<ResourceLocation, String> validateServerChannels(final Map<ResourceLocation, String> channels) {
return validateChannels(channels, "client", NetworkInstance::tryClientVersionOnServer);
}
@Nullable
public static NetworkMismatchData validateChannels(Map<ResourceLocation, Integer> incoming, boolean fromClient) {
var originName = fromClient ? "client" : "server";
/**
* Tests if the map matches with the supplied predicate tester
*
* @param incoming An @{@link Map} of name->version pairs for testing
* @param originName A label for use in logging (where the version pairs came from)
* @param testFunction The test function to use for testing
* @return a map of mismatched channel ids and versions, or an empty map if all channels accept themselves
*/
private static Map<ResourceLocation, String> validateChannels(final Map<ResourceLocation, String> incoming, final String originName, BiFunction<NetworkInstance, String, Boolean> testFunction) {
final Map<ResourceLocation, String> results = instances.values().stream().
map(ni -> {
final String incomingVersion = incoming.getOrDefault(ni.getChannelName(), ABSENT.version());
final boolean test = testFunction.apply(ni, incomingVersion);
LOGGER.debug(NETREGISTRY, "Channel '{}' : Version test of '{}' from {} : {}", ni.getChannelName(), incomingVersion, originName, test ? "ACCEPTED" : "REJECTED");
return Pair.of(Pair.of(ni.getChannelName(), incomingVersion), test);
}).filter(p->!p.getRight()).map(Pair::getLeft).collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
Set<ResourceLocation> missing = new HashSet<>();
Map<ResourceLocation, NetworkMismatchData.Version> results = new HashMap<>();
instances.forEach((name, net) -> {
VersionTest test = fromClient ? net.clientAcceptedVersions : net.serverAcceptedVersions;
if (!results.isEmpty()) {
var status = VersionTest.Status.MISSING;
var version = 0;
if (incoming.containsKey(net.getChannelName())) {
status = VersionTest.Status.PRESENT;
version = incoming.get(net.getChannelName());
}
boolean accepted = test.accepts(status, version);
LOGGER.debug(NETREGISTRY, "Channel '{}' : Version test of '{} {}' from {} : {}", name, status, version, originName, accepted ? "ACCEPTED" : "REJECTED");
if (!accepted) {
if (status == VersionTest.Status.MISSING)
missing.add(name);
else
results.put(name, new NetworkMismatchData.Version(Integer.toString(version), Integer.toString(net.getNetworkProtocolVersion())));
}
});
if (!results.isEmpty() || !missing.isEmpty()) {
LOGGER.error(NETREGISTRY, "Channels [{}] rejected their {} side version number",
results.keySet().stream().map(Object::toString).collect(Collectors.joining(",")),
originName);
return results;
Stream.concat(missing.stream(), results.keySet().stream()).map(Object::toString).collect(Collectors.joining(",")), originName);
return new NetworkMismatchData(results, missing, !fromClient, null);
}
LOGGER.debug(NETREGISTRY, "Accepting channel list from {}", originName);
return results;
}
/**
* Retrieve the {@link LoginPayload} list for dispatch during {@link HandshakeHandler#tickLogin(Connection)} handling.
* Dispatches {@link NetworkEvent.GatherLoginPayloadsEvent} to each {@link NetworkInstance}.
*
* @return The {@link LoginPayload} list
* @param direction the impl direction for the request - only gathers for LOGIN_TO_CLIENT
*/
static List<LoginPayload> gatherLoginPayloads(final NetworkDirection direction, boolean isLocal) {
if (direction!=NetworkDirection.LOGIN_TO_CLIENT) return Collections.emptyList();
List<LoginPayload> gatheredPayloads = new ArrayList<>();
instances.values().forEach(ni->ni.dispatchGatherLogin(gatheredPayloads, isLocal));
return gatheredPayloads;
LOGGER.debug(NETREGISTRY, "Accepting channel list from {}", originName);
return null;
}
public static boolean checkListPingCompatibilityForClient(Map<ResourceLocation, ServerStatusPing.ChannelData> incoming) {
Set<ResourceLocation> handled = new HashSet<>();
final List<Pair<ResourceLocation, Boolean>> results = instances.values().stream().
filter(p -> !p.getChannelName().getNamespace().equals("fml")).
map(ni -> {
final ServerStatusPing.ChannelData incomingVersion = incoming.getOrDefault(ni.getChannelName(), ABSENT);
final boolean test = ni.tryServerVersionOnClient(incomingVersion.version());
handled.add(ni.getChannelName());
LOGGER.debug(NETREGISTRY, "Channel '{}' : Version test of '{}' during listping : {}", ni.getChannelName(), incomingVersion, test ? "ACCEPTED" : "REJECTED");
return Pair.of(ni.getChannelName(), test);
}).filter(p->!p.getRight()).collect(Collectors.toList());
final List<ResourceLocation> missingButRequired = incoming.entrySet().stream().
filter(p -> !p.getKey().getNamespace().equals("fml")).
filter(p -> !p.getValue().required()).
filter(p -> !handled.contains(p.getKey())).
map(Map.Entry::getKey).
collect(Collectors.toList());
var rejected = new ArrayList<String>();
if (!results.isEmpty()) {
LOGGER.error(NETREGISTRY, "Channels [{}] rejected their server side version number during listping",
results.stream().map(Pair::getLeft).map(Object::toString).collect(Collectors.joining(",")));
for (var net : instances.values()) {
var status = VersionTest.Status.MISSING;
var version = 0;
if (incoming.containsKey(net.getChannelName())) {
status = VersionTest.Status.PRESENT;
version = incoming.get(net.getChannelName()).version();
}
boolean accepted = net.serverAcceptedVersions.accepts(status, version);
LOGGER.debug(NETREGISTRY, "Channel '{}' : Version test of '{} {}' during listping : {}", net.getChannelName(), status, version, accepted ? "ACCEPTED" : "REJECTED");
if (!accepted)
rejected.add(net.getChannelName().toString());
handled.add(net.getChannelName());
}
var missingButRequired = new ArrayList<String>();
incoming.forEach((name, data) -> {
if (data.required() && !handled.contains(name))
missingButRequired.add(name.toString());
});
if (!rejected.isEmpty()) {
LOGGER.error(NETREGISTRY, "Channels [{}] rejected their server side version number during listping", String.join(", ", rejected));
return false;
}
if(!missingButRequired.isEmpty()){
LOGGER.error(NETREGISTRY, "The server is likely to require channel [{}] to be present, yet we don't have it",
missingButRequired);
if (!missingButRequired.isEmpty()) {
LOGGER.error(NETREGISTRY, "The server is likely to require channel [{}] to be present, yet we don't have it", String.join(", ", missingButRequired));
return false;
}
LOGGER.debug(NETREGISTRY, "Accepting channel list during listping");
return true;
}
private static boolean lock = false;
public boolean isLocked(){
return lock;
}
static boolean lock = false;
public static void lock() {
lock=true;
lock = true;
}
/**
* Tracks individual outbound messages for dispatch to clients during login handling. Gathered by dispatching
* {@link NetworkEvent.GatherLoginPayloadsEvent} during early connection handling.
*/
public static class LoginPayload {
/**
* The data for sending
*/
private final FriendlyByteBuf data;
/**
* A channel which will receive a {@link NetworkEvent.LoginPayloadEvent} from the {@link LoginWrapper}
*/
private final ResourceLocation channelName;
/**
* Some context for logging purposes
*/
private final String messageContext;
/**
* If the connection should await a response to this packet to continue with the handshake
*/
private final boolean needsResponse;
public LoginPayload(final FriendlyByteBuf buffer, final ResourceLocation channelName, final String messageContext) {
this(buffer, channelName, messageContext, true);
}
public LoginPayload(final FriendlyByteBuf buffer, final ResourceLocation channelName, final String messageContext, final boolean needsResponse)
{
this.data = buffer;
this.channelName = channelName;
this.messageContext = messageContext;
this.needsResponse = needsResponse;
}
public FriendlyByteBuf getData() {
return data;
}
public ResourceLocation getChannelName() {
return channelName;
}
public String getMessageContext() {
return messageContext;
}
public boolean needsResponse()
{
return needsResponse;
@SuppressWarnings("unchecked")
public static void onConnectionStart(Connection connection) {
ForgeEventFactory.onConnectionStart(connection);
var channel = connection.channel();
for (var inst : instances.values()) {
if (inst.attributes != null)
inst.attributes.forEach((k, v) -> ((Attribute<Object>)channel.attr(k)).compareAndSet(null, (Object)v.apply(connection)));
if (inst.channelHandler != null)
inst.channelHandler.accept(connection);
}
}
/**
* Builder for constructing impl channels using a builder style API.
*/
public static class ChannelBuilder {
private ResourceLocation channelName;
private Supplier<String> networkProtocolVersion;
private Predicate<String> clientAcceptedVersions;
private Predicate<String> serverAcceptedVersions;
/**
* The name of the channel. Must be unique.
* @param channelName The name of the channel
* @return the channel builder
*/
public static ChannelBuilder named(ResourceLocation channelName)
{
ChannelBuilder builder = new ChannelBuilder();
builder.channelName = channelName;
return builder;
}
/**
* The impl protocol string for this channel. This will be gathered during login and sent to
* the remote partner, where it will be tested with against the relevant predicate.
*
* @see #serverAcceptedVersions(Predicate)
* @see #clientAcceptedVersions(Predicate)
* @param networkProtocolVersion A supplier of strings for impl protocol version testing
* @return the channel builder
*/
public ChannelBuilder networkProtocolVersion(Supplier<String> networkProtocolVersion)
{
this.networkProtocolVersion = networkProtocolVersion;
return this;
}
/**
* A predicate run on the client, with the {@link #networkProtocolVersion(Supplier)} string from
* the server, or the special value {@link NetworkRegistry#ABSENT} indicating the absence of
* the channel on the remote side.
* @param clientAcceptedVersions A predicate for testing
* @return the channel builder
*/
public ChannelBuilder clientAcceptedVersions(Predicate<String> clientAcceptedVersions)
{
this.clientAcceptedVersions = clientAcceptedVersions;
return this;
}
/**
* A predicate run on the server, with the {@link #networkProtocolVersion(Supplier)} string from
* the server, or the special value {@link NetworkRegistry#ABSENT} indicating the absence of
* the channel on the remote side.
* @param serverAcceptedVersions A predicate for testing
* @return the channel builder
*/
public ChannelBuilder serverAcceptedVersions(Predicate<String> serverAcceptedVersions)
{
this.serverAcceptedVersions = serverAcceptedVersions;
return this;
}
/**
* Create the impl instance
* @return the {@link NetworkInstance}
*/
private NetworkInstance createNetworkInstance() {
return createInstance(channelName, networkProtocolVersion, clientAcceptedVersions, serverAcceptedVersions);
}
/**
* Build a new {@link SimpleChannel} with this builder's configuration.
*
* @return A new {@link SimpleChannel}
*/
public SimpleChannel simpleChannel() {
return new SimpleChannel(createNetworkInstance());
}
/**
* Build a new {@link EventNetworkChannel} with this builder's configuration.
* @return A new {@link EventNetworkChannel}
*/
public EventNetworkChannel eventNetworkChannel() {
return new EventNetworkChannel(createNetworkInstance());
}
public static Map<ResourceLocation, Integer> buildChannelVersions() {
var ret = new Object2IntOpenHashMap<ResourceLocation>(instances.size());
instances.forEach((k, v) -> ret.put(k, v.getNetworkProtocolVersion()));
return ret;
}
}
@@ -15,46 +15,45 @@ import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.server.level.ServerChunkCache;
import net.minecraftforge.network.simple.SimpleChannel;
import net.minecraftforge.server.ServerLifecycleHooks;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jetbrains.annotations.Nullable;
/**
* Means to distribute packets in various ways
*
* @see SimpleChannel#send(PacketTarget, Object)
* @see Channel#send(Object, PacketTarget)
*
* @param <T>
*/
public class PacketDistributor<T> {
public record PacketDistributor<T>(BiFunction<PacketDistributor<T>, T, Consumer<Packet<?>>> functor, NetworkDirection direction) {
/**
* Send to the player specified in the Supplier
* <br/>
* {@link #with(Supplier)} Player
* {@link #with(T)} Player
*/
public static final PacketDistributor<ServerPlayer> PLAYER = new PacketDistributor<>(PacketDistributor::playerConsumer, NetworkDirection.PLAY_TO_CLIENT);
public static final PacketDistributor<ServerPlayer> PLAYER = new PacketDistributor<>(PacketDistributor::playerConsumer);
/**
* Send to everyone in the dimension specified in the Supplier
* <br/>
* {@link #with(Supplier)} DimensionType
* {@link #with(T)} DimensionType
*/
public static final PacketDistributor<ResourceKey<Level>> DIMENSION = new PacketDistributor<>(PacketDistributor::playerListDimConsumer, NetworkDirection.PLAY_TO_CLIENT);
public static final PacketDistributor<ResourceKey<Level>> DIMENSION = new PacketDistributor<>(PacketDistributor::playerListDimConsumer);
/**
* Send to everyone near the {@link TargetPoint} specified in the Supplier
* <br/>
* {@link #with(Supplier)} TargetPoint
* {@link #with(T)} TargetPoint
*/
public static final PacketDistributor<TargetPoint> NEAR = new PacketDistributor<>(PacketDistributor::playerListPointConsumer, NetworkDirection.PLAY_TO_CLIENT);
public static final PacketDistributor<TargetPoint> NEAR = new PacketDistributor<>(PacketDistributor::playerListPointConsumer);
/**
* Send to everyone
* <br/>
* {@link #noArg()}
*/
public static final PacketDistributor<Void> ALL = new PacketDistributor<>(PacketDistributor::playerListAll, NetworkDirection.PLAY_TO_CLIENT);
public static final PacketDistributor<Void> ALL = new PacketDistributor<>(PacketDistributor::playerListAll);
/**
* Send to the server (CLIENT to SERVER)
* <br/>
@@ -64,119 +63,50 @@ public class PacketDistributor<T> {
/**
* Send to all tracking the Entity in the Supplier
* <br/>
* {@link #with(Supplier)} Entity
* {@link #with(T)} Entity
*/
public static final PacketDistributor<Entity> TRACKING_ENTITY = new PacketDistributor<>(PacketDistributor::trackingEntity, NetworkDirection.PLAY_TO_CLIENT);
public static final PacketDistributor<Entity> TRACKING_ENTITY = new PacketDistributor<>(PacketDistributor::trackingEntity);
/**
* Send to all tracking the Entity and Player in the Supplier
* <br/>
* {@link #with(Supplier)} Entity
* {@link #with(T)} Entity
*/
public static final PacketDistributor<Entity> TRACKING_ENTITY_AND_SELF = new PacketDistributor<>(PacketDistributor::trackingEntityAndSelf, NetworkDirection.PLAY_TO_CLIENT);
public static final PacketDistributor<Entity> TRACKING_ENTITY_AND_SELF = new PacketDistributor<>(PacketDistributor::trackingEntityAndSelf);
/**
* Send to all tracking the Chunk in the Supplier
* <br/>
* {@link #with(Supplier)} Chunk
* {@link #with(T)} Chunk
*/
public static final PacketDistributor<LevelChunk> TRACKING_CHUNK = new PacketDistributor<>(PacketDistributor::trackingChunk, NetworkDirection.PLAY_TO_CLIENT);
public static final PacketDistributor<LevelChunk> TRACKING_CHUNK = new PacketDistributor<>(PacketDistributor::trackingChunk);
/**
* Send to the supplied list of NetworkManager instances in the Supplier
* <br/>
* {@link #with(Supplier)} List of NetworkManager
* {@link #with(T)} List of NetworkManager
*/
public static final PacketDistributor<List<Connection>> NMLIST = new PacketDistributor<>(PacketDistributor::networkManagerList, NetworkDirection.PLAY_TO_CLIENT);
public static final class TargetPoint {
private final ServerPlayer excluded;
private final double x;
private final double y;
private final double z;
private final double r2;
private final ResourceKey<Level> dim;
/**
* A target point with excluded entity
*
* @param excluded Entity to exclude
* @param x X
* @param y Y
* @param z Z
* @param r2 Radius
* @param dim DimensionType
*/
public TargetPoint(final ServerPlayer excluded, final double x, final double y, final double z, final double r2, final ResourceKey<Level> dim) {
this.excluded = excluded;
this.x = x;
this.y = y;
this.z = z;
this.r2 = r2;
this.dim = dim;
}
public static final PacketDistributor<List<Connection>> NMLIST = new PacketDistributor<>(PacketDistributor::networkManagerList);
public static record TargetPoint(@Nullable ServerPlayer excluded, double x, double y, double z, double r2, ResourceKey<Level> dim) {
/**
* A target point without excluded entity
* @param x X
* @param y Y
* @param z Z
* @param r2 Radius
* @param dim DimensionType
*/
public TargetPoint(final double x, final double y, final double z, final double r2, final ResourceKey<Level> dim) {
this.excluded = null;
this.x = x;
this.y = y;
this.z = z;
this.r2 = r2;
this.dim = dim;
public TargetPoint(double x, double y, double z, double r2, ResourceKey<Level> dim) {
this(null, x, y, z, r2, dim);
}
/**
* Helper to build a TargetPoint without excluded Entity
* @param x X
* @param y Y
* @param z Z
* @param r2 Radius
* @param dim DimensionType
* @return A TargetPoint supplier
*/
public static Supplier<TargetPoint> p(double x, double y, double z, double r2, ResourceKey<Level> dim) {
TargetPoint tp = new TargetPoint(x, y, z, r2, dim);
return ()->tp;
}
}
/**
* A Distributor curried with a specific value instance, for actual dispatch
*
* @see SimpleChannel#send(PacketTarget, Object)
*
* @see Channel#send(Object, PacketTarget)
*/
public static class PacketTarget {
private final Consumer<Packet<?>> packetConsumer;
private final PacketDistributor<?> distributor;
PacketTarget(final Consumer<Packet<?>> packetConsumer, final PacketDistributor<?> distributor) {
this.packetConsumer = packetConsumer;
this.distributor = distributor;
}
public record PacketTarget(Consumer<Packet<?>> packetConsumer, NetworkDirection direction) {
public void send(Packet<?> packet) {
packetConsumer.accept(packet);
}
public NetworkDirection getDirection() {
return distributor.direction;
}
}
private final BiFunction<PacketDistributor<T>, Supplier<T>, Consumer<Packet<?>>> functor;
private final NetworkDirection direction;
public PacketDistributor(BiFunction<PacketDistributor<T>, Supplier<T>, Consumer<Packet<?>>> functor, NetworkDirection direction) {
this.functor = functor;
this.direction = direction;
public PacketDistributor(BiFunction<PacketDistributor<T>, T, Consumer<Packet<?>>> functor) {
this(functor, NetworkDirection.PLAY_TO_CLIENT);
}
/**
@@ -184,8 +114,8 @@ public class PacketDistributor<T> {
* @param input The input to apply
* @return A curried instance
*/
public PacketTarget with(Supplier<T> input) {
return new PacketTarget(functor.apply(this, input), this);
public PacketTarget with(T input) {
return new PacketTarget(functor.apply(this, input), this.direction());
}
/**
@@ -196,54 +126,43 @@ public class PacketDistributor<T> {
* @return A curried instance
*/
public PacketTarget noArg() {
return new PacketTarget(functor.apply(this, ()->null), this);
return new PacketTarget(functor.apply(this, null), this.direction());
}
private Consumer<Packet<?>> playerConsumer(final Supplier<ServerPlayer> entityPlayerMPSupplier) {
return p -> entityPlayerMPSupplier.get().connection.getConnection().send(p);
}
private Consumer<Packet<?>> playerListDimConsumer(final Supplier<ResourceKey<Level>> dimensionTypeSupplier) {
return p->getServer().getPlayerList().broadcastAll(p, dimensionTypeSupplier.get());
private Consumer<Packet<?>> playerConsumer(ServerPlayer player) {
return p -> player.connection.getConnection().send(p);
}
private Consumer<Packet<?>> playerListAll(final Supplier<Void> voidSupplier) {
private Consumer<Packet<?>> playerListDimConsumer(ResourceKey<Level> dimension) {
return p -> getServer().getPlayerList().broadcastAll(p, dimension);
}
private Consumer<Packet<?>> playerListAll(Void ignored) {
return p -> getServer().getPlayerList().broadcastAll(p);
}
private Consumer<Packet<?>> clientToServer(final Supplier<Void> voidSupplier) {
private Consumer<Packet<?>> clientToServer(Void ignored) {
return p -> Minecraft.getInstance().getConnection().send(p);
}
private Consumer<Packet<?>> playerListPointConsumer(final Supplier<TargetPoint> targetPointSupplier) {
return p -> {
final TargetPoint tp = targetPointSupplier.get();
getServer().getPlayerList().broadcast(tp.excluded, tp.x, tp.y, tp.z, tp.r2, tp.dim, p);
};
private Consumer<Packet<?>> playerListPointConsumer(TargetPoint tp) {
return p -> getServer().getPlayerList().broadcast(tp.excluded, tp.x, tp.y, tp.z, tp.r2, tp.dim, p);
}
private Consumer<Packet<?>> trackingEntity(final Supplier<Entity> entitySupplier) {
return p-> {
final Entity entity = entitySupplier.get();
((ServerChunkCache)entity.getCommandSenderWorld().getChunkSource()).broadcast(entity, p);
};
private Consumer<Packet<?>> trackingEntity(Entity entity) {
return p -> ((ServerChunkCache)entity.getCommandSenderWorld().getChunkSource()).broadcast(entity, p);
}
private Consumer<Packet<?>> trackingEntityAndSelf(final Supplier<Entity> entitySupplier) {
return p-> {
final Entity entity = entitySupplier.get();
((ServerChunkCache)entity.getCommandSenderWorld().getChunkSource()).broadcastAndSend(entity, p);
};
private Consumer<Packet<?>> trackingEntityAndSelf(Entity entity) {
return p -> ((ServerChunkCache)entity.getCommandSenderWorld().getChunkSource()).broadcastAndSend(entity, p);
}
private Consumer<Packet<?>> trackingChunk(final Supplier<LevelChunk> chunkPosSupplier) {
return p -> {
final LevelChunk chunk = chunkPosSupplier.get();
((ServerChunkCache)chunk.getLevel().getChunkSource()).chunkMap.getPlayers(chunk.getPos(), false).forEach(e -> e.connection.send(p));
};
private Consumer<Packet<?>> trackingChunk(LevelChunk chunk) {
return p -> ((ServerChunkCache)chunk.getLevel().getChunkSource()).chunkMap.getPlayers(chunk.getPos(), false).forEach(e -> e.connection.send(p));
}
private Consumer<Packet<?>> networkManagerList(final Supplier<List<Connection>> nmListSupplier) {
return p -> nmListSupplier.get().forEach(nm->nm.send(p));
private Consumer<Packet<?>> networkManagerList(List<Connection> connections) {
return p -> connections.forEach(nm->nm.send(p));
}
private MinecraftServer getServer() {
@@ -1,326 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import io.netty.buffer.Unpooled;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.MenuAccess;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.util.LogicalSidedProvider;
import net.minecraftforge.entity.IEntityAdditionalSpawnData;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Supplier;
public class PlayMessages
{
/**
* Used to spawn a custom entity without the same restrictions as
* {@link ClientboundAddEntityPacket}
* <p>
* To customize how your entity is created clientside (instead of using the default factory provided to the
* {@link EntityType})
* see {@link EntityType.Builder#setCustomClientFactory}.
*/
public static class SpawnEntity
{
private final Entity entity;
private final int typeId;
private final int entityId;
private final UUID uuid;
private final double posX, posY, posZ;
private final byte pitch, yaw, headYaw;
private final int velX, velY, velZ;
private final FriendlyByteBuf buf;
SpawnEntity(Entity e)
{
this.entity = e;
this.typeId = BuiltInRegistries.ENTITY_TYPE.getId(e.getType()); //TODO: Codecs
this.entityId = e.getId();
this.uuid = e.getUUID();
this.posX = e.getX();
this.posY = e.getY();
this.posZ = e.getZ();
this.pitch = (byte) Mth.floor(e.getXRot() * 256.0F / 360.0F);
this.yaw = (byte) Mth.floor(e.getYRot() * 256.0F / 360.0F);
this.headYaw = (byte) (e.getYHeadRot() * 256.0F / 360.0F);
Vec3 vec3d = e.getDeltaMovement();
double d1 = Mth.clamp(vec3d.x, -3.9D, 3.9D);
double d2 = Mth.clamp(vec3d.y, -3.9D, 3.9D);
double d3 = Mth.clamp(vec3d.z, -3.9D, 3.9D);
this.velX = (int) (d1 * 8000.0D);
this.velY = (int) (d2 * 8000.0D);
this.velZ = (int) (d3 * 8000.0D);
this.buf = null;
}
private SpawnEntity(int typeId, int entityId, UUID uuid, double posX, double posY, double posZ, byte pitch, byte yaw, byte headYaw, int velX, int velY, int velZ, FriendlyByteBuf buf)
{
this.entity = null;
this.typeId = typeId;
this.entityId = entityId;
this.uuid = uuid;
this.posX = posX;
this.posY = posY;
this.posZ = posZ;
this.pitch = pitch;
this.yaw = yaw;
this.headYaw = headYaw;
this.velX = velX;
this.velY = velY;
this.velZ = velZ;
this.buf = buf;
}
public static void encode(SpawnEntity msg, FriendlyByteBuf buf)
{
buf.writeVarInt(msg.typeId);
buf.writeInt(msg.entityId);
buf.writeLong(msg.uuid.getMostSignificantBits());
buf.writeLong(msg.uuid.getLeastSignificantBits());
buf.writeDouble(msg.posX);
buf.writeDouble(msg.posY);
buf.writeDouble(msg.posZ);
buf.writeByte(msg.pitch);
buf.writeByte(msg.yaw);
buf.writeByte(msg.headYaw);
buf.writeShort(msg.velX);
buf.writeShort(msg.velY);
buf.writeShort(msg.velZ);
if (msg.entity instanceof IEntityAdditionalSpawnData entityAdditionalSpawnData)
{
final FriendlyByteBuf spawnDataBuffer = new FriendlyByteBuf(Unpooled.buffer());
entityAdditionalSpawnData.writeSpawnData(spawnDataBuffer);
buf.writeVarInt(spawnDataBuffer.readableBytes());
buf.writeBytes(spawnDataBuffer);
spawnDataBuffer.release();
} else
{
buf.writeVarInt(0);
}
}
public static SpawnEntity decode(FriendlyByteBuf buf)
{
return new SpawnEntity(buf.readVarInt(), buf.readInt(), new UUID(buf.readLong(), buf.readLong()), buf.readDouble(), buf.readDouble(), buf.readDouble(), buf.readByte(), buf.readByte(), buf.readByte(), buf.readShort(), buf.readShort(), buf.readShort(), readSpawnDataPacket(buf));
}
private static FriendlyByteBuf readSpawnDataPacket(FriendlyByteBuf buf)
{
final int count = buf.readVarInt();
if (count > 0)
{
final FriendlyByteBuf spawnDataBuffer = new FriendlyByteBuf(Unpooled.buffer());
spawnDataBuffer.writeBytes(buf, count);
return spawnDataBuffer;
}
return new FriendlyByteBuf(Unpooled.buffer());
}
public static void handle(SpawnEntity msg, Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() -> {
try
{
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.byId(msg.typeId);
Optional<Level> world = LogicalSidedProvider.CLIENTWORLD.get(ctx.get().getDirection().getReceptionSide());
Entity e = world.map(w -> type.customClientSpawn(msg, w)).orElse(null);
if (e == null)
{
return;
}
/*
* Sets the postiion on the client, Mirrors what
* Entity#recreateFromPacket and LivingEntity#recreateFromPacket does.
*/
e.syncPacketPositionCodec(msg.posX, msg.posY, msg.posZ);
e.absMoveTo(msg.posX, msg.posY, msg.posZ, (msg.yaw * 360) / 256.0F, (msg.pitch * 360) / 256.0F);
e.setYHeadRot((msg.headYaw * 360) / 256.0F);
e.setYBodyRot((msg.headYaw * 360) / 256.0F);
e.setId(msg.entityId);
e.setUUID(msg.uuid);
world.filter(ClientLevel.class::isInstance).ifPresent(w -> ((ClientLevel) w).putNonPlayerEntity(msg.entityId, e));
e.lerpMotion(msg.velX / 8000.0, msg.velY / 8000.0, msg.velZ / 8000.0);
if (e instanceof IEntityAdditionalSpawnData entityAdditionalSpawnData)
{
entityAdditionalSpawnData.readSpawnData(msg.buf);
}
} finally
{
msg.buf.release();
}
});
ctx.get().setPacketHandled(true);
}
public Entity getEntity()
{
return entity;
}
public int getTypeId()
{
return typeId;
}
public int getEntityId()
{
return entityId;
}
public UUID getUuid()
{
return uuid;
}
public double getPosX()
{
return posX;
}
public double getPosY()
{
return posY;
}
public double getPosZ()
{
return posZ;
}
public byte getPitch()
{
return pitch;
}
public byte getYaw()
{
return yaw;
}
public byte getHeadYaw()
{
return headYaw;
}
public int getVelX()
{
return velX;
}
public int getVelY()
{
return velY;
}
public int getVelZ()
{
return velZ;
}
public FriendlyByteBuf getAdditionalData()
{
return buf;
}
}
public static class OpenContainer
{
private final int id;
private final int windowId;
private final Component name;
private final FriendlyByteBuf additionalData;
OpenContainer(MenuType<?> id, int windowId, Component name, FriendlyByteBuf additionalData)
{
this(BuiltInRegistries.MENU.getId(id), windowId, name, additionalData);
}
private OpenContainer(int id, int windowId, Component name, FriendlyByteBuf additionalData)
{
this.id = id;
this.windowId = windowId;
this.name = name;
this.additionalData = additionalData;
}
public static void encode(OpenContainer msg, FriendlyByteBuf buf)
{
buf.writeVarInt(msg.id);
buf.writeVarInt(msg.windowId);
buf.writeComponent(msg.name);
buf.writeByteArray(msg.additionalData.readByteArray());
}
public static OpenContainer decode(FriendlyByteBuf buf)
{
return new OpenContainer(buf.readVarInt(), buf.readVarInt(), buf.readComponent(), new FriendlyByteBuf(Unpooled.wrappedBuffer(buf.readByteArray(32600))));
}
public static void handle(OpenContainer msg, Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() -> {
try
{
MenuScreens.getScreenFactory(msg.getType(), Minecraft.getInstance(), msg.getWindowId(), msg.getName()).ifPresent(f -> {
AbstractContainerMenu c = msg.getType().create(msg.getWindowId(), Minecraft.getInstance().player.getInventory(), msg.getAdditionalData());
@SuppressWarnings("unchecked") Screen s = ((MenuScreens.ScreenConstructor<AbstractContainerMenu, ?>) f).create(c, Minecraft.getInstance().player.getInventory(), msg.getName());
Minecraft.getInstance().player.containerMenu = ((MenuAccess<?>) s).getMenu();
Minecraft.getInstance().setScreen(s);
});
} finally
{
msg.getAdditionalData().release();
}
});
ctx.get().setPacketHandled(true);
}
public final MenuType<?> getType()
{
return BuiltInRegistries.MENU.byId(this.id);
}
public int getWindowId()
{
return windowId;
}
public Component getName()
{
return name;
}
public FriendlyByteBuf getAdditionalData()
{
return additionalData;
}
}
}
@@ -71,13 +71,14 @@ import java.util.stream.Collectors;
* }</pre>
*
*/
// TODO: Rewrite to a simpler format And/Or remove when I rewrite DisplayTest
public record ServerStatusPing(
Map<ResourceLocation, ChannelData> channels,
Map<String, String> mods,
int fmlNetworkVer,
boolean truncated
)
{
) {
private static final Codec<ByteBuf> BYTE_BUF_CODEC = Codec.STRING
.xmap(ServerStatusPing::decodeOptimized, ServerStatusPing::encodeOptimized);
@@ -99,43 +100,38 @@ public record ServerStatusPing(
))));
public ServerStatusPing()
{
public ServerStatusPing() {
this(
NetworkRegistry.buildChannelVersionsForListPing(),
Util.make(new HashMap<>(), map -> ModList.get().forEachModContainer((modid, mc) ->
map.put(modid, mc.getCustomExtension(IExtensionPoint.DisplayTest.class)
.map(IExtensionPoint.DisplayTest::suppliedVersion)
.map(Supplier::get)
.orElse(NetworkConstants.IGNORESERVERONLY)))),
NetworkConstants.FMLNETVERSION,
false
NetworkRegistry.buildChannelVersionsForListPing(),
Util.make(new HashMap<>(), map -> ModList.get().forEachModContainer((modid, mc) ->
map.put(modid, mc.getCustomExtension(IExtensionPoint.DisplayTest.class)
.map(IExtensionPoint.DisplayTest::suppliedVersion)
.map(Supplier::get)
.orElse(IExtensionPoint.DisplayTest.IGNORESERVERONLY)))),
NetworkContext.NET_VERSION,
false
);
}
@Override // Don't compare the truncated flag as it is irrelevant
public boolean equals(Object o)
{
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ServerStatusPing that)) return false;
return fmlNetworkVer == that.fmlNetworkVer && channels.equals(that.channels) && mods.equals(that.mods);
}
@Override
public int hashCode()
{
public int hashCode() {
return Objects.hash(channels, mods, fmlNetworkVer);
}
private List<Map.Entry<ResourceLocation, ChannelData>> getChannelsForMod(String modId)
{
private List<Map.Entry<ResourceLocation, ChannelData>> getChannelsForMod(String modId) {
return channels.entrySet().stream()
.filter(c -> c.getKey().getNamespace().equals(modId))
.toList();
}
private List<Map.Entry<ResourceLocation, ChannelData>> getNonModChannels()
{
private List<Map.Entry<ResourceLocation, ChannelData>> getNonModChannels() {
return channels.entrySet().stream()
.filter(c -> !mods.containsKey(c.getKey().getNamespace()))
.toList();
@@ -161,55 +157,45 @@ public record ServerStatusPing(
buf.writeBoolean(false); // placeholder for whether we are truncating
buf.writeShort(mods.size()); // short so that we can replace it later in case of truncation
int writtenCount = 0;
for (var modEntry : mods.entrySet())
{
var isIgnoreServerOnly = modEntry.getValue().equals(NetworkConstants.IGNORESERVERONLY);
for (var modEntry : mods.entrySet()) {
var isIgnoreServerOnly = modEntry.getValue().equals(IExtensionPoint.DisplayTest.IGNORESERVERONLY);
var channelsForMod = getChannelsForMod(modEntry.getKey());
var channelSizeAndVersionFlag = channelsForMod.size() << 1;
if (isIgnoreServerOnly)
{
channelSizeAndVersionFlag |= VERSION_FLAG_IGNORESERVERONLY;
}
buf.writeVarInt(channelSizeAndVersionFlag);
buf.writeUtf(modEntry.getKey());
if (!isIgnoreServerOnly)
{
buf.writeUtf(modEntry.getValue());
}
// write the channels for this mod, if any
for (var entry : channelsForMod)
{
for (var entry : channelsForMod) {
buf.writeUtf(entry.getKey().getPath());
buf.writeUtf(entry.getValue().version());
buf.writeVarInt(entry.getValue().version());
buf.writeBoolean(entry.getValue().required());
}
writtenCount++;
if (buf.readableBytes() >= 60000)
{
if (buf.readableBytes() >= 60000) {
reachedSizeLimit = true;
break;
}
}
if (!reachedSizeLimit)
{
if (!reachedSizeLimit) {
// write any channels that don't match up with a ModID.
var nonModChannels = getNonModChannels();
buf.writeVarInt(nonModChannels.size());
for (var entry : nonModChannels)
{
buf.writeResourceLocation(entry.getKey());
buf.writeUtf(entry.getValue().version());
buf.writeVarInt(entry.getValue().version());
buf.writeBoolean(entry.getValue().required());
}
}
else
{
} else {
buf.setShort(1, writtenCount);
buf.writeVarInt(0);
}
@@ -226,8 +212,7 @@ public record ServerStatusPing(
Map<ResourceLocation, ChannelData> channels;
Map<String, String> mods;
try
{
try {
truncated = buf.readBoolean();
var modsSize = buf.readUnsignedShort();
mods = new HashMap<>();
@@ -237,10 +222,10 @@ public record ServerStatusPing(
var channelSize = channelSizeAndVersionFlag >>> 1;
var isIgnoreServerOnly = (channelSizeAndVersionFlag & VERSION_FLAG_IGNORESERVERONLY) != 0;
var modId = buf.readUtf();
var modVersion = isIgnoreServerOnly ? NetworkConstants.IGNORESERVERONLY : buf.readUtf();
var modVersion = isIgnoreServerOnly ? IExtensionPoint.DisplayTest.IGNORESERVERONLY : buf.readUtf();
for (var i1 = 0; i1 < channelSize; i1++) {
var channelName = buf.readUtf();
var channelVersion = buf.readUtf();
var channelVersion = buf.readVarInt();
var requiredOnClient = buf.readBoolean();
final ResourceLocation id = new ResourceLocation(modId, channelName);
channels.put(id, new ChannelData(id, channelVersion, requiredOnClient));
@@ -252,13 +237,11 @@ public record ServerStatusPing(
var nonModChannelCount = buf.readVarInt();
for (var i = 0; i < nonModChannelCount; i++) {
var channelName = buf.readResourceLocation();
var channelVersion = buf.readUtf();
var channelVersion = buf.readVarInt();
var requiredOnClient = buf.readBoolean();
channels.put(channelName, new ChannelData(channelName, channelVersion, requiredOnClient));
}
}
finally
{
} finally {
buf.release();
}
@@ -269,8 +252,7 @@ public record ServerStatusPing(
* Encode given ByteBuf to a String. This is optimized for UTF-16 Code-Point count.
* Supports at most 2^30 bytes in length
*/
private static String encodeOptimized(ByteBuf buf)
{
private static String encodeOptimized(ByteBuf buf) {
var byteLength = buf.readableBytes();
var sb = new StringBuilder();
sb.append((char) (byteLength & 0x7FFF));
@@ -278,10 +260,8 @@ public record ServerStatusPing(
int buffer = 0; // we will need at most 8 + 14 = 22 bits of buffer, so an int is enough
int bitsInBuf = 0;
while (buf.isReadable())
{
if (bitsInBuf >= 15)
{
while (buf.isReadable()) {
if (bitsInBuf >= 15) {
char c = (char) (buffer & 0x7FFF);
sb.append(c);
buffer >>>= 15;
@@ -293,8 +273,7 @@ public record ServerStatusPing(
}
buf.release();
if (bitsInBuf > 0)
{
if (bitsInBuf > 0) {
char c = (char) (buffer & 0x7FFF);
sb.append(c);
}
@@ -304,8 +283,7 @@ public record ServerStatusPing(
/**
* Decode binary data encoded by {@link #encodeOptimized}
*/
private static ByteBuf decodeOptimized(String s)
{
private static ByteBuf decodeOptimized(String s) {
var size0 = ((int) s.charAt(0));
var size1 = ((int) s.charAt(1));
var size = size0 | (size1 << 15);
@@ -315,10 +293,8 @@ public record ServerStatusPing(
int stringIndex = 2;
int buffer = 0; // we will need at most 8 + 14 = 22 bits of buffer, so an int is enough
int bitsInBuf = 0;
while (stringIndex < s.length())
{
while (bitsInBuf >= 8)
{
while (stringIndex < s.length()) {
while (bitsInBuf >= 8) {
buf.writeByte(buffer);
buffer >>>= 8;
bitsInBuf -= 8;
@@ -331,8 +307,7 @@ public record ServerStatusPing(
}
// write any leftovers
while (buf.readableBytes() < size)
{
while (buf.readableBytes() < size) {
buf.writeByte(buffer);
buffer >>>= 8;
bitsInBuf -= 8;
@@ -340,38 +315,34 @@ public record ServerStatusPing(
return buf;
}
public Map<ResourceLocation, ChannelData> getRemoteChannels()
{
public Map<ResourceLocation, ChannelData> getRemoteChannels() {
return this.channels;
}
public Map<String,String> getRemoteModData()
{
public Map<String,String> getRemoteModData() {
return mods;
}
public int getFMLNetworkVersion()
{
public int getFMLNetworkVersion() {
return fmlNetworkVer;
}
public boolean isTruncated()
{
public boolean isTruncated() {
return truncated;
}
public record ModInfo(String modId, String modmarker) {
public static final Codec<ModInfo> CODEC = RecordCodecBuilder.create(in -> in.group(
Codec.STRING.fieldOf("modId").forGetter(ModInfo::modId),
Codec.STRING.fieldOf("modmarker").forGetter(ModInfo::modmarker)
Codec.STRING.fieldOf("modId").forGetter(ModInfo::modId),
Codec.STRING.fieldOf("modmarker").forGetter(ModInfo::modmarker)
).apply(in, ModInfo::new));
}
public record ChannelData(ResourceLocation res, String version, boolean required) {
public record ChannelData(ResourceLocation res, int version, boolean required) {
public static final Codec<ChannelData> CODEC = RecordCodecBuilder.create(in -> in.group(
ResourceLocation.CODEC.fieldOf("res").forGetter(ChannelData::res),
Codec.STRING.fieldOf("version").forGetter(ChannelData::version),
Codec.BOOL.fieldOf("required").forGetter(ChannelData::required)
ResourceLocation.CODEC.fieldOf("res").forGetter(ChannelData::res),
Codec.INT.fieldOf("version").forGetter(ChannelData::version),
Codec.BOOL.fieldOf("required").forGetter(ChannelData::required)
).apply(in, ChannelData::new));
}
}
@@ -0,0 +1,347 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraftforge.event.network.CustomPayloadEvent;
import org.apache.commons.lang3.function.TriConsumer;
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 org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import io.netty.buffer.Unpooled;
import io.netty.util.AttributeKey;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.shorts.Short2ObjectArrayMap;
import it.unimi.dsi.fastutil.shorts.Short2ObjectMap;
import java.util.*;
import java.util.function.*;
public class SimpleChannel extends Channel<Object> {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker MARKER = MarkerManager.getMarker("SIMPLE_CHANNEL");
@ApiStatus.Internal
SimpleChannel(NetworkInstance instance) {
super(instance);
instance.addListener(this::networkEventListener);
}
/**
* Build a new MessageBuilder, using the next available discriminator.
*
* @param type Type of message
* @param <M> Type of type
*/
public <M> MessageBuilder<M> messageBuilder(final Class<M> type) {
return messageBuilder(type, nextIndex());
}
/**
* Build a new MessageBuilder.
*
* @param type Type of message
* @param discriminator Manually configured discriminator, Must be between 0 and 255 inclusive.
* @param <M> Type of type
*/
public <M> MessageBuilder<M> messageBuilder(final Class<M> type, short discriminator) {
return messageBuilder(type, discriminator, null);
}
/**
* Build a new MessageBuilder, using the next available discriminator.
*
* @param type Type of message
* @param direction a impl direction which will be asserted before any processing of this message occurs. Use to
* enforce strict sided handling to prevent spoofing.
* @param <M> Type of type
*/
public <M> MessageBuilder<M> messageBuilder(final Class<M> type, NetworkDirection direction) {
return messageBuilder(type, nextIndex(), direction);
}
/**
* Build a new MessageBuilder.
*
* @param type Type of message
* @param discriminator Manually configured discriminator, Must be between 0 and 255 inclusive.
* @param direction a impl direction which will be asserted before any processing of this message occurs. Use to
* enforce strict sided handling to prevent spoofing.
* @param <M> Type of type
*/
public <M> MessageBuilder<M> messageBuilder(final Class<M> type, short discriminator, NetworkDirection direction) {
return new MessageBuilder<>(this, type, discriminator, direction);
}
public static class MessageBuilder<MSG> {
private final SimpleChannel channel;
private final Class<MSG> type;
private final short id;
private final Optional<NetworkDirection> direction;
private BiConsumer<MSG, FriendlyByteBuf> encoder;
private Function<FriendlyByteBuf, MSG> decoder;
private BiConsumer<MSG, CustomPayloadEvent.Context> consumer;
private MessageBuilder(final SimpleChannel channel, final Class<MSG> type, short id, @Nullable NetworkDirection networkDirection) {
this.channel = channel;
this.type = type;
this.id = id;
this.direction = Optional.ofNullable(networkDirection);
}
/**
* Set the message encoder, which writes this message to a {@link FriendlyByteBuf}.
* <p>
* The encoder is called <em>immediately</em> {@linkplain #send(PacketDistributor.PacketTarget, Object) when the
* packet is sent}. This means encoding typically occurs on the main server/client thread rather than on the
* network thread.
* <p>
* However, this behaviour should not be relied on, and the encoder should try to be thread-safe and not
* interact with the current game state.
*
* @param encoder The message encoder.
* @return This message builder, for chaining.
*/
public MessageBuilder<MSG> encoder(BiConsumer<MSG, FriendlyByteBuf> encoder) {
this.encoder = encoder;
return this;
}
/**
* Set the message decoder, which reads the message from a {@link FriendlyByteBuf}.
* <p>
* The decoder is called when the message is received on the network thread. The decoder should not attempt to
* access or mutate any game state, deferring that until the {@linkplain #consumer(ToBooleanBiFunction) the
* message is handled}.
*
* @param decoder The message decoder.
* @return The message builder, for chaining.
*/
public MessageBuilder<MSG> decoder(Function<FriendlyByteBuf, MSG> decoder) {
this.decoder = decoder;
return this;
}
/**
* Set the message consumer, which is called once a message has been decoded. This accepts the decoded message
* object and the message's context.
* <p>
* The consumer is called on the network thread, and so should not interact with most game state by default.
* {@link CustomPayloadEvent.Context#enqueueWork(Runnable)} can be used to handle the message on the main server or
* client thread. Alternatively one can use {@link #consumerMainThread(BiConsumer)} to run the handler on the
* main thread.
*
* @param consumer The message consumer.
* @return The message builder, for chaining.
*
* @see #consumerMainThread(BiConsumer)
*/
public MessageBuilder<MSG> consumerNetworkThread(BiConsumer<MSG, CustomPayloadEvent.Context> consumer) {
this.consumer = consumer;
return this;
}
/**
* Set the message consumer, which is called once a message has been decoded. This accepts the decoded message
* object and the message's context. The instance will be retrieved from the associated AttributeKey on the
* channel.
* <p>
* The consumer is called on the network thread, and so should not interact with most game state by default.
* {@link CustomPayloadEvent.Context#enqueueWork(Runnable)} can be used to handle the message on the main server or
* client thread. Alternatively one can use {@link #consumerMainThread(TriConsumer)} to run the handler on the
* main thread.
*
* @param consumer The message consumer.
* @return The message builder, for chaining.
*
* @see #consumerMainThread(BiConsumer)
*/
public <C> MessageBuilder<MSG> consumerNetworkThread(AttributeKey<C> key, TriConsumer<C, MSG, CustomPayloadEvent.Context> consumer) {
return consumerNetworkThread((msg, ctx) -> {
var inst = ctx.getConnection().channel().attr(key).get();
consumer.accept(inst, msg, ctx);
});
}
/**
* Function returning a boolean "packet handled" indication, for simpler channel building.
*
* @see #consumerNetworkThread(BiConsumer)
*/
public MessageBuilder<MSG> consumerNetworkThread(ToBooleanBiFunction<MSG, CustomPayloadEvent.Context> handler) {
this.consumer = (msg, ctx) -> ctx.setPacketHandled(handler.applyAsBool(msg, ctx));
return this;
}
/**
* Function returning a boolean "packet handled" indication, for simpler channel building.
*
* @see #consumerNetworkThread(AttributeKey,TriConsumer)
*/
public <C> MessageBuilder<MSG> consumerNetworkThread(AttributeKey<C> key, ToBooleanTriFunction<C, MSG, CustomPayloadEvent.Context> handler) {
return consumerNetworkThread((msg, ctx) -> {
var inst = ctx.getConnection().channel().attr(key).get();
return handler.applyAsBool(inst, msg, ctx);
});
}
/**
* Set the message consumer, which is called once a message has been decoded. This accepts the decoded message
* object and the message's context.
* <p>
* Unlike {@link #consumerNetworkThread(BiConsumer)}, the consumer is called on the main thread, and so can
* interact with most game state by default.
*
* @param consumer The message consumer.
* @return The message builder, for chaining.
*
* @see #consumerNetworkThread(BiConsumer)
*/
public MessageBuilder<MSG> consumerMainThread(BiConsumer<MSG, CustomPayloadEvent.Context> consumer) {
this.consumer = (msg, context) -> {
var ctx = context;
ctx.enqueueWork(() -> consumer.accept(msg, context));
ctx.setPacketHandled(true);
};
return this;
}
/**
* Set the message consumer, which is called once a message has been decoded. This accepts the decoded message
* object and the message's context. The instance will be retrieved from the associated AttributeKey on the
* channel.
* <p>
* Unlike {@link #consumerNetworkThread(AttributeKey,TriConsumer)}, the consumer is called on the main thread,
* and so can interact with most game state by default.
*
* @param consumer The message consumer.
* @return The message builder, for chaining.
*
* @see #consumerNetworkThread(BiConsumer)
*/
public <C> MessageBuilder<MSG> consumerMainThread(AttributeKey<C> key, TriConsumer<C, MSG, CustomPayloadEvent.Context> consumer) {
this.consumer = (msg, ctx) -> {
ctx.enqueueWork(() -> {
var inst = ctx.getConnection().channel().attr(key).get();
consumer.accept(inst, msg, ctx);
});
ctx.setPacketHandled(true);
};
return this;
}
// TODO: Move out to full classes?
@FunctionalInterface
public interface ToBooleanBiFunction<T, U> {
boolean applyAsBool(T first, U second);
}
@FunctionalInterface
public interface ToBooleanTriFunction<T, U, V> {
boolean applyAsBool(T first, U second, V third);
}
/**
* Finishes building this packet.
* @return The attached SimpleChannel to facilitate chaining.
*/
public SimpleChannel add() {
var msg = new Message<>(this.id, this.type, this.direction, this.encoder, this.decoder, this.consumer);
if (channel.byId.containsKey(msg.index()))
throw new IllegalStateException("Failed to register SimpleChannel message, ID " + msg.index() + " already claimed: " + msg.type().getName());
if (channel.byType.containsKey(msg.type()))
throw new IllegalStateException("Failed to register SimpleChannel message, Class " + msg.type().getName() + " already registered");
channel.byId.put(msg.index(), msg);
channel.byType.put(msg.type(), msg);
return this.channel;
}
}
/* ===================================================================================
* INTERNAL BELOW THIS
* ===================================================================================
*/
private short lastIndex = 0;
private Short2ObjectMap<Message<?>> byId = new Short2ObjectArrayMap<>();
private Object2ObjectMap<Class<?>, Message<?>> byType = new Object2ObjectArrayMap<>();
private record Message<MSG>(
short index,
Class<MSG> type,
Optional<NetworkDirection> direction,
BiConsumer<MSG, FriendlyByteBuf> encoder,
Function<FriendlyByteBuf, MSG> decoder,
BiConsumer<MSG, CustomPayloadEvent.Context> consumer
){ };
private short nextIndex() {
while (byId.containsKey(lastIndex)) {
lastIndex++;
if (lastIndex > 0xFF)
throw new IllegalStateException("Ran out of discriminator, only 255 are allowed");
}
return lastIndex++;
}
private void networkEventListener(CustomPayloadEvent event) {
var data = event.getPayload();
if (data == null || !data.isReadable()) {
LOGGER.error(MARKER, "Received empty payload on channel {} login index {}", getName(), event.getLoginIndex());
return;
}
short id = data.readUnsignedByte();
var msg = byId.get(id);
if (msg == null) {
LOGGER.error(MARKER, "Received invalid discriminator byte {} on channel {}", id, getName());
return;
}
var con = event.getSource().getConnection();
var dir = event.getSource().getDirection();
if (msg.direction.isPresent() && msg.direction.get() != dir) {
var error = "Illegal packet received, terminating connection. " + msg.type().getName() + " expexted " + msg.direction.get() + " but was " + dir;
LOGGER.error(MARKER, error);
con.disconnect(Component.literal(error));
throw new IllegalStateException(error);
}
decodeAndDispatch(data, event.getSource(), msg);
}
// Yay generics
private static <MSG> void decodeAndDispatch(FriendlyByteBuf data, CustomPayloadEvent.Context ctx, Message<MSG> msg) {
var message = msg.decoder().apply(data);
msg.consumer.accept(message, ctx);
}
@SuppressWarnings("unchecked")
@Override
protected FriendlyByteBuf toBuffer(Object message) {
var msg = byType.get(message.getClass());
if (msg == null) {
LOGGER.error(MARKER, "Attempted to send invalid message {} on channel {}", message.getClass().getName(), getName());
throw new IllegalArgumentException("Invalid message " + message.getClass().getName());
}
var ret = new FriendlyByteBuf(Unpooled.buffer());
ret.writeByte(msg.index() & 0xFF);
if (msg.encoder() != null)
((BiConsumer<Object, FriendlyByteBuf>)msg.encoder()).accept(message, ret);
return ret;
}
}
@@ -0,0 +1,36 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.config;
import java.util.function.Consumer;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.Packet;
import net.minecraft.server.network.ConfigurationTask.Type;
public class ConfigurationTaskContext {
private final Connection connection;
private final Consumer<Packet<?>> send;
private final Consumer<Type> finish;
public ConfigurationTaskContext(Connection connection, Consumer<Packet<?>> send, Consumer<Type> finish) {
this.connection = connection;
this.send = send;
this.finish = finish;
}
public Connection getConnection() {
return connection;
}
public void send(Packet<?> packet) {
this.send.accept(packet);
}
public void finish(Type task) {
this.finish.accept(task);
}
}
@@ -0,0 +1,44 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.config;
import java.util.function.Consumer;
import net.minecraft.network.protocol.Packet;
import net.minecraft.server.network.ConfigurationTask;
/**
* A simple ConfigurationTask that will run a block of code and then mark itself as finished.
*/
public class SimpleConfigurationTask implements ConfigurationTask {
private final Type type;
private final Consumer<ConfigurationTaskContext> task;
public SimpleConfigurationTask(Type type, Consumer<ConfigurationTaskContext> task) {
this.type = type;
this.task = task;
}
public SimpleConfigurationTask(Type type, Runnable task) {
this(type, c -> task.run());
}
@Override
public void start(ConfigurationTaskContext ctx) {
this.task.accept(ctx);
ctx.finish(type());
}
@Override
public void start(Consumer<Packet<?>> send) {
throw new IllegalStateException("This should never be called");
}
@Override
public Type type() {
return this.type;
}
}
@@ -1,55 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.event;
import net.minecraft.network.Connection;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkInstance;
import net.minecraftforge.network.NetworkRegistry;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* An event-bus like object on which {@link NetworkEvent}s are posted.
*
* These events are fired from the network thread, and so should not interact with most game state by default.
* {@link NetworkEvent.Context#enqueueWork(Runnable)} can be used to handle the message on the main server or client
* thread.
*
* @see NetworkRegistry#newEventChannel(ResourceLocation, Supplier, Predicate, Predicate)
* @see NetworkRegistry.ChannelBuilder#newEventChannel(ResourceLocation, Supplier, Predicate, Predicate)
*/
public class EventNetworkChannel
{
private final NetworkInstance instance;
public EventNetworkChannel(NetworkInstance instance)
{
this.instance = instance;
}
public <T extends NetworkEvent> void addListener(Consumer<T> eventListener)
{
instance.addListener(eventListener);
}
public void registerObject(Object object)
{
instance.registerObject(object);
}
public void unregisterObject(Object object)
{
instance.unregisterObject(object);
}
public boolean isRemotePresent(Connection manager) {
return instance.isRemotePresent(manager);
}
}
@@ -16,34 +16,27 @@ import org.apache.logging.log4j.Logger;
import com.google.common.collect.ImmutableMap;
public class NetworkFilters
{
public class NetworkFilters {
private static final Logger LOGGER = LogManager.getLogger();
private static final Map<String, Function<Connection, VanillaPacketFilter>> instances = ImmutableMap.of(
"forge:vanilla_filter", manager -> new VanillaConnectionNetworkFilter()/*,
"forge:forge_fixes", ForgeConnectionNetworkFilter::new*/
"forge:vanilla_filter", manager -> new VanillaConnectionNetworkFilter()/*,
"forge:forge_fixes", ForgeConnectionNetworkFilter::new*/
);
public static void injectIfNecessary(Connection manager)
{
public static void injectIfNecessary(Connection manager) {
ChannelPipeline pipeline = manager.channel().pipeline();
if (pipeline.get("packet_handler") == null)
return; // Realistically this can only ever be null if the connection was prematurely closed due to an error. We return early here to reduce further log spam.
instances.forEach((key, filterFactory) -> {
VanillaPacketFilter filter = filterFactory.apply(manager);
if (filter.isNecessary(manager))
{
if (filter.isNecessary(manager)) {
pipeline.addBefore("packet_handler", key, filter);
LOGGER.debug("Injected {} into {}", filter, manager);
}
});
}
private NetworkFilters()
{
}
private NetworkFilters() {}
}
@@ -23,42 +23,34 @@ import net.minecraft.network.Connection;
import net.minecraft.network.protocol.game.ClientboundCommandsPacket;
import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.NetworkHooks;
import net.minecraftforge.network.ConnectionType;
import net.minecraftforge.network.NetworkContext;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryManager;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import com.google.common.collect.ImmutableMap;
import com.mojang.brigadier.tree.RootCommandNode;
import com.mojang.logging.LogUtils;
/**
* A filter for impl packets, used to filter/modify parts of vanilla impl messages that
* will cause errors or warnings on vanilla clients, for example entity attributes that are added by Forge or mods.
*/
@ChannelHandler.Sharable
public class VanillaConnectionNetworkFilter extends VanillaPacketFilter
{
private static final Logger LOGGER = LogUtils.getLogger();
public VanillaConnectionNetworkFilter()
{
public class VanillaConnectionNetworkFilter extends VanillaPacketFilter {
public VanillaConnectionNetworkFilter() {
super(
ImmutableMap.<Class<? extends Packet<?>>, BiConsumer<Packet<?>, List<? super Packet<?>>>>builder()
.put(handler(ClientboundUpdateAttributesPacket.class, VanillaConnectionNetworkFilter::filterEntityProperties))
.put(handler(ClientboundCommandsPacket.class, VanillaConnectionNetworkFilter::filterCommandList))
// TODO Filter tags
//.put(handler(ClientboundUpdateTagsPacket.class, VanillaConnectionNetworkFilter::filterCustomTagTypes))
.build()
ImmutableMap.<Class<? extends Packet<?>>, BiConsumer<Packet<?>, List<? super Packet<?>>>>builder()
.put(handler(ClientboundUpdateAttributesPacket.class, VanillaConnectionNetworkFilter::filterEntityProperties))
.put(handler(ClientboundCommandsPacket.class, VanillaConnectionNetworkFilter::filterCommandList))
// TODO Filter tags
//.put(handler(ClientboundUpdateTagsPacket.class, VanillaConnectionNetworkFilter::filterCustomTagTypes))
.build()
);
}
@Override
protected boolean isNecessary(Connection manager)
{
return NetworkHooks.isVanillaConnection(manager);
protected boolean isNecessary(Connection connection) {
return NetworkContext.get(connection).getType() == ConnectionType.VANILLA;
}
/**
@@ -66,8 +58,7 @@ public class VanillaConnectionNetworkFilter extends VanillaPacketFilter
* A vanilla client would ignore these with an error log.
*/
@NotNull
private static ClientboundUpdateAttributesPacket filterEntityProperties(ClientboundUpdateAttributesPacket msg)
{
private static ClientboundUpdateAttributesPacket filterEntityProperties(ClientboundUpdateAttributesPacket msg) {
ClientboundUpdateAttributesPacket newPacket = new ClientboundUpdateAttributesPacket(msg.getEntityId(), Collections.emptyList());
msg.getValues().stream()
.filter(snapshot -> {
@@ -83,8 +74,7 @@ public class VanillaConnectionNetworkFilter extends VanillaPacketFilter
* A vanilla client would fail to deserialize the packet and disconnect with an error message if these were sent.
*/
@NotNull
private static ClientboundCommandsPacket filterCommandList(ClientboundCommandsPacket packet)
{
private static ClientboundCommandsPacket filterCommandList(ClientboundCommandsPacket packet) {
CommandBuildContext commandBuildContext = Commands.createValidationContext(VanillaRegistries.createLookup());
RootCommandNode<SharedSuggestionProvider> root = packet.getRoot(commandBuildContext);
RootCommandNode<SharedSuggestionProvider> newRoot = CommandTreeCleaner.cleanArgumentTypes(root, argType -> {
@@ -109,12 +99,11 @@ public class VanillaConnectionNetworkFilter extends VanillaPacketFilter
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return new ClientboundUpdateTagsPacket(tags);
}
*/
private static boolean isVanillaRegistry(ResourceLocation location)
{
private static boolean isVanillaRegistry(ResourceLocation location) {
// Checks if the registry name is contained within the static view of both BuiltInRegistries and VanillaRegistries
return RegistryManager.getVanillaRegistryKeys().contains(location)
|| VanillaRegistries.DATAPACK_REGISTRY_KEYS.stream().anyMatch(k -> k.location().equals(location));
}
*/
}
@@ -0,0 +1,22 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.packets;
import net.minecraft.network.FriendlyByteBuf;
/*
* A simple packet used to acknowledge that the client has received and processed a message sent by the server.
* The token can be anything, ideally it would an identifier sent from the server.
*/
public record Acknowledge(int token) {
public void encode(FriendlyByteBuf buf) {
buf.writeVarInt(token);
}
public static Acknowledge decode(FriendlyByteBuf buf) {
return new Acknowledge(buf.readVarInt());
}
}
@@ -0,0 +1,35 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.packets;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.NetworkRegistry;
public record ChannelVersions(Map<ResourceLocation, Integer> channels) {
public ChannelVersions() {
this(NetworkRegistry.buildChannelVersions());
}
public static ChannelVersions decode(FriendlyByteBuf buf) {
Map<ResourceLocation, Integer> channels = new HashMap<>();
int len = buf.readVarInt();
for (int x = 0; x < len; x++)
channels.put(buf.readResourceLocation(), buf.readVarInt());
return new ChannelVersions(channels);
}
public void encode(FriendlyByteBuf buf) {
buf.writeVarInt(channels.size());
channels.forEach((k, v) -> {
buf.writeResourceLocation(k);
buf.writeVarInt(v);
});
}
}
@@ -0,0 +1,19 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.packets;
import net.minecraft.network.FriendlyByteBuf;
public record ConfigData(String name, byte[] data) {
public void encode(final FriendlyByteBuf buf) {
buf.writeUtf(this.name());
buf.writeByteArray(this.data());
}
public static ConfigData decode(FriendlyByteBuf buf) {
return new ConfigData(buf.readUtf(), buf.readByteArray());
}
}
@@ -0,0 +1,24 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.packets;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
public record LoginWrapper(ResourceLocation channel, FriendlyByteBuf data) {
public static LoginWrapper decode(FriendlyByteBuf buf) {
var channel = buf.readResourceLocation();
var len = buf.readVarInt();
var data = new FriendlyByteBuf(buf.readBytes(len));
return new LoginWrapper(channel, data);
}
public void encode(FriendlyByteBuf buf) {
buf.writeResourceLocation(channel);
buf.writeVarInt(data.readableBytes());
buf.writeBytes(data.slice());
}
}
@@ -0,0 +1,57 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.packets;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.network.NetworkContext.NetworkMismatchData;
import net.minecraftforge.network.NetworkContext.NetworkMismatchData.Version;
/**
* Notifies the client of a channel mismatch on the server, so a {@link net.minecraftforge.client.gui.ModMismatchDisconnectedScreen} is used to notify the user of the disconnection.
* This packet also sends the data of a channel mismatch (currently, the ids and versions of the mismatched channels) to the client for it to display the correct information in said screen.
*/
public record MismatchData(
Map<ResourceLocation, Version> mismatched,
Set<ResourceLocation> missing
) {
private static final int MAX_LENGTH = 0x100;
public MismatchData(NetworkMismatchData data) {
this(data.mismatched(), data.missing());
}
public static MismatchData decode(FriendlyByteBuf buf) {
var mismatched = buf.readMap(
i -> new ResourceLocation(i.readUtf(MAX_LENGTH)),
i -> new Version(
i.readUtf(MAX_LENGTH),
i.readUtf(MAX_LENGTH)
)
);
var missing = buf.readCollection(HashSet::new,
i -> new ResourceLocation(i.readUtf(MAX_LENGTH))
);
return new MismatchData(mismatched, missing);
}
public void encode(FriendlyByteBuf buf) {
buf.writeMap(mismatched,
(o, k) -> o.writeUtf(k.toString(), MAX_LENGTH),
(o, v) -> {
o.writeUtf(v.received(), MAX_LENGTH);
o.writeUtf(v.had(), MAX_LENGTH);
}
);
buf.writeCollection(missing,
(o, k) -> o.writeUtf(k.toString(), MAX_LENGTH)
);
}
}
@@ -0,0 +1,53 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.packets;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.fml.ModList;
/**
* Prefixes S2CModList by sending additional data about the mods installed on the server to the client
* The mod data is stored as follows: [modId -> [modName, modVersion]]
*/
public record ModVersions(Map<String, Info> mods) {
private static final int MAX_LENGTH = 0x100;
public static ModVersions create() {
Map<String, ModVersions.Info> mods = new HashMap<>();
ModList.get().getMods().stream().forEach(mod ->
mods.put(
mod.getModId(),
new Info(mod.getDisplayName(), mod.getVersion().toString())
)
);
return new ModVersions(mods);
}
public static ModVersions decode(FriendlyByteBuf buf) {
var mods = buf.<String, Info>readMap(
o -> o.readUtf(MAX_LENGTH),
o -> new Info(
o.readUtf(MAX_LENGTH),
o.readUtf(MAX_LENGTH)
)
);
return new ModVersions(mods);
}
public void encode(FriendlyByteBuf output) {
output.writeMap(mods,
(o, s) -> o.writeUtf(s, MAX_LENGTH),
(o, p) -> {
o.writeUtf(p.name(), MAX_LENGTH);
o.writeUtf(p.version(), MAX_LENGTH);
}
);
}
public record Info(String name, String version) {}
}
@@ -0,0 +1,91 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.packets;
import org.jetbrains.annotations.ApiStatus;
import io.netty.buffer.Unpooled;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.MenuAccess;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraftforge.event.network.CustomPayloadEvent;
// TODO: Reevaluate if this is needed This is the same as ClientboundOpenScreenPacket packet but allows for additional data
public class OpenContainer {
private final int id;
private final int windowId;
private final Component name;
private final FriendlyByteBuf additionalData;
/** Use NetworkHooks.openScreen */
@ApiStatus.Internal
@SuppressWarnings("deprecation")
public OpenContainer(MenuType<?> id, int windowId, Component name, FriendlyByteBuf additionalData) {
this(BuiltInRegistries.MENU.getId(id), windowId, name, additionalData);
}
private OpenContainer(int id, int windowId, Component name, FriendlyByteBuf additionalData) {
this.id = id;
this.windowId = windowId;
this.name = name;
this.additionalData = additionalData;
}
public static void encode(OpenContainer msg, FriendlyByteBuf buf) {
buf.writeVarInt(msg.id);
buf.writeVarInt(msg.windowId);
buf.writeComponent(msg.name);
buf.writeByteArray(msg.additionalData.readByteArray());
}
public static OpenContainer decode(FriendlyByteBuf buf) {
return new OpenContainer(buf.readVarInt(), buf.readVarInt(), buf.readComponent(), new FriendlyByteBuf(Unpooled.wrappedBuffer(buf.readByteArray(32600))));
}
@SuppressWarnings("unchecked")
public static void handle(OpenContainer msg, CustomPayloadEvent.Context ctx) {
ctx.enqueueWork(() -> {
try {
var mc = Minecraft.getInstance();
var inv = mc.player.getInventory();
MenuScreens.getScreenFactory(msg.getType(), mc, msg.getWindowId(), msg.getName()).ifPresent(f -> {
AbstractContainerMenu c = msg.getType().create(msg.getWindowId(), inv, msg.getAdditionalData());
Screen s = ((MenuScreens.ScreenConstructor<AbstractContainerMenu, ?>)f).create(c, inv, msg.getName());
mc.player.containerMenu = ((MenuAccess<?>)s).getMenu();
mc.setScreen(s);
});
} finally {
msg.getAdditionalData().release();
}
});
ctx.setPacketHandled(true);
}
@SuppressWarnings("deprecation")
public final MenuType<?> getType() {
return BuiltInRegistries.MENU.byId(this.id);
}
public int getWindowId() {
return windowId;
}
public Component getName() {
return name;
}
public FriendlyByteBuf getAdditionalData() {
return additionalData;
}
}
@@ -0,0 +1,22 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.packets;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistry.Snapshot;
public record RegistryData(int token, ResourceLocation name, Snapshot data) {
public void encode(FriendlyByteBuf buf) {
buf.writeVarInt(token);
buf.writeResourceLocation(name);
buf.writeBytes(data.getPacketData());
}
public static RegistryData decode(FriendlyByteBuf buf) {
return new RegistryData(buf.readVarInt(), buf.readResourceLocation(), Snapshot.read(buf));
}
}
@@ -0,0 +1,37 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.packets;
import java.util.List;
import net.minecraft.core.Registry;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.DataPackRegistriesHooks;
import net.minecraftforge.registries.RegistryManager;
public record RegistryList(
int token,
List<ResourceLocation> normal,
List<ResourceKey<? extends Registry<?>>> datapacks) {
public RegistryList(int token) {
this(token, RegistryManager.getRegistryNamesForSyncToClient(), List.copyOf(DataPackRegistriesHooks.getSyncedCustomRegistries()));
}
public static RegistryList decode(FriendlyByteBuf buf) {
var token = buf.readVarInt();
var normal = buf.readList(FriendlyByteBuf::readResourceLocation);
List<ResourceKey<? extends Registry<?>>> datapacks = buf.readList(b -> ResourceKey.createRegistryKey(buf.readResourceLocation()));
return new RegistryList(token, normal, datapacks);
}
public void encode(FriendlyByteBuf buf) {
buf.writeVarInt(token());
buf.writeCollection(normal(), FriendlyByteBuf::writeResourceLocation);
buf.writeCollection(datapacks(), FriendlyByteBuf::writeResourceKey);
}
}
@@ -0,0 +1,211 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.packets;
import java.util.Optional;
import java.util.UUID;
import io.netty.buffer.Unpooled;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.common.util.LogicalSidedProvider;
import net.minecraftforge.entity.IEntityAdditionalSpawnData;
import net.minecraftforge.event.network.CustomPayloadEvent;
import net.minecraftforge.event.network.CustomPayloadEvent.Context;
/**
* Used to spawn a custom entity without the same restrictions as
* {@link ClientboundAddEntityPacket}
* <p>
* To customize how your entity is created clientside (instead of using the default factory provided to the
* {@link EntityType})
* see {@link EntityType.Builder#setCustomClientFactory}.
*/
public class SpawnEntity {
private final Entity entity;
private final int typeId;
private final int entityId;
private final UUID uuid;
private final double posX, posY, posZ;
private final byte pitch, yaw, headYaw;
private final int velX, velY, velZ;
private final FriendlyByteBuf buf;
SpawnEntity(Entity e) {
this.entity = e;
this.typeId = BuiltInRegistries.ENTITY_TYPE.getId(e.getType()); //TODO: Codecs
this.entityId = e.getId();
this.uuid = e.getUUID();
this.posX = e.getX();
this.posY = e.getY();
this.posZ = e.getZ();
this.pitch = (byte) Mth.floor(e.getXRot() * 256.0F / 360.0F);
this.yaw = (byte) Mth.floor(e.getYRot() * 256.0F / 360.0F);
this.headYaw = (byte) (e.getYHeadRot() * 256.0F / 360.0F);
Vec3 vec3d = e.getDeltaMovement();
double d1 = Mth.clamp(vec3d.x, -3.9D, 3.9D);
double d2 = Mth.clamp(vec3d.y, -3.9D, 3.9D);
double d3 = Mth.clamp(vec3d.z, -3.9D, 3.9D);
this.velX = (int) (d1 * 8000.0D);
this.velY = (int) (d2 * 8000.0D);
this.velZ = (int) (d3 * 8000.0D);
this.buf = null;
}
private SpawnEntity(int typeId, int entityId, UUID uuid, double posX, double posY, double posZ, byte pitch, byte yaw, byte headYaw, int velX, int velY, int velZ, FriendlyByteBuf buf) {
this.entity = null;
this.typeId = typeId;
this.entityId = entityId;
this.uuid = uuid;
this.posX = posX;
this.posY = posY;
this.posZ = posZ;
this.pitch = pitch;
this.yaw = yaw;
this.headYaw = headYaw;
this.velX = velX;
this.velY = velY;
this.velZ = velZ;
this.buf = buf;
}
public static void encode(SpawnEntity msg, FriendlyByteBuf buf) {
buf.writeVarInt(msg.typeId);
buf.writeInt(msg.entityId);
buf.writeLong(msg.uuid.getMostSignificantBits());
buf.writeLong(msg.uuid.getLeastSignificantBits());
buf.writeDouble(msg.posX);
buf.writeDouble(msg.posY);
buf.writeDouble(msg.posZ);
buf.writeByte(msg.pitch);
buf.writeByte(msg.yaw);
buf.writeByte(msg.headYaw);
buf.writeShort(msg.velX);
buf.writeShort(msg.velY);
buf.writeShort(msg.velZ);
if (msg.entity instanceof IEntityAdditionalSpawnData entityAdditionalSpawnData) {
final FriendlyByteBuf spawnDataBuffer = new FriendlyByteBuf(Unpooled.buffer());
entityAdditionalSpawnData.writeSpawnData(spawnDataBuffer);
buf.writeVarInt(spawnDataBuffer.readableBytes());
buf.writeBytes(spawnDataBuffer);
spawnDataBuffer.release();
} else {
buf.writeVarInt(0);
}
}
public static SpawnEntity decode(FriendlyByteBuf buf) {
return new SpawnEntity(buf.readVarInt(), buf.readInt(), new UUID(buf.readLong(), buf.readLong()), buf.readDouble(), buf.readDouble(), buf.readDouble(), buf.readByte(), buf.readByte(), buf.readByte(), buf.readShort(), buf.readShort(), buf.readShort(), readSpawnDataPacket(buf));
}
private static FriendlyByteBuf readSpawnDataPacket(FriendlyByteBuf buf) {
final int count = buf.readVarInt();
if (count > 0) {
final FriendlyByteBuf spawnDataBuffer = new FriendlyByteBuf(Unpooled.buffer());
spawnDataBuffer.writeBytes(buf, count);
return spawnDataBuffer;
}
return new FriendlyByteBuf(Unpooled.buffer());
}
public static void handle(SpawnEntity msg, CustomPayloadEvent.Context ctx) {
ctx.enqueueWork(() -> {
try {
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.byId(msg.typeId);
Optional<Level> world = LogicalSidedProvider.CLIENTWORLD.get(ctx.getDirection().getReceptionSide());
Entity e = world.map(w -> type.customClientSpawn(msg, w)).orElse(null);
if (e == null)
return;
/*
* Sets the postiion on the client, Mirrors what
* Entity#recreateFromPacket and LivingEntity#recreateFromPacket does.
*/
e.syncPacketPositionCodec(msg.posX, msg.posY, msg.posZ);
e.absMoveTo(msg.posX, msg.posY, msg.posZ, (msg.yaw * 360) / 256.0F, (msg.pitch * 360) / 256.0F);
e.setYHeadRot((msg.headYaw * 360) / 256.0F);
e.setYBodyRot((msg.headYaw * 360) / 256.0F);
e.setId(msg.entityId);
e.setUUID(msg.uuid);
world.filter(ClientLevel.class::isInstance).ifPresent(w -> ((ClientLevel) w).putNonPlayerEntity(msg.entityId, e));
e.lerpMotion(msg.velX / 8000.0, msg.velY / 8000.0, msg.velZ / 8000.0);
if (e instanceof IEntityAdditionalSpawnData entityAdditionalSpawnData)
entityAdditionalSpawnData.readSpawnData(msg.buf);
} finally {
msg.buf.release();
}
});
ctx.setPacketHandled(true);
}
public Entity getEntity() {
return entity;
}
public int getTypeId() {
return typeId;
}
public int getEntityId() {
return entityId;
}
public UUID getUuid() {
return uuid;
}
public double getPosX() {
return posX;
}
public double getPosY() {
return posY;
}
public double getPosZ() {
return posZ;
}
public byte getPitch() {
return pitch;
}
public byte getYaw() {
return yaw;
}
public byte getHeadYaw() {
return headYaw;
}
public int getVelX() {
return velX;
}
public int getVelY() {
return velY;
}
public int getVelZ() {
return velZ;
}
public FriendlyByteBuf getAdditionalData() {
return buf;
}
}
@@ -1,159 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.simple;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import it.unimi.dsi.fastutil.shorts.Short2ObjectArrayMap;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.HandshakeHandler;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkHooks;
import net.minecraftforge.network.NetworkInstance;
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.Objects;
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<MessageHandler<?>> indicies = new Short2ObjectArrayMap<>();
private final Object2ObjectArrayMap<Class<?>, MessageHandler<?>> types = new Object2ObjectArrayMap<>();
private final NetworkInstance networkInstance;
public IndexedMessageCodec() {
this(null);
}
public IndexedMessageCodec(final NetworkInstance instance) {
this.networkInstance = instance;
}
@SuppressWarnings("unchecked")
public <MSG> MessageHandler<MSG> findMessageType(final MSG msgToReply) {
return (MessageHandler<MSG>) types.get(msgToReply.getClass());
}
@SuppressWarnings("unchecked")
<MSG> MessageHandler<MSG> findIndex(final short i) {
return (MessageHandler<MSG>) indicies.get(i);
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
class MessageHandler<MSG>
{
private final Optional<BiConsumer<MSG, FriendlyByteBuf>> encoder;
private final Optional<Function<FriendlyByteBuf, MSG>> decoder;
private final int index;
private final BiConsumer<MSG,Supplier<NetworkEvent.Context>> messageConsumer;
private final Class<MSG> messageType;
private final Optional<NetworkDirection> networkDirection;
private Optional<BiConsumer<MSG, Integer>> loginIndexSetter;
private Optional<Function<MSG, Integer>> loginIndexGetter;
public MessageHandler(int index, Class<MSG> messageType, BiConsumer<MSG, FriendlyByteBuf> encoder, Function<FriendlyByteBuf, MSG> decoder, BiConsumer<MSG, Supplier<NetworkEvent.Context>> messageConsumer, final Optional<NetworkDirection> networkDirection)
{
this.index = index;
this.messageType = messageType;
this.encoder = Optional.ofNullable(encoder);
this.decoder = Optional.ofNullable(decoder);
this.messageConsumer = messageConsumer;
this.networkDirection = networkDirection;
this.loginIndexGetter = Optional.empty();
this.loginIndexSetter = Optional.empty();
indicies.put((short)(index & 0xff), this);
types.put(messageType, this);
}
void setLoginIndexSetter(BiConsumer<MSG, Integer> loginIndexSetter)
{
this.loginIndexSetter = Optional.of(loginIndexSetter);
}
Optional<BiConsumer<MSG, Integer>> getLoginIndexSetter() {
return this.loginIndexSetter;
}
void setLoginIndexGetter(Function<MSG, Integer> loginIndexGetter) {
this.loginIndexGetter = Optional.of(loginIndexGetter);
}
public Optional<Function<MSG, Integer>> getLoginIndexGetter() {
return this.loginIndexGetter;
}
MSG newInstance() {
try {
return messageType.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
LOGGER.error("Invalid login message", e);
throw new RuntimeException(e);
}
}
}
private static <M> void tryDecode(FriendlyByteBuf payload, Supplier<NetworkEvent.Context> context, int payloadIndex, MessageHandler<M> codec)
{
codec.decoder.map(d->d.apply(payload)).
map(p->{
// Only run the loginIndex function for payloadIndexed packets (login)
if (payloadIndex != Integer.MIN_VALUE)
{
codec.getLoginIndexSetter().ifPresent(f-> f.accept(p, payloadIndex));
}
return p;
}).ifPresent(m->codec.messageConsumer.accept(m, context));
}
private static <M> int tryEncode(FriendlyByteBuf target, M message, MessageHandler<M> codec) {
codec.encoder.ifPresent(encoder->{
target.writeByte(codec.index & 0xff);
encoder.accept(message, target);
});
return codec.loginIndexGetter.orElse(m -> Integer.MIN_VALUE).apply(message);
}
public <MSG> int build(MSG message, FriendlyByteBuf target)
{
@SuppressWarnings("unchecked")
MessageHandler<MSG> messageHandler = (MessageHandler<MSG>)types.get(message.getClass());
if (messageHandler == null) {
LOGGER.error(SIMPLENET, "Received invalid message {} on channel {}", message.getClass().getName(), Optional.ofNullable(networkInstance).map(NetworkInstance::getChannelName).map(Objects::toString).orElse("MISSING CHANNEL"));
throw new IllegalArgumentException("Invalid message "+message.getClass().getName());
}
return tryEncode(target, message, messageHandler);
}
void consume(FriendlyByteBuf payload, int payloadIndex, Supplier<NetworkEvent.Context> context) {
if (payload == null || !payload.isReadable()) {
LOGGER.error(SIMPLENET, "Received empty payload on channel {}", Optional.ofNullable(networkInstance).map(NetworkInstance::getChannelName).map(Objects::toString).orElse("MISSING CHANNEL"));
if (!HandshakeHandler.packetNeedsResponse(context.get().getNetworkManager(), payloadIndex))
{
context.get().setPacketHandled(true); //don't disconnect if the corresponding S2C packet that was not recognized on the client doesn't require a proper response
}
return;
}
short discriminator = payload.readUnsignedByte();
final MessageHandler<?> messageHandler = indicies.get(discriminator);
if (messageHandler == null) {
LOGGER.error(SIMPLENET, "Received invalid discriminator byte {} on channel {}", discriminator, Optional.ofNullable(networkInstance).map(NetworkInstance::getChannelName).map(Objects::toString).orElse("MISSING CHANNEL"));
return;
}
NetworkHooks.validatePacketDirection(context.get().getDirection(), messageHandler.networkDirection, context.get().getNetworkManager());
tryDecode(payload, context, payloadIndex, messageHandler);
}
<MSG> MessageHandler<MSG> addCodecIndex(int index, Class<MSG> messageType, BiConsumer<MSG, FriendlyByteBuf> encoder, Function<FriendlyByteBuf, MSG> decoder, BiConsumer<MSG, Supplier<NetworkEvent.Context>> messageConsumer, final Optional<NetworkDirection> networkDirection) {
return new MessageHandler<>(index, messageType, encoder, decoder, messageConsumer, networkDirection);
}
}
@@ -1,313 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.simple;
import io.netty.buffer.Unpooled;
import net.minecraft.client.Minecraft;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.Packet;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkInstance;
import net.minecraftforge.network.PacketDistributor;
import org.apache.commons.lang3.tuple.Pair;
import java.util.*;
import java.util.function.*;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public class SimpleChannel
{
private final NetworkInstance instance;
private final IndexedMessageCodec indexedCodec;
private final Optional<Consumer<NetworkEvent.ChannelRegistrationChangeEvent>> registryChangeConsumer;
private List<Function<Boolean, ? extends List<? extends Pair<String,?>>>> loginPackets;
private Map<Class<?>, Boolean> packetsNeedResponse;
public SimpleChannel(NetworkInstance instance) {
this(instance, Optional.empty());
}
private SimpleChannel(NetworkInstance instance, Optional<Consumer<NetworkEvent.ChannelRegistrationChangeEvent>> registryChangeNotify) {
this.instance = instance;
this.indexedCodec = new IndexedMessageCodec(instance);
this.loginPackets = new ArrayList<>();
this.packetsNeedResponse = new HashMap<>();
instance.addListener(this::networkEventListener);
instance.addGatherListener(this::networkLoginGather);
this.registryChangeConsumer = registryChangeNotify;
}
public SimpleChannel(NetworkInstance instance, Consumer<NetworkEvent.ChannelRegistrationChangeEvent> registryChangeNotify) {
this(instance, Optional.of(registryChangeNotify));
}
private void networkLoginGather(final NetworkEvent.GatherLoginPayloadsEvent gatherEvent) {
loginPackets.forEach(packetGenerator->{
packetGenerator.apply(gatherEvent.isLocal()).forEach(p->{
FriendlyByteBuf pb = new FriendlyByteBuf(Unpooled.buffer());
this.indexedCodec.build(p.getRight(), pb);
gatherEvent.add(pb, this.instance.getChannelName(), p.getLeft(), packetsNeedResponse.getOrDefault(p.getRight().getClass(), true));
});
});
}
private void networkEventListener(final NetworkEvent networkEvent)
{
if (networkEvent instanceof NetworkEvent.ChannelRegistrationChangeEvent) {
this.registryChangeConsumer.ifPresent(l->l.accept(((NetworkEvent.ChannelRegistrationChangeEvent) networkEvent)));
} else {
this.indexedCodec.consume(networkEvent.getPayload(), networkEvent.getLoginIndex(), networkEvent.getSource());
}
}
public <MSG> int encodeMessage(MSG message, final FriendlyByteBuf target) {
return this.indexedCodec.build(message, target);
}
public <MSG> IndexedMessageCodec.MessageHandler<MSG> registerMessage(int index, Class<MSG> messageType, BiConsumer<MSG, FriendlyByteBuf> encoder, Function<FriendlyByteBuf, MSG> decoder, BiConsumer<MSG, Supplier<NetworkEvent.Context>> messageConsumer) {
return registerMessage(index, messageType, encoder, decoder, messageConsumer, Optional.empty());
}
public <MSG> IndexedMessageCodec.MessageHandler<MSG> registerMessage(int index, Class<MSG> messageType, BiConsumer<MSG, FriendlyByteBuf> encoder, Function<FriendlyByteBuf, MSG> decoder, BiConsumer<MSG, Supplier<NetworkEvent.Context>> messageConsumer, final Optional<NetworkDirection> networkDirection) {
return this.indexedCodec.addCodecIndex(index, messageType, encoder, decoder, messageConsumer, networkDirection);
}
private <MSG> Pair<FriendlyByteBuf,Integer> toBuffer(MSG msg) {
final FriendlyByteBuf bufIn = new FriendlyByteBuf(Unpooled.buffer());
int index = encodeMessage(msg, bufIn);
return Pair.of(bufIn, index);
}
public <MSG> void sendToServer(MSG message)
{
sendTo(message, Minecraft.getInstance().getConnection().getConnection(), NetworkDirection.PLAY_TO_SERVER);
}
public <MSG> void sendTo(MSG message, Connection manager, NetworkDirection direction)
{
manager.send(toVanillaPacket(message, direction));
}
/**
* Send a message to the {@link PacketDistributor.PacketTarget} from a {@link PacketDistributor} instance.
*
* <pre>
* channel.send(PacketDistributor.PLAYER.with(()->player), message)
* </pre>
*
* @param target The curried target from a PacketDistributor
* @param message The message to send
* @param <MSG> The type of the message
*/
public <MSG> void send(PacketDistributor.PacketTarget target, MSG message) {
target.send(toVanillaPacket(message, target.getDirection()));
}
public <MSG> Packet<?> toVanillaPacket(MSG message, NetworkDirection direction)
{
return direction.buildPacket(toBuffer(message), instance.getChannelName()).getThis();
}
public <MSG> void reply(MSG msgToReply, NetworkEvent.Context context)
{
context.getPacketDispatcher().sendPacket(instance.getChannelName(), toBuffer(msgToReply).getLeft());
}
/**
* Returns true if the channel is present in the given connection.
*/
public boolean isRemotePresent(Connection manager) {
return instance.isRemotePresent(manager);
}
/**
* Build a new MessageBuilder. The type should implement {@link java.util.function.IntSupplier} if it is a login
* packet.
* @param type Type of message
* @param id id in the indexed codec
* @param <M> Type of type
* @return a MessageBuilder
*/
public <M> MessageBuilder<M> messageBuilder(final Class<M> type, int id) {
return MessageBuilder.forType(this, type, id, null);
}
/**
* Build a new MessageBuilder. The type should implement {@link java.util.function.IntSupplier} if it is a login
* packet.
* @param type Type of message
* @param id id in the indexed codec
* @param direction a impl direction which will be asserted before any processing of this message occurs. Use to
* enforce strict sided handling to prevent spoofing.
* @param <M> Type of type
* @return a MessageBuilder
*/
public <M> MessageBuilder<M> messageBuilder(final Class<M> type, int id, NetworkDirection direction) {
return MessageBuilder.forType(this, type, id, direction);
}
public static class MessageBuilder<MSG> {
private SimpleChannel channel;
private Class<MSG> type;
private int id;
private BiConsumer<MSG, FriendlyByteBuf> encoder;
private Function<FriendlyByteBuf, MSG> decoder;
private BiConsumer<MSG, Supplier<NetworkEvent.Context>> consumer;
private Function<MSG, Integer> loginIndexGetter;
private BiConsumer<MSG, Integer> loginIndexSetter;
private Function<Boolean, List<Pair<String, MSG>>> loginPacketGenerators;
private Optional<NetworkDirection> networkDirection;
private boolean needsResponse = true;
private static <MSG> MessageBuilder<MSG> forType(final SimpleChannel channel, final Class<MSG> type, int id, NetworkDirection networkDirection) {
MessageBuilder<MSG> builder = new MessageBuilder<>();
builder.channel = channel;
builder.id = id;
builder.type = type;
builder.networkDirection = Optional.ofNullable(networkDirection);
return builder;
}
/**
* Set the message encoder, which writes this message to a {@link FriendlyByteBuf}.
* <p>
* The encoder is called <em>immediately</em> {@linkplain #send(PacketDistributor.PacketTarget, Object) when the
* packet is sent}. This means encoding typically occurs on the main server/client thread rather than on the
* network thread.
* <p>
* However, this behaviour should not be relied on, and the encoder should try to be thread-safe and not
* interact with the current game state.
*
* @param encoder The message encoder.
* @return This message builder, for chaining.
*/
public MessageBuilder<MSG> encoder(BiConsumer<MSG, FriendlyByteBuf> encoder) {
this.encoder = encoder;
return this;
}
/**
* Set the message decoder, which reads the message from a {@link FriendlyByteBuf}.
* <p>
* The decoder is called when the message is received on the network thread. The decoder should not attempt to
* access or mutate any game state, deferring that until the {@linkplain #consumer(ToBooleanBiFunction) the
* message is handled}.
*
* @param decoder The message decoder.
* @return The message builder, for chaining.
*/
public MessageBuilder<MSG> decoder(Function<FriendlyByteBuf, MSG> decoder) {
this.decoder = decoder;
return this;
}
public MessageBuilder<MSG> loginIndex(Function<MSG, Integer> loginIndexGetter, BiConsumer<MSG, Integer> loginIndexSetter) {
this.loginIndexGetter = loginIndexGetter;
this.loginIndexSetter = loginIndexSetter;
return this;
}
public MessageBuilder<MSG> buildLoginPacketList(Function<Boolean, List<Pair<String,MSG>>> loginPacketGenerators) {
this.loginPacketGenerators = loginPacketGenerators;
return this;
}
public MessageBuilder<MSG> markAsLoginPacket()
{
this.loginPacketGenerators = (isLocal) -> {
try {
return Collections.singletonList(Pair.of(type.getName(), type.newInstance()));
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException("Inaccessible no-arg constructor for message "+type.getName(), e);
}
};
return this;
}
/**
* Marks this packet as not needing a response when sent to the client
*/
public MessageBuilder<MSG> noResponse()
{
this.needsResponse = false;
return this;
}
/**
* Set the message consumer, which is called once a message has been decoded. This accepts the decoded message
* object and the message's context.
* <p>
* The consumer is called on the network thread, and so should not interact with most game state by default.
* {@link NetworkEvent.Context#enqueueWork(Runnable)} can be used to handle the message on the main server or
* client thread. Alternatively one can use {@link #consumerMainThread(BiConsumer)} to run the handler on the
* main thread.
*
* @param consumer The message consumer.
* @return The message builder, for chaining.
* @see #consumerMainThread(BiConsumer)
*/
public MessageBuilder<MSG> consumerNetworkThread(BiConsumer<MSG, Supplier<NetworkEvent.Context>> consumer) {
this.consumer = consumer;
return this;
}
/**
* Set the message consumer, which is called once a message has been decoded. This accepts the decoded message
* object and the message's context.
* <p>
* Unlike {@link #consumerNetworkThread(BiConsumer)}, the consumer is called on the main thread, and so can
* interact with most game state by default.
*
* @param consumer The message consumer.
* @return The message builder, for chaining.
* @see #consumerNetworkThread(BiConsumer)
*/
public MessageBuilder<MSG> consumerMainThread(BiConsumer<MSG, Supplier<NetworkEvent.Context>> consumer) {
this.consumer = (msg, context) -> {
var ctx = context.get();
ctx.enqueueWork(() -> consumer.accept(msg, context));
ctx.setPacketHandled(true);
};
return this;
}
public interface ToBooleanBiFunction<T, U> {
boolean applyAsBool(T first, U second);
}
/**
* Function returning a boolean "packet handled" indication, for simpler channel building.
* @param handler a handler
* @return this
* @see #consumerNetworkThread(BiConsumer)
*/
public MessageBuilder<MSG> consumerNetworkThread(ToBooleanBiFunction<MSG, Supplier<NetworkEvent.Context>> handler) {
this.consumer = (msg, ctx) -> {
boolean handled = handler.applyAsBool(msg, ctx);
ctx.get().setPacketHandled(handled);
};
return this;
}
public void add() {
final IndexedMessageCodec.MessageHandler<MSG> message = this.channel.registerMessage(this.id, this.type, this.encoder, this.decoder, this.consumer, this.networkDirection);
if (this.loginIndexSetter != null) {
message.setLoginIndexSetter(this.loginIndexSetter);
}
if (this.loginIndexGetter != null) {
if (!IntSupplier.class.isAssignableFrom(this.type)) {
throw new IllegalArgumentException("Login packet type that does not supply an index as an IntSupplier");
}
message.setLoginIndexGetter(this.loginIndexGetter);
}
if (this.loginPacketGenerators != null) {
this.channel.loginPackets.add(this.loginPacketGenerators);
}
this.channel.packetsNeedResponse.put(this.type, this.needsResponse);
}
}
}
@@ -0,0 +1,39 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.tasks;
import java.util.function.Consumer;
import org.jetbrains.annotations.ApiStatus;
import net.minecraft.network.protocol.Packet;
import net.minecraft.server.network.ConfigurationTask;
import net.minecraftforge.network.NetworkInitialization;
import net.minecraftforge.network.config.ConfigurationTaskContext;
import net.minecraftforge.network.packets.ChannelVersions;
/**
* Sends the list of known channels to the client as well as their specific versions.
* Allows the client to do compatibility checking.
*/
@ApiStatus.Internal
public class ChannelVersionsTask implements ConfigurationTask {
public static final Type TYPE = new Type("forge:channel_list");
@Override
public void start(ConfigurationTaskContext ctx) {
NetworkInitialization.PLAY.send(new ChannelVersions(), ctx.getConnection());
}
@Override
public void start(Consumer<Packet<?>> send) {
throw new IllegalStateException("This should never be called");
}
@Override
public Type type() {
return TYPE;
}
}
@@ -0,0 +1,36 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.tasks;
import org.jetbrains.annotations.ApiStatus;
import net.minecraftforge.event.network.GatherLoginConfigurationTasksEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.network.ConnectionType;
import net.minecraftforge.network.NetworkContext;
@ApiStatus.Internal
public class ForgeNetworkConfigurationHandler {
@SubscribeEvent
public void gatherInit(GatherLoginConfigurationTasksEvent event) {
var ctx = NetworkContext.get(event.getConnection());
if (ctx.getType() != ConnectionType.MODDED)
return;
// Send minecraft:register packet for all known channels. This allows the other side to know what we can talk about.
event.addTask(new RegisterChannelsTask());
// Send the mod version and display name to the client so that it can check for compatibility, Currently doesn't really do anything
// We expect a response from the client
event.addTask(new ModVersionsTask());
// Send the channel list to the client, which is checked on the client to make sure it knows how to talk to the server.
// We expect a Response from the client
event.addTask(new ChannelVersionsTask());
// Sync all of our registry mappings
event.addTask(new SyncRegistriesTask());
// Lastly sync raw mod config files. We send raw file bytes, which is very inefficient, but we can change it later. //TODO: Compress/Optimize config file data
event.addTask(new SyncConfigTask());
}
}
@@ -0,0 +1,40 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.tasks;
import java.util.function.Consumer;
import org.jetbrains.annotations.ApiStatus;
import net.minecraft.network.protocol.Packet;
import net.minecraft.server.network.ConfigurationTask;
import net.minecraftforge.network.NetworkInitialization;
import net.minecraftforge.network.config.ConfigurationTaskContext;
import net.minecraftforge.network.packets.ModVersions;
/**
* Sends the list of known channels to the client using the
* <a href="https://web.archive.org/web/20220711204310/https://dinnerbone.com/blog/2012/01/13/minecraft-plugin-channels-messaging/">Plugin Channel</a>
* register messages.
*/
@ApiStatus.Internal
public class ModVersionsTask implements ConfigurationTask {
public static final Type TYPE = new Type("forge:channel_list");
@Override
public void start(ConfigurationTaskContext ctx) {
NetworkInitialization.PLAY.send(ModVersions.create(), ctx.getConnection());
}
@Override
public void start(Consumer<Packet<?>> send) {
throw new IllegalStateException("This should never be called");
}
@Override
public Type type() {
return TYPE;
}
}
@@ -0,0 +1,41 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.tasks;
import java.util.function.Consumer;
import org.jetbrains.annotations.ApiStatus;
import net.minecraft.network.protocol.Packet;
import net.minecraft.server.network.ConfigurationTask;
import net.minecraftforge.network.ChannelListManager;
import net.minecraftforge.network.config.ConfigurationTaskContext;
/**
* Sends the list of known channels to the client using the
* <a href="https://web.archive.org/web/20220711204310/https://dinnerbone.com/blog/2012/01/13/minecraft-plugin-channels-messaging/">Plugin Channel</a>
* register messages.
*/
@ApiStatus.Internal
class RegisterChannelsTask implements ConfigurationTask {
private static final Type TYPE = new Type("forge:send_vanilla_channel_list");
@Override
public void start(ConfigurationTaskContext ctx) {
ChannelListManager.addChannels(ctx.getConnection());
ctx.finish(type());
}
@Override
public void start(Consumer<Packet<?>> send) {
throw new IllegalStateException("This should never be called");
}
@Override
public Type type() {
return TYPE;
}
}
@@ -0,0 +1,45 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.tasks;
import java.io.IOException;
import java.nio.file.Files;
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 org.jetbrains.annotations.ApiStatus;
import net.minecraft.network.chat.Component;
import net.minecraftforge.fml.config.ConfigTracker;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.network.NetworkInitialization;
import net.minecraftforge.network.config.ConfigurationTaskContext;
import net.minecraftforge.network.config.SimpleConfigurationTask;
import net.minecraftforge.network.packets.ConfigData;
@ApiStatus.Internal
class SyncConfigTask extends SimpleConfigurationTask {
static final Type TYPE = new Type("forge:sync_configs");
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker MARKER = MarkerManager.getMarker("FORGE_SYNC_CONFIG");
SyncConfigTask() {
super(TYPE, SyncConfigTask::run);
}
private static void run(ConfigurationTaskContext ctx) {
for (var cfg : ConfigTracker.INSTANCE.configSets().get(ModConfig.Type.SERVER)) {
try {
var pkt = new ConfigData(cfg.getFileName(), Files.readAllBytes(cfg.getFullPath()));
NetworkInitialization.PLAY.send(pkt, ctx.getConnection());
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to read config file {} terminating connection", cfg.getFileName(), e);
ctx.getConnection().disconnect(Component.literal("Connection closed - Failed to read config on server"));
}
}
}
}
@@ -0,0 +1,94 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.network.tasks;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
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 org.jetbrains.annotations.ApiStatus;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.Packet;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.network.ConfigurationTask;
import net.minecraftforge.event.network.CustomPayloadEvent;
import net.minecraftforge.network.ForgePacketHandler;
import net.minecraftforge.network.NetworkInitialization;
import net.minecraftforge.network.config.ConfigurationTaskContext;
import net.minecraftforge.network.packets.Acknowledge;
import net.minecraftforge.network.packets.RegistryData;
import net.minecraftforge.network.packets.RegistryList;
import net.minecraftforge.registries.ForgeRegistry.Snapshot;
import net.minecraftforge.registries.RegistryManager;
/**
* Sends the list of known channels to the client as well as their specific versions.
* Allows the client to do compatibility checking.
*/
@ApiStatus.Internal
public class SyncRegistriesTask implements ConfigurationTask {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker MARKER = MarkerManager.getMarker("SYNC_REGISTRIES_TASK");
public static final Type TYPE = new Type("forge:sync_registries");
private ConfigurationTaskContext taskCtx;
private Map<ResourceLocation, Snapshot> snapshot;
private ForgePacketHandler handler;
private int expectedToken;
@Override
public void start(ConfigurationTaskContext ctx) {
this.taskCtx = ctx;
var con = ctx.getConnection();
handler = con.channel().attr(NetworkInitialization.CONTEXT).get();
// If we're in memory, then don't actually sync the registries.
if (!ctx.getConnection().isMemoryConnection())
this.snapshot = RegistryManager.ACTIVE.takeSnapshot(false);
expectedToken = handler.expectAck(this::sendRegistries);
NetworkInitialization.PLAY.send(new RegistryList(expectedToken), con);
}
private void sendRegistries(Acknowledge msg, CustomPayloadEvent.Context ctx) {
if (msg.token() != expectedToken) {
LOGGER.error(MARKER, "Received unknown acknowledgement received {} exptected {}", msg.token(), expectedToken);
ctx.getConnection().disconnect(Component.literal("Illegal Acknowledge packet received, unknown token: " + msg.token()));
return;
}
// We've got no more to send, so finish this task!
if (this.snapshot == null || this.snapshot.isEmpty()) {
taskCtx.finish(type());
return;
}
// Send the next registry!
var name = this.snapshot.keySet().iterator().next();
var data = this.snapshot.remove(name);
expectedToken = this.handler.expectAck(this::sendRegistries);
NetworkInitialization.PLAY.reply(new RegistryData(expectedToken, name, data), ctx);
}
@Override
public void start(Consumer<Packet<?>> send) {
throw new IllegalStateException("This should never be called");
}
@Override
public Type type() {
return TYPE;
}
}
@@ -14,7 +14,6 @@ import org.jetbrains.annotations.ApiStatus;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
@@ -23,8 +22,7 @@ import java.util.Set;
import java.util.stream.Stream;
@ApiStatus.Internal
public final class DataPackRegistriesHooks
{
public final class DataPackRegistriesHooks {
private DataPackRegistriesHooks() {} // utility class
private static final Map<ResourceKey<? extends Registry<?>>, RegistrySynchronization.NetworkedRegistryData<?>> NETWORKABLE_REGISTRIES = new LinkedHashMap<>();
@@ -34,8 +32,7 @@ public final class DataPackRegistriesHooks
private static final Set<ResourceKey<? extends Registry<?>>> SYNCED_CUSTOM_REGISTRIES_VIEW = Collections.unmodifiableSet(SYNCED_CUSTOM_REGISTRIES);
/* Internal forge hook for retaining mutable access to RegistryAccess's codec registry when it bootstraps. */
public static Map<ResourceKey<? extends Registry<?>>, RegistrySynchronization.NetworkedRegistryData<?>> grabNetworkableRegistries(ImmutableMap.Builder<ResourceKey<? extends Registry<?>>, RegistrySynchronization.NetworkedRegistryData<?>> builder)
{
public static Map<ResourceKey<? extends Registry<?>>, RegistrySynchronization.NetworkedRegistryData<?>> grabNetworkableRegistries(ImmutableMap.Builder<ResourceKey<? extends Registry<?>>, RegistrySynchronization.NetworkedRegistryData<?>> builder) {
if (!StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass().equals(RegistrySynchronization.class))
throw new IllegalCallerException("Attempted to call DataPackRegistriesHooks#grabNetworkableRegistries!");
NETWORKABLE_REGISTRIES.forEach(builder::put);
@@ -45,12 +42,10 @@ public final class DataPackRegistriesHooks
}
/* Internal forge method, registers a datapack registry codec and folder. */
static <T> void addRegistryCodec(DataPackRegistryEvent.DataPackRegistryData<T> data)
{
static <T> void addRegistryCodec(DataPackRegistryEvent.DataPackRegistryData<T> data) {
RegistryDataLoader.RegistryData<T> loaderData = data.loaderData();
DATA_PACK_REGISTRIES.add(loaderData);
if (data.networkCodec() != null)
{
if (data.networkCodec() != null) {
SYNCED_CUSTOM_REGISTRIES.add(loaderData.key());
NETWORKABLE_REGISTRIES.put(loaderData.key(), new RegistrySynchronization.NetworkedRegistryData<>(loaderData.key(), data.networkCodec()));
}
@@ -60,8 +55,7 @@ public final class DataPackRegistriesHooks
* {@return An unmodifiable view of the list of datapack registries}.
* These registries are loaded from per-world datapacks on server startup.
*/
public static List<RegistryDataLoader.RegistryData<?>> getDataPackRegistries()
{
public static List<RegistryDataLoader.RegistryData<?>> getDataPackRegistries() {
return DATA_PACK_REGISTRIES_VIEW;
}
@@ -74,8 +68,7 @@ public final class DataPackRegistriesHooks
* Clients must have each of a server's synced datapack registries to be able to connect to that server;
* vanilla clients therefore cannot connect if this list is non-empty on the server.
*/
public static Set<ResourceKey<? extends Registry<?>>> getSyncedCustomRegistries()
{
public static Set<ResourceKey<? extends Registry<?>>> getSyncedCustomRegistries() {
return SYNCED_CUSTOM_REGISTRIES_VIEW;
}
}
@@ -946,8 +946,7 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
}
}
public static class Snapshot
{
public static class Snapshot {
private static final Comparator<ResourceLocation> sorter = (a,b) -> a.compareNamespaced(b);
public final Map<ResourceLocation, Integer> ids = Maps.newTreeMap(sorter);
public final Map<ResourceLocation, ResourceLocation> aliases = Maps.newTreeMap(sorter);
@@ -955,13 +954,11 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
public final Map<ResourceLocation, String> overrides = Maps.newTreeMap(sorter);
private FriendlyByteBuf binary = null;
public CompoundTag write()
{
public CompoundTag write() {
CompoundTag data = new CompoundTag();
ListTag ids = new ListTag();
this.ids.entrySet().stream().forEach(e ->
{
this.ids.entrySet().stream().forEach(e -> {
CompoundTag tag = new CompoundTag();
tag.putString("K", e.getKey().toString());
tag.putInt("V", e.getValue());
@@ -970,8 +967,7 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
data.put("ids", ids);
ListTag aliases = new ListTag();
this.aliases.entrySet().stream().forEach(e ->
{
this.aliases.entrySet().stream().forEach(e -> {
CompoundTag tag = new CompoundTag();
tag.putString("K", e.getKey().toString());
tag.putString("V", e.getValue().toString());
@@ -980,8 +976,7 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
data.put("aliases", aliases);
ListTag overrides = new ListTag();
this.overrides.entrySet().stream().forEach(e ->
{
this.overrides.entrySet().stream().forEach(e -> {
CompoundTag tag = new CompoundTag();
tag.putString("K", e.getKey().toString());
tag.putString("V", e.getValue());
@@ -995,99 +990,58 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
return data;
}
public static Snapshot read(CompoundTag nbt)
{
public static Snapshot read(CompoundTag nbt) {
Snapshot ret = new Snapshot();
if (nbt == null)
{
return ret;
}
ListTag list = nbt.getList("ids", 10);
list.forEach(e ->
{
list.forEach(e -> {
CompoundTag comp = (CompoundTag)e;
ret.ids.put(new ResourceLocation(comp.getString("K")), comp.getInt("V"));
});
list = nbt.getList("aliases", 10);
list.forEach(e ->
{
list.forEach(e -> {
CompoundTag comp = (CompoundTag)e;
ret.aliases.put(new ResourceLocation(comp.getString("K")), new ResourceLocation(comp.getString("V")));
});
list = nbt.getList("overrides", 10);
list.forEach(e ->
{
list.forEach(e -> {
CompoundTag comp = (CompoundTag)e;
ret.overrides.put(new ResourceLocation(comp.getString("K")), comp.getString("V"));
});
int[] blocked = nbt.getIntArray("blocked");
for (int i : blocked)
{
ret.blocked.add(i);
}
return ret;
}
public synchronized FriendlyByteBuf getPacketData()
{
public synchronized FriendlyByteBuf getPacketData() {
if (binary == null) {
FriendlyByteBuf pkt = new FriendlyByteBuf(Unpooled.buffer());
pkt.writeVarInt(this.ids.size());
this.ids.forEach((k,v) -> {
pkt.writeResourceLocation(k);
pkt.writeVarInt(v);
});
pkt.writeVarInt(this.aliases.size());
this.aliases.forEach((k, v) -> {
pkt.writeResourceLocation(k);
pkt.writeResourceLocation(v);
});
pkt.writeVarInt(this.overrides.size());
this.overrides.forEach((k, v) -> {
pkt.writeResourceLocation(k);
pkt.writeUtf(v, 0x100);
});
pkt.writeVarInt(this.blocked.size());
this.blocked.forEach(pkt::writeVarInt);
pkt.writeMap(this.ids, FriendlyByteBuf::writeResourceLocation, FriendlyByteBuf::writeVarInt);
pkt.writeMap(this.aliases, FriendlyByteBuf::writeResourceLocation, FriendlyByteBuf::writeResourceLocation);
pkt.writeMap(this.overrides, FriendlyByteBuf::writeResourceLocation, (b,v) -> b.writeUtf(v, 0x100));
pkt.writeCollection(this.blocked, FriendlyByteBuf::writeVarInt);
this.binary = pkt;
}
return new FriendlyByteBuf(binary.slice());
}
public static Snapshot read(FriendlyByteBuf buff)
{
if (buff == null)
public static Snapshot read(FriendlyByteBuf buf) {
if (buf == null)
return new Snapshot();
Snapshot ret = new Snapshot();
int len = buff.readVarInt();
for (int x = 0; x < len; x++)
ret.ids.put(buff.readResourceLocation(), buff.readVarInt());
len = buff.readVarInt();
for (int x = 0; x < len; x++)
ret.aliases.put(buff.readResourceLocation(), buff.readResourceLocation());
len = buff.readVarInt();
for (int x = 0; x < len; x++)
ret.overrides.put(buff.readResourceLocation(), buff.readUtf(0x100));
len = buff.readVarInt();
for (int x = 0; x < len; x++)
ret.blocked.add(buff.readVarInt());
var ret = new Snapshot();
ret.ids.putAll(buf.readMap(FriendlyByteBuf::readResourceLocation, FriendlyByteBuf::readVarInt));
ret.aliases.putAll(buf.readMap(FriendlyByteBuf::readResourceLocation, FriendlyByteBuf::readResourceLocation));
ret.overrides.putAll(buf.readMap(FriendlyByteBuf::readResourceLocation, b -> b.readUtf(0x100)));
ret.blocked.addAll(buf.readList(FriendlyByteBuf::readVarInt));
return ret;
}
}
@@ -10,11 +10,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.mojang.serialization.Lifecycle;
@@ -24,14 +21,12 @@ import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.core.Registry;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.network.HandshakeMessages;
import net.minecraftforge.registries.ForgeRegistry.Snapshot;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.ApiStatus;
public class RegistryManager
{
public class RegistryManager {
private static final Logger LOGGER = LogManager.getLogger();
public static final RegistryManager ACTIVE = new RegistryManager("ACTIVE");
public static final RegistryManager VANILLA = new RegistryManager("VANILLA");
@@ -39,65 +34,61 @@ public class RegistryManager
private static Set<ResourceLocation> vanillaRegistryKeys = Set.of();
BiMap<ResourceLocation, ForgeRegistry<?>> registries = HashBiMap.create();
private Map<ResourceLocation, ? extends IForgeRegistry<?>> registryView = Collections.unmodifiableMap(registries);
private Set<ResourceLocation> persisted = Sets.newHashSet();
private Set<ResourceLocation> synced = Sets.newHashSet();
private Map<ResourceLocation, ResourceLocation> legacyNames = new HashMap<>();
private final String name;
RegistryManager()
{
RegistryManager() {
this("STAGING");
}
public RegistryManager(String name)
{
public RegistryManager(String name) {
this.name = name;
}
public String getName()
{
public String getName() {
return this.name;
}
boolean isStaging()
{
boolean isStaging() {
return "STAGING".equals(this.name);
}
@SuppressWarnings("unchecked")
public <V> ForgeRegistry<V> getRegistry(ResourceLocation key)
{
public <V> ForgeRegistry<V> getRegistry(ResourceLocation key) {
return (ForgeRegistry<V>)this.registries.get(key);
}
public <V> ForgeRegistry<V> getRegistry(ResourceKey<? extends Registry<V>> key)
{
public <V> ForgeRegistry<V> getRegistry(ResourceKey<? extends Registry<V>> key) {
return getRegistry(key.location());
}
public <V> ResourceLocation getName(IForgeRegistry<V> reg)
{
public <V> ResourceLocation getName(IForgeRegistry<V> reg) {
return this.registries.inverse().get(reg);
}
public <V> ResourceLocation updateLegacyName(ResourceLocation legacyName)
{
public Map<ResourceLocation, ? extends IForgeRegistry<?>> getRegistries() {
return this.registryView;
}
public static Set<ResourceLocation> getVanillaRegistryKeys() {
return vanillaRegistryKeys;
}
public <V> ResourceLocation updateLegacyName(ResourceLocation legacyName) {
ResourceLocation originalName = legacyName;
while (getRegistry(legacyName) == null)
{
while (getRegistry(legacyName) == null) {
legacyName = legacyNames.get(legacyName);
if (legacyName == null)
{
return originalName;
}
}
return legacyName;
}
public <V> ForgeRegistry<V> getRegistry(ResourceLocation key, RegistryManager other)
{
if (!this.registries.containsKey(key))
{
public <V> ForgeRegistry<V> getRegistry(ResourceLocation key, RegistryManager other) {
if (!this.registries.containsKey(key)) {
ForgeRegistry<V> ot = other.getRegistry(key);
if (ot == null)
return null;
@@ -113,8 +104,7 @@ public class RegistryManager
return getRegistry(key);
}
<V> ForgeRegistry<V> createRegistry(ResourceLocation name, RegistryBuilder<V> builder)
{
<V> ForgeRegistry<V> createRegistry(ResourceLocation name, RegistryBuilder<V> builder) {
if (registries.containsKey(name))
throw new IllegalArgumentException("Attempted to register a registry for " + name + " but it already exists");
ForgeRegistry<V> reg = new ForgeRegistry<V>(this, name, builder);
@@ -128,22 +118,19 @@ public class RegistryManager
return getRegistry(name);
}
static <V> void registerToRootRegistry(ForgeRegistry<V> forgeReg)
{
static <V> void registerToRootRegistry(ForgeRegistry<V> forgeReg) {
injectForgeRegistry(forgeReg, BuiltInRegistries.REGISTRY);
}
@SuppressWarnings("unchecked")
private static <V> void injectForgeRegistry(ForgeRegistry<V> forgeReg, Registry<? extends Registry<?>> rootRegistry)
{
private static <V> void injectForgeRegistry(ForgeRegistry<V> forgeReg, Registry<? extends Registry<?>> rootRegistry) {
WritableRegistry<Registry<V>> registry = (WritableRegistry<Registry<V>>) rootRegistry;
Registry<V> wrapper = forgeReg.getWrapper();
if (wrapper != null)
registry.register(forgeReg.getRegistryKey(), wrapper, Lifecycle.experimental());
}
public static void postNewRegistryEvent()
{
public static void postNewRegistryEvent() {
NewRegistryEvent event = new NewRegistryEvent();
DataPackRegistryEvent.NewRegistry dataPackEvent = new DataPackRegistryEvent.NewRegistry();
vanillaRegistryKeys = Set.copyOf(BuiltInRegistries.REGISTRY.keySet());
@@ -155,61 +142,29 @@ public class RegistryManager
dataPackEvent.process();
}
private void addLegacyName(ResourceLocation legacyName, ResourceLocation name)
{
private void addLegacyName(ResourceLocation legacyName, ResourceLocation name) {
if (this.legacyNames.containsKey(legacyName))
{
throw new IllegalArgumentException("Legacy name conflict for registry " + name + ", upgrade path must be linear: " + legacyName);
}
this.legacyNames.put(legacyName, name);
}
private void findSuperTypes(Class<?> type, Set<Class<?>> types)
{
if (type == null || type == Object.class)
{
return;
}
types.add(type);
for (Class<?> interfac : type.getInterfaces())
{
findSuperTypes(interfac, types);
}
findSuperTypes(type.getSuperclass(), types);
}
public Map<ResourceLocation, Snapshot> takeSnapshot(boolean savingToDisc)
{
Map<ResourceLocation, Snapshot> ret = Maps.newHashMap();
Set<ResourceLocation> keys = savingToDisc ? this.persisted : this.synced;
public Map<ResourceLocation, Snapshot> takeSnapshot(boolean savingToDisc) {
Map<ResourceLocation, Snapshot> ret = new HashMap<>();
var keys = savingToDisc ? this.persisted : this.synced;
keys.forEach(name -> ret.put(name, getRegistry(name).makeSnapshot()));
return ret;
}
//Public for testing only
public void clean()
{
@ApiStatus.Internal
public void clean() {
this.persisted.clear();
this.synced.clear();
this.registries.clear();
}
public static List<Pair<String, HandshakeMessages.S2CRegistry>> generateRegistryPackets(boolean isLocal)
{
return !isLocal ? ACTIVE.takeSnapshot(false).entrySet().stream().
map(e->Pair.of("Registry " + e.getKey(), new HandshakeMessages.S2CRegistry(e.getKey(), e.getValue()))).
collect(Collectors.toList()) : Collections.emptyList();
}
public static List<ResourceLocation> getRegistryNamesForSyncToClient()
{
return ACTIVE.registries.keySet().stream().
filter(resloc -> ACTIVE.synced.contains(resloc)).
collect(Collectors.toList());
}
public static Set<ResourceLocation> getVanillaRegistryKeys()
{
return vanillaRegistryKeys;
@ApiStatus.Internal
public static List<ResourceLocation> getRegistryNamesForSyncToClient() {
return ACTIVE.registries.keySet().stream().filter(ACTIVE.synced::contains).toList();
}
}
@@ -20,8 +20,13 @@ import net.minecraft.core.Holder;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
import net.minecraft.gametest.framework.GameTestServer;
import net.minecraft.network.Connection;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.protocol.handshake.ClientIntent;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket;
import net.minecraft.server.packs.PackResources;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.PackSource;
@@ -35,11 +40,10 @@ import net.minecraftforge.common.world.BiomeModifier;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.fml.ModLoadingStage;
import net.minecraftforge.fml.ModLoadingWarning;
import net.minecraftforge.network.ConnectionType;
import net.minecraftforge.network.NetworkConstants;
import net.minecraftforge.network.NetworkHooks;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.network.ConnectionType;
import net.minecraftforge.network.NetworkContext;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.registries.ForgeRegistries.Keys;
import net.minecraftforge.resource.PathPackResources;
import net.minecraftforge.server.permission.PermissionAPI;
@@ -48,10 +52,6 @@ import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import net.minecraft.network.Connection;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket;
import net.minecraft.server.packs.repository.Pack;
import net.minecraft.server.packs.repository.Pack.Info;
import net.minecraft.server.MinecraftServer;
@@ -69,16 +69,17 @@ import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.GameData;
import org.jetbrains.annotations.ApiStatus;
public class ServerLifecycleHooks
{
@SuppressWarnings("deprecation")
@ApiStatus.Internal
public class ServerLifecycleHooks {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker SERVERHOOKS = MarkerManager.getMarker("SERVERHOOKS");
private static final LevelResource SERVERCONFIG = new LevelResource("serverconfig");
private static final AtomicBoolean allowLogins = new AtomicBoolean(false);
private static volatile CountDownLatch exitLatch = null;
private static MinecraftServer currentServer;
private static Path getServerConfigPath(final MinecraftServer server)
{
private static Path getServerConfigPath(final MinecraftServer server) {
final Path serverConfig = server.getWorldPath(SERVERCONFIG);
if (!Files.isDirectory(serverConfig)) {
try {
@@ -90,8 +91,7 @@ public class ServerLifecycleHooks
return serverConfig;
}
public static boolean handleServerAboutToStart(final MinecraftServer server)
{
public static boolean handleServerAboutToStart(final MinecraftServer server) {
currentServer = server;
// on the dedi server we need to force the stuff to setup properly
LogicalSidedProvider.setServer(()->server);
@@ -100,8 +100,7 @@ public class ServerLifecycleHooks
return !MinecraftForge.EVENT_BUS.post(new ServerAboutToStartEvent(server));
}
public static boolean handleServerStarting(final MinecraftServer server)
{
public static boolean handleServerStarting(final MinecraftServer server) {
DistExecutor.runWhenOn(Dist.DEDICATED_SERVER, ()->()->{
LanguageHook.loadLanguagesOnServer(server);
// GameTestServer requires the gametests to be registered earlier, so it is done in main and should not be done twice.
@@ -112,90 +111,28 @@ public class ServerLifecycleHooks
return !MinecraftForge.EVENT_BUS.post(new ServerStartingEvent(server));
}
public static void handleServerStarted(final MinecraftServer server)
{
MinecraftForge.EVENT_BUS.post(new ServerStartedEvent(server));
allowLogins.set(true);
}
public static void handleServerStopping(final MinecraftServer server)
{
allowLogins.set(false);
MinecraftForge.EVENT_BUS.post(new ServerStoppingEvent(server));
}
public static void expectServerStopped()
{
public static void expectServerStopped() {
exitLatch = new CountDownLatch(1);
}
public static void handleServerStopped(final MinecraftServer server)
{
public static void handleServerStopped(final MinecraftServer server) {
if (!server.isDedicatedServer()) GameData.revertToFrozen();
MinecraftForge.EVENT_BUS.post(new ServerStoppedEvent(server));
currentServer = null;
LogicalSidedProvider.setServer(null);
CountDownLatch latch = exitLatch;
if (latch != null)
{
if (latch != null) {
latch.countDown();
exitLatch = null;
}
ConfigTracker.INSTANCE.unloadConfigs(ModConfig.Type.SERVER, getServerConfigPath(server));
}
public static MinecraftServer getCurrentServer()
{
public static MinecraftServer getCurrentServer() {
return currentServer;
}
private static AtomicBoolean allowLogins = new AtomicBoolean(false);
public static boolean handleServerLogin(final ClientIntentionPacket packet, final Connection manager) {
if (!allowLogins.get())
{
MutableComponent text = Component.literal("Server is still starting! Please wait before reconnecting.");
LOGGER.info(SERVERHOOKS,"Disconnecting Player (server is still starting): {}", text.getContents());
manager.send(new ClientboundLoginDisconnectPacket(text));
manager.disconnect(text);
return false;
}
if (packet.nextProtocol() == ConnectionProtocol.LOGIN) {
var fmlVersion = NetworkHooks.getFMLVersion(packet.hostName());
final ConnectionType connectionType = ConnectionType.forVersionFlag(fmlVersion);
final int versionNumber = connectionType.getFMLVersionNumber(fmlVersion);
if (connectionType == ConnectionType.MODDED && versionNumber != NetworkConstants.FMLNETVERSION) {
rejectConnection(manager, connectionType, "This modded server is not impl compatible with your modded client. Please verify your Forge version closely matches the server. Got net version " + versionNumber + " this server is net version " + NetworkConstants.FMLNETVERSION);
return false;
}
if (connectionType == ConnectionType.VANILLA && !NetworkRegistry.acceptsVanillaClientConnections()) {
rejectConnection(manager, connectionType, "This server has mods that require Forge to be installed on the client. Contact your server admin for more details.");
return false;
}
}
if (packet.nextProtocol() == ConnectionProtocol.STATUS) return true;
NetworkHooks.registerServerLoginChannel(manager, packet);
return true;
}
private static void rejectConnection(final Connection manager, ConnectionType type, String message) {
//manager.setProtocol(ConnectionProtocol.LOGIN); Pretty sure things auto swap in ProtocolSwapHandler
LOGGER.info(SERVERHOOKS, "[{}] Disconnecting {} connection attempt: {}", manager.getLoggableAddress(true), type, message); // TODO: Respect logIP setting
MutableComponent text = Component.literal(message);
manager.send(new ClientboundLoginDisconnectPacket(text));
manager.disconnect(text);
}
public static void handleExit(int retVal)
{
System.exit(retVal);
}
@ApiStatus.Internal
public static RepositorySource buildPackFinder(Map<IModFile, ? extends PathPackResources> modResourcePacks) {
@@ -203,8 +140,7 @@ public class ServerLifecycleHooks
}
private static void serverPackFinder(Map<IModFile, ? extends PathPackResources> modResourcePacks, Consumer<Pack> packAcceptor) {
for (Entry<IModFile, ? extends PathPackResources> e : modResourcePacks.entrySet())
{
for (Entry<IModFile, ? extends PathPackResources> e : modResourcePacks.entrySet()) {
IModInfo mod = e.getKey().getModInfos().get(0);
if (Objects.equals(mod.getModId(), "minecraft")) continue; // skip the minecraft "mod"
final String name = "mod:" + mod.getModId();
@@ -233,8 +169,7 @@ public class ServerLifecycleHooks
}
}
private static void runModifiers(final MinecraftServer server)
{
private static void runModifiers(final MinecraftServer server) {
final RegistryAccess registries = server.registryAccess();
// The order of holders() is the order modifiers were loaded in.
@@ -249,13 +184,57 @@ public class ServerLifecycleHooks
// Apply sorted biome modifiers to each biome.
registries.registryOrThrow(Registries.BIOME).holders().forEach(biomeHolder ->
{
biomeHolder.value().modifiableBiomeInfo().applyBiomeModifiers(biomeHolder, biomeModifiers);
});
biomeHolder.value().modifiableBiomeInfo().applyBiomeModifiers(biomeHolder, biomeModifiers)
);
// Apply sorted structure modifiers to each structure.
registries.registryOrThrow(Registries.STRUCTURE).holders().forEach(structureHolder ->
{
structureHolder.value().modifiableStructureInfo().applyStructureModifiers(structureHolder, structureModifiers);
});
structureHolder.value().modifiableStructureInfo().applyStructureModifiers(structureHolder, structureModifiers)
);
}
//==================================================================================================================================================================================
//==================================================================================================================================================================================
//==================================================================================================================================================================================
//==================================================================================================================================================================================
//==================================================================================================================================================================================
//==================================================================================================================================================================================
public static void handleServerStarted(final MinecraftServer server) {
MinecraftForge.EVENT_BUS.post(new ServerStartedEvent(server));
allowLogins.set(true);
}
public static void handleServerStopping(final MinecraftServer server) {
allowLogins.set(false);
MinecraftForge.EVENT_BUS.post(new ServerStoppingEvent(server));
}
public static boolean handleServerLogin(final ClientIntentionPacket packet, final Connection connection) {
var ctx = NetworkContext.get(connection);
ctx.processIntention(packet.hostName());
if (!allowLogins.get())
return rejectConnection(connection, ctx.getType(), "Server is still starting! Please wait before reconnecting.");
if (packet.nextProtocol() != ConnectionProtocol.LOGIN)
return true;
if (ctx.getType() == ConnectionType.MODDED && ctx.getNetVersion() != NetworkContext.NET_VERSION)
return rejectConnection(connection, ctx.getType(), "This modded server is not impl compatible with your modded client. Please verify your Forge version closely matches the server. Got net version " + ctx.getNetVersion() + " this server is net version " + NetworkContext.NET_VERSION);
if (ctx.getType() == ConnectionType.VANILLA && !NetworkRegistry.acceptsVanillaClientConnections())
return rejectConnection(connection, ctx.getType(), "This server has mods that require Forge to be installed on the client. Contact your server admin for more details.");
NetworkRegistry.onConnectionStart(connection);
return true;
}
private static boolean rejectConnection(final Connection connection, ConnectionType type, String message) {
connection.setClientboundProtocolAfterHandshake(ClientIntent.LOGIN);
LOGGER.info(SERVERHOOKS, "[{}] Disconnecting {} connection attempt: {}", connection.getLoggableAddress(true), type, message); // TODO: Respect logIP setting
var text = Component.literal(message);
connection.send(new ClientboundLoginDisconnectPacket(text));
connection.disconnect(text);
return false;
}
}
@@ -9,10 +9,9 @@ import net.minecraft.commands.CommandSource;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.locale.Language;
import net.minecraftforge.network.ConnectionType;
import net.minecraftforge.network.NetworkHooks;
import net.minecraftforge.network.NetworkContext;
import java.util.Locale;
public class TextComponentHelper {
@@ -29,10 +28,8 @@ public class TextComponentHelper {
}
private static boolean isVanillaClient(CommandSource sender) {
if (sender instanceof ServerPlayer playerMP) {
ServerGamePacketListenerImpl channel = playerMP.connection;
return NetworkHooks.getConnectionType(channel::getConnection) == ConnectionType.VANILLA;
}
if (sender instanceof ServerPlayer playerMP)
return NetworkContext.get(playerMP.connection.getConnection()).getType() == ConnectionType.VANILLA;
return false;
}
}