Update to 1.14.2

This commit is contained in:
LexManos authored and cpw committed 2019-06-07 16:50:47 -04:00
1 parent d3e8804dbf
commit a7df63e1a1
1010 files changed
+15254 -19520

No files matched your search

@@ -21,6 +21,16 @@ package net.minecraftforge.fml;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import net.minecraft.resources.IResourceManager;
import net.minecraftforge.resource.IResourceType;
import net.minecraftforge.resource.VanillaResourceType;
import net.minecraftforge.versions.forge.ForgeVersion;
import net.minecraftforge.versions.mcp.MCPVersion;
import net.minecraft.resources.IResourceManager;
import net.minecraftforge.resource.IResourceType;
@@ -39,7 +39,6 @@ import org.apache.logging.log4j.Logger;
import com.google.common.base.Function;
import com.google.common.base.Stopwatch;
import net.minecraft.util.IThreadListener;
import net.minecraftforge.forgespi.language.IModInfo;
/**
@@ -59,7 +58,7 @@ public class DeferredWorkQueue
{
public final IModInfo owner;
public final Runnable task;
TaskInfo(IModInfo owner, Runnable task) {
this.owner = owner;
this.task = task;
@@ -68,15 +67,15 @@ public class DeferredWorkQueue
/**
* {@link Runnable} except it allows throwing checked exceptions.
*
*
* Is to {@link Runnable} as {@link Callable} is to {@link Supplier}.
*/
@FunctionalInterface
public interface CheckedRunnable
public interface CheckedRunnable
{
void run() throws Exception;
}
private static final Logger LOGGER = LogManager.getLogger();
private static ThreadLocal<ModContainer> currentOwner = new ThreadLocal<>();
@@ -84,7 +83,7 @@ public class DeferredWorkQueue
private static final ConcurrentLinkedDeque<TaskInfo> taskQueue = new ConcurrentLinkedDeque<>();
private static final Executor deferredExecutor = r -> taskQueue.add(new TaskInfo(currentOwner.get().getModInfo(), r));
private static <T> Function<Throwable, T> handleException() {
final ModContainer owner = currentOwner.get();
return t -> {
@@ -103,7 +102,7 @@ public class DeferredWorkQueue
* <p>
* If the task has a result, use {@link #getLater(Supplier)} or
* {@link #getLaterChecked(Callable)}.
*
*
* @param workToEnqueue A {@link Runnable} to execute later, on the loading
* thread
* @return A {@link CompletableFuture} that completes at said time
@@ -123,7 +122,7 @@ public class DeferredWorkQueue
* <p>
* If the task has a result, use {@link #getLater(Supplier)} or
* {@link #getLaterChecked(Callable)}.
*
*
* @param workToEnqueue A {@link CheckedRunnable} to execute later, on the
* loading thread
* @return A {@link CompletableFuture} that completes at said time
@@ -147,7 +146,7 @@ public class DeferredWorkQueue
* <p>
* If the task does not have a result, use {@link #runLater(Runnable)} or
* {@link #runLaterChecked(CheckedRunnable)}.
*
*
* @param <T> The result type of the task
* @param workToEnqueue A {@link Supplier} to execute later, on the loading
* thread
@@ -168,7 +167,7 @@ public class DeferredWorkQueue
* <p>
* If the task does not have a result, use {@link #runLater(Runnable)} or
* {@link #runLaterChecked(CheckedRunnable)}.
*
*
* @param <T> The result type of the task
* @param workToEnqueue A {@link Supplier} to execute later, on the loading
* thread
@@ -183,7 +182,7 @@ public class DeferredWorkQueue
}
});
}
static void clear() {
taskQueue.clear();
}
@@ -19,21 +19,20 @@
package net.minecraftforge.fml;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.resources.IResourcePack;
import net.minecraftforge.fml.network.FMLPlayMessages;
import net.minecraftforge.fml.packs.ModFileResourcePack;
import org.apache.commons.lang3.tuple.Pair;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.resources.IResourcePack;
import net.minecraftforge.fml.packs.ModFileResourcePack;
public class ExtensionPoint<T>
{
public static final ExtensionPoint<BiFunction<Minecraft, GuiScreen, GuiScreen>> CONFIGGUIFACTORY = new ExtensionPoint<>();
public static final ExtensionPoint<BiFunction<Minecraft, Screen, Screen>> CONFIGGUIFACTORY = new ExtensionPoint<>();
public static final ExtensionPoint<BiFunction<Minecraft, ModFileResourcePack, IResourcePack>> RESOURCEPACK = new ExtensionPoint<>();
/**
* Compatibility display test for the mod.
@@ -44,12 +43,6 @@ public class ExtensionPoint<T>
*/
public static final ExtensionPoint<Pair<Supplier<String>, BiPredicate<String, Boolean>>> DISPLAYTEST = new ExtensionPoint<>();
/**
* Register with {@link ModLoadingContext#registerExtensionPoint(ExtensionPoint, Supplier)}
*/
public static final ExtensionPoint<Function<FMLPlayMessages.OpenContainer, GuiScreen>> GUIFACTORY = new ExtensionPoint<>();
private Class<T> type;
private ExtensionPoint() {
@@ -25,8 +25,8 @@ import java.util.Objects;
import java.util.Optional;
import com.google.common.collect.Multimap;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
@@ -56,39 +56,39 @@ public final class FMLWorldPersistenceHook implements WorldPersistenceHooks.Worl
}
@Override
public NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info)
public CompoundNBT getDataForWriting(SaveHandler handler, WorldInfo info)
{
NBTTagCompound fmlData = new NBTTagCompound();
NBTTagList modList = new NBTTagList();
CompoundNBT fmlData = new CompoundNBT();
ListNBT modList = new ListNBT();
ModList.get().getMods().forEach(mi->
{
final NBTTagCompound mod = new NBTTagCompound();
mod.setString("ModId", mi.getModId());
mod.setString("ModVersion", MavenVersionStringHelper.artifactVersionToString(mi.getVersion()));
final CompoundNBT mod = new CompoundNBT();
mod.putString("ModId", mi.getModId());
mod.putString("ModVersion", MavenVersionStringHelper.artifactVersionToString(mi.getVersion()));
modList.add(mod);
});
fmlData.setTag("LoadingModList", modList);
fmlData.func_218657_a("LoadingModList", modList);
NBTTagCompound registries = new NBTTagCompound();
fmlData.setTag("Registries", registries);
CompoundNBT registries = new CompoundNBT();
fmlData.func_218657_a("Registries", registries);
LOGGER.debug(WORLDPERSISTENCE,"Gathering id map for writing to world save {}", info.getWorldName());
for (Map.Entry<ResourceLocation, ForgeRegistry.Snapshot> e : RegistryManager.ACTIVE.takeSnapshot(true).entrySet())
{
registries.setTag(e.getKey().toString(), e.getValue().write());
registries.func_218657_a(e.getKey().toString(), e.getValue().write());
}
return fmlData;
}
@Override
public void readData(SaveHandler handler, WorldInfo info, NBTTagCompound tag)
public void readData(SaveHandler handler, WorldInfo info, CompoundNBT tag)
{
if (tag.hasKey("LoadingModList"))
if (tag.contains("LoadingModList"))
{
NBTTagList modList = tag.getList("LoadingModList", (byte)10);
ListNBT modList = tag.getList("LoadingModList", (byte)10);
for (int i = 0; i < modList.size(); i++)
{
NBTTagCompound mod = modList.getCompound(i);
CompoundNBT mod = modList.getCompound(i);
String modId = mod.getString("ModId");
if (Objects.equals("minecraft", modId)) {
continue;
@@ -109,15 +109,15 @@ public final class FMLWorldPersistenceHook implements WorldPersistenceHooks.Worl
Multimap<ResourceLocation, ResourceLocation> failedElements = null;
if (tag.hasKey("ModItemData") || tag.hasKey("ItemData")) // Pre 1.7
if (tag.contains("ModItemData") || tag.contains("ItemData")) // Pre 1.7
{
StartupQuery.notify("This save predates 1.7.10, it can no longer be loaded here. Please load in 1.7.10 or 1.8 first");
StartupQuery.abort();
}
else if (tag.hasKey("Registries")) // 1.8, genericed out the 'registries' list
else if (tag.contains("Registries")) // 1.8, genericed out the 'registries' list
{
Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot = new HashMap<>();
NBTTagCompound regs = tag.getCompound("Registries");
CompoundNBT regs = tag.getCompound("Registries");
for (String key : regs.keySet())
{
snapshot.put(new ResourceLocation(key), ForgeRegistry.Snapshot.read(regs.getCompound(key)));
@@ -64,7 +64,7 @@ public class StartupQuery {
public static void abort()
{
MinecraftServer server = ServerLifecycleHooks.getCurrentServer();
if (server != null) server.initiateShutdown();
if (server != null) server.initiateShutdown(false);
aborted = true; // to abort loading and go back to the main menu
throw new AbortedException(); // to halt the server
@@ -20,15 +20,15 @@
package net.minecraftforge.fml;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import java.util.List;
public class TextComponentMessageFormatHandler {
public static int handle(final TextComponentTranslation parent, final List<ITextComponent> children, final Object[] formatArgs, final String format) {
public static int handle(final TranslationTextComponent parent, final List<ITextComponent> children, final Object[] formatArgs, final String format) {
try {
TextComponentString component = new TextComponentString(ForgeI18n.parseFormat(format, formatArgs));
StringTextComponent component = new StringTextComponent(ForgeI18n.parseFormat(format, formatArgs));
component.getStyle().setParentStyle(parent.getStyle());
children.add(component);
return format.length();
@@ -29,6 +29,22 @@ import net.minecraftforge.versions.mcp.MCPVersion;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.maven.artifact.versioning.ComparableVersion;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@@ -19,7 +19,7 @@
package net.minecraftforge.fml;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
import net.minecraftforge.fml.common.thread.EffectiveSide;
@@ -35,12 +35,12 @@ public class WorldPersistenceHooks
worldPersistenceHooks.add(hook);
}
public static void handleWorldDataSave(final SaveHandler handler, final WorldInfo worldInfo, final NBTTagCompound tagCompound)
public static void handleWorldDataSave(final SaveHandler handler, final WorldInfo worldInfo, final CompoundNBT tagCompound)
{
worldPersistenceHooks.forEach(wac->tagCompound.setTag(wac.getModId(), wac.getDataForWriting(handler, worldInfo)));
worldPersistenceHooks.forEach(wac->tagCompound.func_218657_a(wac.getModId(), wac.getDataForWriting(handler, worldInfo)));
}
public static void handleWorldDataLoad(SaveHandler handler, WorldInfo worldInfo, NBTTagCompound tagCompound)
public static void handleWorldDataLoad(SaveHandler handler, WorldInfo worldInfo, CompoundNBT tagCompound)
{
if (EffectiveSide.get() == LogicalSide.SERVER)
{
@@ -70,7 +70,7 @@ public class WorldPersistenceHooks
public interface WorldPersistenceHook
{
String getModId();
NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info);
void readData(SaveHandler handler, WorldInfo info, NBTTagCompound tag);
CompoundNBT getDataForWriting(SaveHandler handler, WorldInfo info);
void readData(SaveHandler handler, WorldInfo info, CompoundNBT tag);
}
}
@@ -34,9 +34,9 @@ import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiMultiplayer;
import net.minecraft.client.gui.GuiWorldSelection;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.gui.screen.MultiplayerScreen;
import net.minecraft.client.gui.screen.WorldSelectionScreen;
import net.minecraftforge.fml.ExtensionPoint;
import net.minecraftforge.fml.ForgeI18n;
import net.minecraftforge.fml.ModList;
@@ -55,10 +55,10 @@ import com.google.common.base.Strings;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.ServerStatusResponse;
import net.minecraft.resources.AbstractResourcePack;
import net.minecraft.resources.ResourcePack;
import net.minecraft.resources.FallbackResourceManager;
import net.minecraft.resources.IResourcePack;
import net.minecraft.resources.SimpleReloadableResourceManager;
@@ -127,7 +127,7 @@ public class ClientHooks
}
public static void drawForgePingInfo(GuiMultiplayer gui, ServerData target, int x, int y, int width, int relativeMouseX, int relativeMouseY) {
public static void drawForgePingInfo(MultiplayerScreen gui, ServerData target, int x, int y, int width, int relativeMouseX, int relativeMouseY) {
int idx;
String tooltip;
if (target.forgeData == null)
@@ -162,7 +162,7 @@ public class ClientHooks
}
Minecraft.getInstance().getTextureManager().bindTexture(iconSheet);
Gui.drawModalRectWithCustomSizedTexture(x + width - 18, y + 10, 0, (float)idx, 16, 16, 256.0f, 256.0f);
AbstractGui.blit(x + width - 18, y + 10, 16, 16, 0, idx, 16, 16, 256, 256);
if(relativeMouseX > width - 15 && relativeMouseX < width && relativeMouseY > 10 && relativeMouseY < 26)
gui.setHoveringText(tooltip);
@@ -179,7 +179,7 @@ public class ClientHooks
return new File(Minecraft.getInstance().gameDir, "saves");
}
public static void tryLoadExistingWorld(GuiWorldSelection selectWorldGUI, WorldSummary comparator)
public static void tryLoadExistingWorld(WorldSelectionScreen selectWorldGUI, WorldSummary comparator)
{
try
{
@@ -196,7 +196,7 @@ public class ClientHooks
return Minecraft.getInstance().getConnection()!=null ? Minecraft.getInstance().getConnection().getNetworkManager() : null;
}
public static void handleClientWorldClosing(WorldClient world)
public static void handleClientWorldClosing(ClientWorld world)
{
NetworkManager client = getClientToServerNetworkManager();
// ONLY revert a non-local connection
@@ -268,9 +268,9 @@ public class ClientHooks
List<IModInfo> mods = modRP.getModFile().getModInfos();
logger.error(" mod(s) {} resources at {}", mods.stream().map(IModInfo::getDisplayName).collect(Collectors.toList()), modRP.getModFile().getFilePath());
}
else if (resPack instanceof AbstractResourcePack)
else if (resPack instanceof ResourcePack)
{
logger.error(" resource pack at path {}", ((AbstractResourcePack)resPack).file.getPath());
logger.error(" resource pack at path {}", ((ResourcePack)resPack).file.getPath());
}
else
{
@@ -20,9 +20,8 @@
package net.minecraftforge.fml.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.DownloadingPackFinder;
import net.minecraft.client.resources.ResourcePackInfoClient;
import net.minecraft.client.resources.ClientResourcePackInfo;
import net.minecraft.resources.IReloadableResourceManager;
import net.minecraft.resources.ResourcePackList;
import net.minecraftforge.api.distmarker.Dist;
@@ -40,6 +39,8 @@ import net.minecraftforge.fml.packs.ResourcePackLoader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mojang.blaze3d.platform.GlStateManager;
import java.util.Collections;
import java.util.List;
@@ -53,7 +54,7 @@ public class ClientModLoader
private static Minecraft mc;
private static LoadingFailedException error;
public static void begin(final Minecraft minecraft, final ResourcePackList<ResourcePackInfoClient> defaultResourcePacks, final IReloadableResourceManager mcResourceManager, DownloadingPackFinder metadataSerializer)
public static void begin(final Minecraft minecraft, final ResourcePackList<ClientResourcePackInfo> defaultResourcePacks, final IReloadableResourceManager mcResourceManager, DownloadingPackFinder metadataSerializer)
{
loading = true;
ClientModLoader.mc = minecraft;
@@ -87,8 +88,8 @@ public class ClientModLoader
public static void complete()
{
GlStateManager.disableTexture2D();
GlStateManager.enableTexture2D();
GlStateManager.disableTexture();
GlStateManager.enableTexture();
List<ModLoadingWarning> warnings = ModLoader.get().getWarnings();
boolean showWarnings = true;
try {
@@ -20,7 +20,7 @@
package net.minecraftforge.fml.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ExtensionPoint;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
@@ -30,7 +30,7 @@ import java.util.function.BiFunction;
public class ConfigGuiHandler
{
public static Optional<BiFunction<Minecraft, GuiScreen, GuiScreen>> getGuiFactoryFor(ModInfo selectedMod)
public static Optional<BiFunction<Minecraft, Screen, Screen>> getGuiFactoryFor(ModInfo selectedMod)
{
return ModList.get().getModContainerById(selectedMod.getModId()).
flatMap(mc -> mc.getCustomExtension(ExtensionPoint.CONFIGGUIFACTORY));
@@ -19,12 +19,12 @@
package net.minecraftforge.fml.client;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public interface IDisplayableError
{
@OnlyIn(Dist.CLIENT)
GuiScreen createGui();
Screen createGui();
}
@@ -21,7 +21,7 @@ package net.minecraftforge.fml.client;
import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.screen.Screen;
/**
* This is the interface you need to implement if you want to provide a customized config screen.
@@ -62,7 +62,7 @@ public interface IModGuiFactory {
* @return A class that will be instantiated on clicks on the config button
* or null if no GUI is desired.
*/
GuiScreen createConfigGui(GuiScreen parentScreen);
Screen createConfigGui(Screen parentScreen);
/**
* Return a list of the "runtime" categories this mod wishes to populate with
@@ -20,7 +20,8 @@
package net.minecraftforge.fml.client.config;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.widget.button.Button;
/**
* This class provides a button that fixes several bugs present in the vanilla GuiButton drawing code.
@@ -32,54 +33,24 @@ import net.minecraft.client.gui.GuiButton;
*
* @author bspkrs
*/
public class GuiButtonExt extends GuiButton
public class GuiButtonExt extends Button
{
public GuiButtonExt(int id, int xPos, int yPos, String displayString)
public GuiButtonExt(int xPos, int yPos, int width, int height, String displayString, IPressable handler)
{
super(id, xPos, yPos, displayString);
}
public GuiButtonExt(int id, int xPos, int yPos, int width, int height, String displayString)
{
super(id, xPos, yPos, width, height, displayString);
super(xPos, yPos, width, height, displayString, handler);
}
/**
* Draws this button to the screen.
*/
@Override
public void render(int mouseX, int mouseY, float partial)
public void renderButton(int mouseX, int mouseY, float partial)
{
if (this.visible)
{
Minecraft mc = Minecraft.getInstance();
this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height;
int k = this.getHoverState(this.hovered);
GuiUtils.drawContinuousTexturedBox(BUTTON_TEXTURES, this.x, this.y, 0, 46 + k * 20, this.width, this.height, 200, 20, 2, 3, 2, 2, this.zLevel);
this.renderBg(mc, mouseX, mouseY);
int color = 14737632;
if (packedFGColor != 0)
{
color = packedFGColor;
}
else if (!this.enabled)
{
color = 10526880;
}
else if (this.hovered)
{
color = 16777120;
}
String buttonText = this.displayString;
int strWidth = mc.fontRenderer.getStringWidth(buttonText);
int ellipsisWidth = mc.fontRenderer.getStringWidth("...");
if (strWidth > width - 6 && strWidth > ellipsisWidth)
buttonText = mc.fontRenderer.trimStringToWidth(buttonText, width - 6 - ellipsisWidth).trim() + "...";
this.drawCenteredString(mc.fontRenderer, buttonText, this.x + this.width / 2, this.y + (this.height - 8) / 2, color);
}
super.renderButton(mouseX, mouseY, partial);
FontRenderer font = Minecraft.getInstance().fontRenderer;
int strWidth = font.getStringWidth(this.getMessage());
int ellipsisWidth = font.getStringWidth("...");
if (strWidth > width - 6 && strWidth > ellipsisWidth)
setMessage(font.trimStringToWidth(getMessage(), width - 6 - ellipsisWidth).trim() + "...");
}
}
@@ -20,56 +20,32 @@
package net.minecraftforge.fml.client.config;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.widget.button.Button;
/**
* This class provides a checkbox style control.
*
* @author bspkrs
*/
public class GuiCheckBox extends GuiButton
public class GuiCheckBox extends Button
{
private boolean isChecked;
private int boxWidth;
public GuiCheckBox(int id, int xPos, int yPos, String displayString, boolean isChecked)
public GuiCheckBox(int xPos, int yPos, String displayString, boolean isChecked)
{
super(id, xPos, yPos, displayString);
super(xPos, yPos, Minecraft.getInstance().fontRenderer.getStringWidth(displayString) + 2 + 11, 11, displayString, b -> {});
this.isChecked = isChecked;
this.boxWidth = 11;
this.height = 11;
this.width = this.boxWidth + 2 + Minecraft.getInstance().fontRenderer.getStringWidth(displayString);
}
@Override
public void render(int mouseX, int mouseY, float partial)
public void renderButton(int mouseX, int mouseY, float partial)
{
if (this.visible)
{
Minecraft mc = Minecraft.getInstance();
this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.boxWidth && mouseY < this.y + this.height;
GuiUtils.drawContinuousTexturedBox(BUTTON_TEXTURES, this.x, this.y, 0, 46, this.boxWidth, this.height, 200, 20, 2, 3, 2, 2, this.zLevel);
this.renderBg(mc, mouseX, mouseY);
int color = 14737632;
if (packedFGColor != 0)
{
color = packedFGColor;
}
else if (!this.enabled)
{
color = 10526880;
}
if (this.isChecked)
this.drawCenteredString(mc.fontRenderer, "x", this.x + this.boxWidth / 2 + 1, this.y + 1, 14737632);
this.drawString(mc.fontRenderer, displayString, this.x + this.boxWidth + 2, this.y + 2, color);
}
super.renderButton(mouseX, mouseY, partial);
if (this.isChecked)
this.drawCenteredString(Minecraft.getInstance().fontRenderer, "x", this.x + this.boxWidth / 2 + 1, this.y + 1, 14737632);
}
@Override
public void onClick(double mouseX, double mouseY)
public void onPress()
{
this.isChecked = !this.isChecked;
}
@@ -19,27 +19,20 @@
package net.minecraftforge.fml.client.config;
import net.minecraft.client.gui.GuiDisconnected;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.screen.DisconnectedScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.text.ITextComponent;
import javax.annotation.Nullable;
public class GuiMessageDialog extends GuiDisconnected
public class GuiMessageDialog extends DisconnectedScreen
{
protected String buttonText;
public GuiMessageDialog(@Nullable GuiScreen nextScreen, String title, ITextComponent message, String buttonText)
public GuiMessageDialog(@Nullable Screen nextScreen, String title, ITextComponent message, String buttonText)
{
super(nextScreen, title, message);
this.buttonText = buttonText;
}
@Override
public void initGui()
{
super.initGui();
buttons.get(0).displayString = I18n.format(buttonText);
this.buttonText = I18n.format(buttonText);
}
}
@@ -50,14 +50,14 @@ public class GuiSlider extends GuiButtonExt
public boolean drawString = true;
public GuiSlider(int id, int xPos, int yPos, int width, int height, String prefix, String suf, double minVal, double maxVal, double currentVal, boolean showDec, boolean drawStr)
public GuiSlider(int xPos, int yPos, int width, int height, String prefix, String suf, double minVal, double maxVal, double currentVal, boolean showDec, boolean drawStr, IPressable handler)
{
this(id, xPos, yPos, width, height, prefix, suf, minVal, maxVal, currentVal, showDec, drawStr, null);
this(xPos, yPos, width, height, prefix, suf, minVal, maxVal, currentVal, showDec, drawStr, handler, null);
}
public GuiSlider(int id, int xPos, int yPos, int width, int height, String prefix, String suf, double minVal, double maxVal, double currentVal, boolean showDec, boolean drawStr, @Nullable ISlider par)
public GuiSlider(int xPos, int yPos, int width, int height, String prefix, String suf, double minVal, double maxVal, double currentVal, boolean showDec, boolean drawStr, IPressable handler, @Nullable ISlider par)
{
super(id, xPos, yPos, width, height, prefix);
super(xPos, yPos, width, height, prefix, handler);
minValue = minVal;
maxValue = maxVal;
sliderValue = (currentVal - minValue) / (maxValue - minValue);
@@ -78,18 +78,16 @@ public class GuiSlider extends GuiButtonExt
precision = 0;
}
displayString = dispString + val + suffix;
setMessage(dispString + val + suffix);
drawString = drawStr;
if(!drawString)
{
displayString = "";
}
setMessage("");
}
public GuiSlider(int id, int xPos, int yPos, String displayStr, double minVal, double maxVal, double currentVal, ISlider par)
public GuiSlider(int xPos, int yPos, String displayStr, double minVal, double maxVal, double currentVal, IPressable handler, ISlider par)
{
this(id, xPos, yPos, 150, 20, displayStr, "", minVal, maxVal, currentVal, true, true, par);
this(xPos, yPos, 150, 20, displayStr, "", minVal, maxVal, currentVal, true, true, handler, par);
}
/**
@@ -97,7 +95,7 @@ public class GuiSlider extends GuiButtonExt
* this button.
*/
@Override
public int getHoverState(boolean par1)
public int getYImage(boolean par1)
{
return 0;
}
@@ -116,7 +114,7 @@ public class GuiSlider extends GuiButtonExt
updateSlider();
}
GuiUtils.drawContinuousTexturedBox(BUTTON_TEXTURES, this.x + (int)(this.sliderValue * (float)(this.width - 8)), this.y, 0, 66, 8, this.height, 200, 20, 2, 3, 2, 2, this.zLevel);
GuiUtils.drawContinuousTexturedBox(WIDGETS_LOCATION, this.x + (int)(this.sliderValue * (float)(this.width - 8)), this.y, 0, 66, 8, this.height, 200, 20, 2, 3, 2, 2, this.blitOffset);
}
}
@@ -174,7 +172,7 @@ public class GuiSlider extends GuiButtonExt
if(drawString)
{
displayString = dispString + val + suffix;
setMessage(dispString + val + suffix);
}
if (parent != null)
@@ -19,9 +19,10 @@
package net.minecraftforge.fml.client.config;
import com.mojang.blaze3d.platform.GlStateManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.gui.widget.button.Button;
/**
* This class provides a button that shows a string glyph at the beginning. The glyph can be scaled using the glyphScale parameter.
@@ -33,9 +34,9 @@ public class GuiUnicodeGlyphButton extends GuiButtonExt
public String glyph;
public float glyphScale;
public GuiUnicodeGlyphButton(int id, int xPos, int yPos, int width, int height, String displayString, String glyph, float glyphScale)
public GuiUnicodeGlyphButton(int xPos, int yPos, int width, int height, String displayString, String glyph, float glyphScale, IPressable handler)
{
super(id, xPos, yPos, width, height, displayString);
super(xPos, yPos, width, height, displayString, handler);
this.glyph = glyph;
this.glyphScale = glyphScale;
}
@@ -46,26 +47,12 @@ public class GuiUnicodeGlyphButton extends GuiButtonExt
if (this.visible)
{
Minecraft mc = Minecraft.getInstance();
this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height;
int k = this.getHoverState(this.hovered);
GuiUtils.drawContinuousTexturedBox(GuiButton.BUTTON_TEXTURES, this.x, this.y, 0, 46 + k * 20, this.width, this.height, 200, 20, 2, 3, 2, 2, this.zLevel);
this.isHovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height;
int k = this.getYImage(this.isHovered);
GuiUtils.drawContinuousTexturedBox(Button.WIDGETS_LOCATION, this.x, this.y, 0, 46 + k * 20, this.width, this.height, 200, 20, 2, 3, 2, 2, this.blitOffset);
this.renderBg(mc, mouseX, mouseY);
int color = 14737632;
if (packedFGColor != 0)
{
color = packedFGColor;
}
else if (!this.enabled)
{
color = 10526880;
}
else if (this.hovered)
{
color = 16777120;
}
String buttonText = this.displayString;
String buttonText = this.getMessage();
int glyphWidth = (int) (mc.fontRenderer.getStringWidth(glyph) * glyphScale);
int strWidth = mc.fontRenderer.getStringWidth(buttonText);
int ellipsisWidth = mc.fontRenderer.getStringWidth("...");
@@ -81,11 +68,11 @@ public class GuiUnicodeGlyphButton extends GuiButtonExt
GlStateManager.scalef(glyphScale, glyphScale, 1.0F);
this.drawCenteredString(mc.fontRenderer, glyph,
(int) (((this.x + (this.width / 2) - (strWidth / 2)) / glyphScale) - (glyphWidth / (2 * glyphScale)) + 2),
(int) (((this.y + ((this.height - 8) / glyphScale) / 2) - 1) / glyphScale), color);
(int) (((this.y + ((this.height - 8) / glyphScale) / 2) - 1) / glyphScale), getFGColor());
GlStateManager.popMatrix();
this.drawCenteredString(mc.fontRenderer, buttonText, (int) (this.x + (this.width / 2) + (glyphWidth / glyphScale)),
this.y + (this.height - 8) / 2, color);
this.y + (this.height - 8) / 2, getFGColor());
}
}
}
@@ -21,8 +21,7 @@ package net.minecraftforge.fml.client.config;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.BufferBuilder;
@@ -34,6 +33,8 @@ import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.opengl.GL11;
import com.mojang.blaze3d.platform.GlStateManager;
import java.util.ArrayList;
import java.util.List;
@@ -427,7 +428,7 @@ public class GuiUtils
float endGreen = (float)(endColor >> 8 & 255) / 255.0F;
float endBlue = (float)(endColor & 255) / 255.0F;
GlStateManager.disableTexture2D();
GlStateManager.disableTexture();
GlStateManager.enableBlend();
GlStateManager.disableAlphaTest();
GlStateManager.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
@@ -445,7 +446,7 @@ public class GuiUtils
GlStateManager.shadeModel(GL11.GL_FLAT);
GlStateManager.disableBlend();
GlStateManager.enableAlphaTest();
GlStateManager.enableTexture2D();
GlStateManager.enableTexture();
}
public static void drawInscribedRect(int x, int y, int boundsWidth, int boundsHeight, int rectWidth, int rectHeight)
@@ -465,6 +466,6 @@ public class GuiUtils
if (centerX) x += (w - boundsWidth) / 2;
}
Gui.drawScaledCustomSizeModalRect(x, y, 0, 0, rectWidth, rectHeight, boundsWidth, boundsHeight, rectWidth, rectHeight);
AbstractGui.blit(x, y, 0, 0, rectWidth, rectHeight, boundsWidth, boundsHeight, rectWidth, rectHeight);
}
}
@@ -19,20 +19,20 @@
package net.minecraftforge.fml.client.config;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.widget.button.Button;
/**
* This class implements an easy way to check if the mouse has hovered within a certain region of the screen for a given
* This class implements an easy way to check if the mouse has hovered within a certain region of the screen for a given
* period of time. The region can be defined manually or by supplying a GuiButton object.
*
*
* @author bspkrs
*/
public class HoverChecker
{
private int top, bottom, left, right, threshold;
private GuiButton button;
private Button button;
private long hoverStart;
public HoverChecker(int top, int bottom, int left, int right, int threshold)
{
this.top = top;
@@ -42,13 +42,13 @@ public class HoverChecker
this.threshold = threshold;
this.hoverStart = -1;
}
public HoverChecker(GuiButton button, int threshold)
public HoverChecker(Button button, int threshold)
{
this.button = button;
this.threshold = threshold;
}
/**
* Call this method if the intended region has changed such as if the region must follow a scrolling list.
* It is not necessary to call this method if a GuiButton defines the hover region.
@@ -60,7 +60,7 @@ public class HoverChecker
this.left = left;
this.right = right;
}
/**
* Checks if the mouse is in the hover region. If the specified time period has elapsed the method returns true.
* The hover timer is reset if the mouse is not within the region.
@@ -79,20 +79,20 @@ public class HoverChecker
if (this.button != null)
{
this.top = button.y;
this.bottom = button.y + button.height;
this.bottom = button.y + button.getHeight();
this.left = button.x;
this.right = button.x + button.width;
this.right = button.x + button.getWidth();
canHover = canHover && button.visible;
}
if (canHover && hoverStart == -1 && mouseY >= top && mouseY <= bottom && mouseX >= left && mouseX <= right)
hoverStart = System.currentTimeMillis();
else if (!canHover || mouseY < top || mouseY > bottom || mouseX < left || mouseX > right)
resetHoverTimer();
return canHover && hoverStart != -1 && System.currentTimeMillis() - hoverStart >= threshold;
}
/**
* Manually resets the hover timer.
*/
@@ -19,8 +19,6 @@
package net.minecraftforge.fml.client.config;
import net.minecraft.client.gui.GuiTextField;
/**
* Provides an interface for defining GuiConfigEntry.listEntry objects.
*/
@@ -19,41 +19,39 @@
package net.minecraftforge.fml.client.gui;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.text.TranslationTextComponent;
public class GuiAccessDenied extends GuiScreen
public class GuiAccessDenied extends Screen
{
private GuiScreen parent;
private Screen parent;
private ServerData data;
public GuiAccessDenied(GuiScreen parent, ServerData data)
public GuiAccessDenied(Screen parent, ServerData data)
{
super(new TranslationTextComponent("fml.menu.accessdenied.title"));
this.parent = parent;
this.data = data;
}
@Override
public void initGui()
public void init()
{
this.buttons.add(new GuiButton(1, this.width / 2 - 75, this.height - 38, I18n.format("gui.done"))
{
public void onClick(double mouseX, double mouseY)
{
GuiAccessDenied.this.mc.displayGuiScreen(parent);
}
});
this.buttons.add(new Button(this.width / 2 - 75, this.height - 38, 200, 20, I18n.format("gui.done"), b -> GuiAccessDenied.this.minecraft.displayGuiScreen(parent)));
}
@Override
public void render(int mouseX, int mouseY, float partialTicks)
{
this.drawDefaultBackground();
int offset = Math.max(85 - 2 * 10, 10);
this.drawCenteredString(this.fontRenderer, "Forge Mod Loader could not connect to this server", this.width / 2, offset, 0xFFFFFF);
offset += 10;
this.drawCenteredString(this.fontRenderer, String.format("The server %s has forbidden modded access", data.serverName), this.width / 2, offset, 0xFFFFFF);
this.renderBackground();
String[] lines = I18n.format("fml.menu.accessdenied.message", data.serverName).split("\n");
int offset = Math.max(85 - lines.length * 10, 10);
for (String line : lines) {
this.drawCenteredString(this.font, line, this.width / 2, offset, 0xFFFFFF);
offset += 10;
}
super.render(mouseX, mouseY, partialTicks);
}
}
@@ -20,40 +20,38 @@
package net.minecraftforge.fml.client.gui;
import java.io.File;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.text.TranslationTextComponent;
public class GuiBackupFailed extends GuiScreen
public class GuiBackupFailed extends Screen
{
private GuiScreen parent;
private Screen parent;
private File zipName;
public GuiBackupFailed(GuiScreen parent, File zipName)
public GuiBackupFailed(Screen parent, File zipName)
{
super(new TranslationTextComponent("fml.menu.backupfailed.title"));
this.parent = parent;
this.zipName = zipName;
}
@Override
public void initGui()
public void init()
{
this.buttons.add(new GuiButton(1, this.width / 2 - 75, this.height - 38, I18n.format("gui.done"))
{
public void onClick(double mouseX, double mouseY)
{
GuiBackupFailed.this.mc.displayGuiScreen(parent);
}
});
this.buttons.add(new Button(this.width / 2 - 75, this.height - 38, 200, 20, I18n.format("gui.done"), b -> GuiBackupFailed.this.minecraft.displayGuiScreen(parent)));
}
@Override
public void render(int mouseX, int mouseY, float partialTicks)
{
this.drawDefaultBackground();
int offset = Math.max(85 - 2 * 10, 10);
this.drawCenteredString(this.fontRenderer, String.format("There was an error saving the archive %s", zipName.getName()), this.width / 2, offset, 0xFFFFFF);
offset += 10;
this.drawCenteredString(this.fontRenderer, String.format("Please fix the problem and try again"), this.width / 2, offset, 0xFFFFFF);
this.renderBackground();
String[] lines = I18n.format("fml.menu.backupfailed.message", zipName.getName()).split("\n");
int offset = Math.max(85 - lines.length * 10, 10);
for (String line : lines) {
this.drawCenteredString(this.font, line, this.width / 2, offset, 0xFFFFFF);
offset += 10;
}
super.render(mouseX, mouseY, partialTicks);
}
}
@@ -1,43 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.client.gui;
import net.minecraft.client.gui.GuiButton;
public class GuiButtonClickConsumer extends GuiButton {
public interface DoubleBiConsumer {
void applyAsDouble(double x, double y);
}
private final DoubleBiConsumer onClickAction;
public GuiButtonClickConsumer(final int buttonId, final int x, final int y, final String buttonText, DoubleBiConsumer onClick) {
super(buttonId, x, y, buttonText);
this.onClickAction = onClick;
}
public GuiButtonClickConsumer(final int buttonId, final int x, final int y, final int widthIn, final int heightIn, final String buttonText, DoubleBiConsumer onClick) {
super(buttonId, x, y, widthIn, heightIn, buttonText);
this.onClickAction = onClick;
}
@Override
public void onClick(final double mouseX, final double mouseY) {
onClickAction.applyAsDouble(mouseX, mouseY);
}
}
@@ -18,6 +18,7 @@
*/
package net.minecraftforge.fml.client.gui;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraftforge.fml.ForgeI18n;
import net.minecraftforge.fml.StartupQuery;
@@ -29,18 +30,18 @@ public class GuiConfirmation extends GuiNotification
}
@Override
public void initGui()
public void init()
{
this.addButton(new GuiButtonClickConsumer(0, this.width / 2 - 104, this.height - 38, 100, 20, ForgeI18n.parseMessage("gui.yes"),(x, y)->
this.addButton(new Button(this.width / 2 - 104, this.height - 38, 100, 20, ForgeI18n.parseMessage("gui.yes"), b ->
{
GuiConfirmation.this.mc.currentScreen = null;
GuiConfirmation.this.minecraft.currentScreen = null;
query.setResult(true);
query.finish();
}
));
this.addButton(new GuiButtonClickConsumer(1, this.width / 2 + 4, this.height - 38, 100, 20, ForgeI18n.parseMessage("gui.no"), (x,y)->
this.addButton(new Button(this.width / 2 + 4, this.height - 38, 100, 20, ForgeI18n.parseMessage("gui.no"), b ->
{
GuiConfirmation.this.mc.currentScreen = null;
GuiConfirmation.this.minecraft.currentScreen = null;
query.setResult(false);
query.finish();
}
@@ -39,15 +39,16 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.maven.artifact.versioning.ComparableVersion;
import com.mojang.blaze3d.platform.GlStateManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiListExtended;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.gui.GuiUtilRenderComponents;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.widget.list.ExtendedList;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.gui.widget.Widget;
import net.minecraft.client.gui.RenderComponentsUtil;
import net.minecraft.client.renderer.Rectangle2d;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.renderer.texture.NativeImage;
@@ -55,7 +56,8 @@ import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.util.Size2i;
import net.minecraftforge.fml.ForgeI18n;
@@ -71,32 +73,19 @@ import net.minecraftforge.fml.packs.ModFileResourcePack;
import net.minecraftforge.fml.packs.ResourcePackLoader;
import net.minecraftforge.forgespi.language.IModInfo;
/**
* @author cpw
*
*/
public class GuiModList extends GuiScreen
public class GuiModList extends Screen
{
private static final Logger LOGGER = LogManager.getLogger();
private enum SortType implements Comparator<ModInfo>
{
NORMAL(24),
A_TO_Z(25){ @Override protected int compare(String name1, String name2){ return name1.compareTo(name2); }},
Z_TO_A(26){ @Override protected int compare(String name1, String name2){ return name2.compareTo(name1); }};
NORMAL,
A_TO_Z{ @Override protected int compare(String name1, String name2){ return name1.compareTo(name2); }},
Z_TO_A{ @Override protected int compare(String name1, String name2){ return name2.compareTo(name1); }};
GuiButton button;
private int buttonID;
private SortType(int buttonID)
{
this.buttonID = buttonID;
}
Button button;
protected int compare(String name1, String name2){ return 0; }
@Override
public int compare(ModInfo o1, ModInfo o2)
{
public int compare(ModInfo o1, ModInfo o2) {
String name1 = StringUtils.toLowerCase(stripControlCodes(o1.getDisplayName()));
String name2 = StringUtils.toLowerCase(stripControlCodes(o2.getDisplayName()));
return compare(name1, name2);
@@ -105,41 +94,23 @@ public class GuiModList extends GuiScreen
String getButtonText() {
return I18n.format("fml.menu.mods."+StringUtils.toLowerCase(name()));
}
}
private class SortButton extends GuiButton {
private final SortType type;
public SortButton(int buttonId, int x, int y, int width, int height, SortType type)
{
super(buttonId, x, y, width, height, type.getButtonText());
this.type = type;
}
@Override
public void onClick(double mouseX, double mouseY)
{
GuiModList.this.sortType = this.type;
resortMods();
}
}
private GuiScreen mainMenu;
private Screen mainMenu;
private GuiSlotModList modList;
private InfoPanel modInfo;
private int selected = -1;
private ModInfo selectedMod;
private GuiSlotModList.ModEntry selected = null;
private int listWidth;
private List<ModInfo> mods;
private final List<ModInfo> unsortedMods;
private GuiButton configButton;
private Button configButton;
private int buttonMargin = 1;
private int numButtons = SortType.values().length;
private String lastFilterText = "";
private GuiTextField search;
private TextFieldWidget search;
private boolean sorted = false;
private SortType sortType = SortType.NORMAL;
@@ -147,27 +118,28 @@ public class GuiModList extends GuiScreen
/**
* @param mainMenu
*/
public GuiModList(GuiScreen mainMenu)
public GuiModList(Screen mainMenu)
{
super(new TranslationTextComponent("fml.menu.mods.title"));
this.mainMenu = mainMenu;
this.mods = Collections.unmodifiableList(ModList.get().getMods());
this.unsortedMods = Collections.unmodifiableList(this.mods);
}
class InfoPanel extends GuiListExtended<InfoPanel.Info> {
class InfoPanel extends ExtendedList<InfoPanel.Info> {
InfoPanel(Minecraft mcIn, int widthIn, int heightIn, int topIn, int bottomIn, int slotHeightIn)
{
super(mcIn, widthIn, heightIn, topIn, bottomIn, slotHeightIn);
}
@Override
protected int getScrollBarX()
protected int getScrollbarPosition()
{
return this.right - 6;
return this.getRight() - 6;
}
@Override
public int getListWidth() {
public int getRowWidth() {
return this.width;
}
@@ -181,13 +153,13 @@ public class GuiModList extends GuiScreen
{
this.clearEntries();
}
class Info extends GuiListExtended.IGuiListEntry<Info>
class Info extends ExtendedList.AbstractListEntry<Info>
{
private ResourceLocation logoPath;
private Size2i logoDims;
private List<ITextComponent> lines;
public Info(GuiListExtended<Info> parent, List<String> lines, @Nullable ResourceLocation logoPath, Size2i logoDims)
public Info(ExtendedList<Info> parent, List<String> lines, @Nullable ResourceLocation logoPath, Size2i logoDims)
{
this.list = parent;
this.lines = resizeContent(lines);
@@ -210,20 +182,17 @@ public class GuiModList extends GuiScreen
int maxTextLength = InfoPanel.this.width - 8;
if (maxTextLength >= 0)
{
ret.addAll(GuiUtilRenderComponents.splitText(chat, maxTextLength, GuiModList.this.fontRenderer, false, true));
ret.addAll(RenderComponentsUtil.splitText(chat, maxTextLength, GuiModList.this.font, false, true));
}
}
return ret;
}
@Override
public void drawEntry(int entryWidth, int entryHeight, int mouseX, int mouseY, boolean p_194999_5_, float partialTicks)
public void render(int entryIdx, int top, int left, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean p_194999_5_, float partialTicks)
{
int top = this.getY();
int left = this.getX();
if (logoPath != null) {
mc.getTextureManager().bindTexture(logoPath);
Minecraft.getInstance().getTextureManager().bindTexture(logoPath);
GlStateManager.enableBlend();
GlStateManager.color4f(1.0F, 1.0F, 1.0F, 1.0F);
// Draw the logo image inscribed in a rectangle with width entryWidth (minus some padding) and height 50
@@ -237,16 +206,16 @@ public class GuiModList extends GuiScreen
if (line != null)
{
GlStateManager.enableBlend();
GuiModList.this.fontRenderer.drawStringWithShadow(line.getFormattedText(), left + 4, top, 0xFFFFFF);
GuiModList.this.font.drawStringWithShadow(line.getFormattedText(), left + 4, top, 0xFFFFFF);
GlStateManager.disableAlphaTest();
GlStateManager.disableBlend();
}
top += fontRenderer.FONT_HEIGHT;
top += font.FONT_HEIGHT;
}
final ITextComponent component = findTextLine(mouseX, mouseY, 0, 0);
if (component!=null) {
GuiModList.this.handleComponentHover(component, mouseX, mouseY);
GuiModList.this.renderComponentHoverEffect(component, mouseX, mouseY);
}
}
@@ -258,7 +227,7 @@ public class GuiModList extends GuiScreen
if (offset <= 0)
return null;
int lineIdx = offset / fontRenderer.FONT_HEIGHT;
int lineIdx = offset / font.FONT_HEIGHT;
if (lineIdx >= lines.size() || lineIdx < 1)
return null;
@@ -267,9 +236,9 @@ public class GuiModList extends GuiScreen
{
int k = offX;
for (ITextComponent part : line) {
if (!(part instanceof TextComponentString))
if (!(part instanceof StringTextComponent))
continue;
k += GuiModList.this.fontRenderer.getStringWidth(((TextComponentString)part).getText());
k += GuiModList.this.font.getStringWidth(((StringTextComponent)part).getText());
if (k >= mouseX)
{
return part;
@@ -281,9 +250,9 @@ public class GuiModList extends GuiScreen
@Override
public boolean mouseClicked(final double mouseX, final double mouseY, final int buttonmask) {
final ITextComponent component = findTextLine((int) mouseX, (int) mouseY, InfoPanel.this.left, InfoPanel.this.top);
final ITextComponent component = findTextLine((int) mouseX, (int) mouseY, InfoPanel.this.getLeft(), InfoPanel.this.getTop());
if (component != null) {
GuiModList.this.handleComponentClick(component);
GuiModList.this.handleComponentClicked(component);
return true;
}
return false;
@@ -291,7 +260,7 @@ public class GuiModList extends GuiScreen
}
}
@Override
public void initGui()
public void init()
{
for (ModInfo mod : mods)
{
@@ -301,16 +270,16 @@ public class GuiModList extends GuiScreen
listWidth = Math.min(listWidth, 150);
listWidth += listWidth % numButtons != 0 ? (numButtons - listWidth % numButtons) : 0;
this.modList = new GuiSlotModList(this, listWidth);
this.modList.setSlotXBoundsFromLeft(6);
this.modInfo = new InfoPanel(this.mc, this.width - this.listWidth - 20, this.height, 10, this.height - 30, this.height - 46);
this.modInfo.setSlotXBoundsFromLeft(this.listWidth + 14);
this.modList.setLeftPos(6);
this.modInfo = new InfoPanel(this.minecraft, this.width - this.listWidth - 20, this.height, 10, this.height - 30, this.height - 46);
this.modInfo.setLeftPos(this.listWidth + 14);
this.addButton(new GuiButtonClickConsumer(6, ((modList.right + this.width) / 2) - 100, this.height - 24,
I18n.format("gui.done"), (x, y) -> GuiModList.this.mc.displayGuiScreen(GuiModList.this.mainMenu)));
this.addButton(this.configButton = new GuiButtonClickConsumer(20, 6, this.height - 24, this.listWidth, 20,
I18n.format("fml.menu.mods.config"), (x,y)-> GuiModList.this.displayModConfig()));
this.addButton(new Button(((modList.getRight() + this.width) / 2) - 100, this.height - 24, 200, 20,
I18n.format("gui.done"), b -> GuiModList.this.minecraft.displayGuiScreen(GuiModList.this.mainMenu)));
this.addButton(this.configButton = new Button(6, this.height - 24, this.listWidth, 20,
I18n.format("fml.menu.mods.config"), b -> GuiModList.this.displayModConfig()));
search = new GuiTextField(0, getFontRenderer(), 8, modList.bottom + 17, listWidth - 4, 14);
search = new TextFieldWidget(getFontRenderer(), 8, modList.getBottom() + 17, listWidth - 4, 14, I18n.format("fml.menu.mods.search"));
children.add(search);
children.add(modList);
children.add(modInfo);
@@ -319,25 +288,25 @@ public class GuiModList extends GuiScreen
final int width = listWidth / numButtons;
int x = 6, y = 10;
addButton(SortType.NORMAL.button = new SortButton(SortType.NORMAL.buttonID, x, y, width - buttonMargin, 20, SortType.NORMAL));
addButton(SortType.NORMAL.button = new Button(x, y, width - buttonMargin, 20, SortType.NORMAL.getButtonText(), b -> this.sortType = SortType.NORMAL));
x += width + buttonMargin;
addButton(SortType.A_TO_Z.button = new SortButton(SortType.NORMAL.buttonID, x, y, width - buttonMargin, 20, SortType.A_TO_Z));
addButton(SortType.A_TO_Z.button = new Button(x, y, width - buttonMargin, 20, SortType.A_TO_Z.getButtonText(), b -> this.sortType = SortType.A_TO_Z));
x += width + buttonMargin;
addButton(SortType.Z_TO_A.button = new SortButton(SortType.NORMAL.buttonID, x, y, width - buttonMargin, 20, SortType.Z_TO_A));
addButton(SortType.Z_TO_A.button = new Button(x, y, width - buttonMargin, 20, SortType.Z_TO_A.getButtonText(), b -> this.sortType = SortType.Z_TO_A));
resortMods();
updateCache();
}
private void displayModConfig()
{
if (selectedMod == null) return;
if (selected == null) return;
try
{
ConfigGuiHandler.getGuiFactoryFor(selectedMod).map(f->f.apply(this.mc, this)).ifPresent(newScreen -> this.mc.displayGuiScreen(newScreen));
ConfigGuiHandler.getGuiFactoryFor(selected.getInfo()).map(f->f.apply(this.minecraft, this)).ifPresent(newScreen -> this.minecraft.displayGuiScreen(newScreen));
}
catch (final Exception e)
{
LOGGER.error("There was a critical issue trying to build the config GUI for {}", selectedMod.getModId(), e);
LOGGER.error("There was a critical issue trying to build the config GUI for {}", selected.getInfo().getModId(), e);
}
}
@@ -356,13 +325,14 @@ public class GuiModList extends GuiScreen
{
reloadMods();
mods.sort(sortType);
selected = mods.indexOf(selectedMod);
modList.refreshList();
if (selected != null)
selected = modList.children().stream().filter(e -> e.getInfo() == selected.getInfo()).findFirst().orElse(null);
sorted = true;
}
}
public <T extends GuiListExtended.IGuiListEntry<T>> void buildModList(Consumer<T> modListViewConsumer, Function<ModInfo, T> newEntry)
public <T extends ExtendedList.AbstractListEntry<T>> void buildModList(Consumer<T> modListViewConsumer, Function<ModInfo, T> newEntry)
{
mods.forEach(mod->modListViewConsumer.accept(newEntry.apply(mod)));
}
@@ -376,11 +346,10 @@ public class GuiModList extends GuiScreen
private void resortMods()
{
for (GuiButton b : buttons)
for (SortType sort : SortType.values())
{
if (b instanceof SortButton) {
b.enabled = sortType.button != b;
}
if (sort.button != null)
sort.button.active = sortType != sort;
}
sorted = false;
}
@@ -388,60 +357,49 @@ public class GuiModList extends GuiScreen
@Override
public void render(int mouseX, int mouseY, float partialTicks)
{
this.modList.drawScreen(mouseX, mouseY, partialTicks);
this.modInfo.drawScreen(mouseX, mouseY, partialTicks);
this.modList.render(mouseX, mouseY, partialTicks);
this.modInfo.render(mouseX, mouseY, partialTicks);
int left = ((this.width - this.listWidth - 38) / 2) + this.listWidth + 30;
String text = I18n.format("fml.menu.mods.search");
int x = ((10 + modList.right) / 2) - (getFontRenderer().getStringWidth(text) / 2);
getFontRenderer().drawString(text, x, modList.bottom + 5, 0xFFFFFF);
this.search.drawTextField(mouseX, mouseY, partialTicks);
int x = ((10 + modList.getRight()) / 2) - (getFontRenderer().getStringWidth(text) / 2);
getFontRenderer().drawString(text, x, modList.getBottom() + 5, 0xFFFFFF);
this.search.render(mouseX, mouseY, partialTicks);
super.render(mouseX, mouseY, partialTicks);
}
Minecraft getMinecraftInstance()
{
return mc;
return minecraft;
}
FontRenderer getFontRenderer()
{
return fontRenderer;
return font;
}
public void selectModIndex(int index)
public void setSelected(GuiSlotModList.ModEntry entry)
{
if (index == this.selected) {
this.selected = -1;
} else
{
this.selected = index;
}
this.selectedMod = (this.selected >= 0 && this.selected< mods.size()) ? mods.get(this.selected) : null;
this.selected = entry == this.selected ? null : entry;
updateCache();
}
public boolean modIndexSelected(int index)
{
return index == selected;
}
private void updateCache()
{
if (selectedMod == null) {
if (selected == null) {
modInfo.clear();
return;
}
ModInfo selectedMod = selected.getInfo();
this.configButton.enabled = selectedMod.hasConfigUI();
this.configButton.active = selectedMod.hasConfigUI();
List<String> lines = new ArrayList<>();
VersionChecker.CheckResult vercheck = VersionChecker.getResult(selectedMod);
Pair<ResourceLocation, Size2i> logoData = selectedMod.getLogoFile().map(logoFile->
{
TextureManager tm = mc.getTextureManager();
TextureManager tm = this.minecraft.getTextureManager();
final ModFileResourcePack resourcePack = ResourcePackLoader.getResourcePackFor(selectedMod.getModId())
.orElse(ResourcePackLoader.getResourcePackFor("forge").
orElseThrow(()->new RuntimeException("Can't find forge, WHAT!")));
@@ -19,35 +19,33 @@
package net.minecraftforge.fml.client.gui;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.fml.StartupQuery;
public class GuiNotification extends GuiScreen
public class GuiNotification extends Screen
{
public GuiNotification(StartupQuery query)
{
super(new TranslationTextComponent("fml.menu.notification.title"));
this.query = query;
}
@Override
public void initGui()
public void init()
{
this.buttons.add(new GuiButton(0, this.width / 2 - 100, this.height - 38, I18n.format("gui.done"))
{
public void onClick(double mouseX, double mouseY)
{
GuiNotification.this.mc.displayGuiScreen(null);
query.finish();
}
});
this.buttons.add(new Button(this.width / 2 - 100, this.height - 38, 200, 20, I18n.format("gui.done"), b -> {
GuiNotification.this.minecraft.displayGuiScreen(null);
query.finish();
}));
}
@Override
public void render(int mouseX, int mouseY, float partialTicks)
{
this.drawDefaultBackground();
this.renderBackground();
String[] lines = query.getText().split("\n");
@@ -60,12 +58,12 @@ public class GuiNotification extends GuiScreen
{
if (offset >= spaceAvailable)
{
this.drawCenteredString(this.fontRenderer, "...", this.width / 2, offset, 0xFFFFFF);
this.drawCenteredString(this.font, "...", this.width / 2, offset, 0xFFFFFF);
break;
}
else
{
if (!line.isEmpty()) this.drawCenteredString(this.fontRenderer, line, this.width / 2, offset, 0xFFFFFF);
if (!line.isEmpty()) this.drawCenteredString(this.font, line, this.width / 2, offset, 0xFFFFFF);
offset += 10;
}
}
@@ -21,9 +21,8 @@ package net.minecraftforge.fml.client.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiListExtended;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.gui.widget.list.ExtendedList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.versions.forge.ForgeVersion;
import net.minecraftforge.fml.MavenVersionStringHelper;
@@ -32,11 +31,9 @@ import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import static net.minecraft.util.StringUtils.stripControlCodes;
/**
* @author cpw
*
*/
public class GuiSlotModList extends GuiListExtended<GuiSlotModList.ModEntry>
import com.mojang.blaze3d.platform.GlStateManager;
public class GuiSlotModList extends ExtendedList<GuiSlotModList.ModEntry>
{
private static final ResourceLocation VERSION_CHECK_ICONS = new ResourceLocation(ForgeVersion.MOD_ID, "textures/gui/version_check_icons.png");
private final int listWidth;
@@ -52,13 +49,13 @@ public class GuiSlotModList extends GuiListExtended<GuiSlotModList.ModEntry>
}
@Override
protected int getScrollBarX()
protected int getScrollbarPosition()
{
return this.listWidth;
}
@Override
public int getListWidth()
public int getRowWidth()
{
return this.listWidth;
}
@@ -69,18 +66,12 @@ public class GuiSlotModList extends GuiListExtended<GuiSlotModList.ModEntry>
}
@Override
protected boolean isSelected(int index)
protected void renderBackground()
{
return this.parent.modIndexSelected(index);
this.parent.renderBackground();
}
@Override
protected void drawBackground()
{
this.parent.drawDefaultBackground();
}
class ModEntry extends GuiListExtended.IGuiListEntry<ModEntry> {
class ModEntry extends ExtendedList.AbstractListEntry<ModEntry> {
private final ModInfo modInfo;
private final GuiModList parent;
@@ -90,10 +81,8 @@ public class GuiSlotModList extends GuiListExtended<GuiSlotModList.ModEntry>
}
@Override
public void drawEntry(int entryWidth, int entryHeight, int mouseX, int mouseY, boolean p_194999_5_, float partialTicks)
public void render(int entryIdx, int top, int left, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean p_194999_5_, float partialTicks)
{
int top = this.getY();
int left = this.getX();
String name = stripControlCodes(modInfo.getDisplayName());
String version = stripControlCodes(MavenVersionStringHelper.artifactVersionToString(modInfo.getVersion()));
VersionChecker.CheckResult vercheck = VersionChecker.getResult(modInfo);
@@ -106,7 +95,7 @@ public class GuiSlotModList extends GuiListExtended<GuiSlotModList.ModEntry>
Minecraft.getInstance().getTextureManager().bindTexture(VERSION_CHECK_ICONS);
GlStateManager.color4f(1, 1, 1, 1);
GlStateManager.pushMatrix();
Gui.drawModalRectWithCustomSizedTexture(right - (height / 2 + 4), GuiSlotModList.this.top + (height / 2 - 4), vercheck.status.getSheetOffset() * 8, (vercheck.status.isAnimated() && ((System.currentTimeMillis() / 800 & 1)) == 1) ? 8 : 0, 8, 8, 64, 16);
AbstractGui.blit(getRight() - (height / 2 + 4), GuiSlotModList.this.getTop() + (height / 2 - 4), vercheck.status.getSheetOffset() * 8, (vercheck.status.isAnimated() && ((System.currentTimeMillis() / 800 & 1)) == 1) ? 8 : 0, 8, 8, 64, 16);
GlStateManager.popMatrix();
}
}
@@ -114,8 +103,14 @@ public class GuiSlotModList extends GuiListExtended<GuiSlotModList.ModEntry>
@Override
public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_)
{
parent.selectModIndex(this.getIndex());
parent.setSelected(this);
GuiSlotModList.this.setSelected(this);
return false;
}
public ModInfo getInfo()
{
return modInfo;
}
}
}
@@ -22,9 +22,11 @@ package net.minecraftforge.fml.client.gui;
import com.google.common.base.Strings;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiErrorScreen;
import net.minecraft.client.gui.GuiListExtended;
import net.minecraft.client.gui.screen.ErrorScreen;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.widget.list.ExtendedList;
import net.minecraft.util.Util;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.ForgeI18n;
import net.minecraftforge.fml.LoadingFailedException;
@@ -41,7 +43,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class LoadingErrorScreen extends GuiErrorScreen {
public class LoadingErrorScreen extends ErrorScreen {
private static final Logger LOGGER = LogManager.getLogger();
private final Path modsDir;
private final Path logFile;
@@ -53,36 +55,17 @@ public class LoadingErrorScreen extends GuiErrorScreen {
public LoadingErrorScreen(LoadingFailedException loadingException, List<ModLoadingWarning> warnings)
{
super(null, null);
super(new StringTextComponent("Loading Error"), null);
this.modLoadWarnings = warnings;
this.modLoadErrors = loadingException == null ? Collections.emptyList() : loadingException.getErrors();
this.modsDir = FMLPaths.MODSDIR.get();
this.logFile = FMLPaths.GAMEDIR.get().resolve(Paths.get("logs","latest.log"));
}
private double openModsDir(double mouseX, double mouseY)
{
Util.getOSType().openFile(modsDir.toFile());
return 0.0;
}
private double openLogFile(double mouseX, double mouseY)
{
Util.getOSType().openFile(logFile.toFile());
return 0.0;
}
private double continueGame(double mouseX, double mouseY)
{
ClientHooks.logMissingTextureErrors();
mc.displayGuiScreen(null);
return 0.0;
}
@Override
public void initGui()
public void init()
{
super.initGui();
super.init();
this.buttons.clear();
this.children.clear();
@@ -90,13 +73,13 @@ public class LoadingErrorScreen extends GuiErrorScreen {
this.warningHeader = TextFormatting.YELLOW + ForgeI18n.parseMessage("fml.loadingerrorscreen.warningheader", this.modLoadErrors.size()) + TextFormatting.RESET;
int yOffset = this.modLoadErrors.isEmpty() ? 46 : 38;
this.addButton(new GuiButtonClickConsumer(10, 50, this.height - yOffset, this.width / 2 - 55, 20,
ForgeI18n.parseMessage("fml.button.open.mods.folder"), this::openModsDir));
this.addButton(new GuiButtonClickConsumer(11, this.width / 2 + 5, this.height - yOffset, this.width / 2 - 55, 20,
ForgeI18n.parseMessage("fml.button.open.file", logFile.getFileName()), this::openLogFile));
this.addButton(new Button(50, this.height - yOffset, this.width / 2 - 55, 20, ForgeI18n.parseMessage("fml.button.open.mods.folder"), b -> Util.getOSType().openFile(modsDir.toFile())));
this.addButton(new Button(this.width / 2 + 5, this.height - yOffset, this.width / 2 - 55, 20, ForgeI18n.parseMessage("fml.button.open.file", logFile.getFileName()), b -> Util.getOSType().openFile(logFile.toFile())));
if (this.modLoadErrors.isEmpty()) {
this.addButton(new GuiButtonClickConsumer(12, this.width / 4, this.height - 24, this.width / 2, 20,
ForgeI18n.parseMessage("fml.button.continue.launch"), this::continueGame));
this.addButton(new Button(this.width / 4, this.height - 24, this.width / 2, 20, ForgeI18n.parseMessage("fml.button.continue.launch"), b -> {
ClientHooks.logMissingTextureErrors();
this.minecraft.displayGuiScreen(null);
}));
}
this.entryList = new LoadingEntryList(this, this.modLoadErrors, this.modLoadWarnings);
@@ -107,9 +90,9 @@ public class LoadingErrorScreen extends GuiErrorScreen {
@Override
public void render(int mouseX, int mouseY, float partialTicks)
{
this.drawDefaultBackground();
this.entryList.drawScreen(mouseX, mouseY, partialTicks);
drawMultiLineCenteredString(fontRenderer, this.modLoadErrors.isEmpty() ? warningHeader : errorHeader, this.width / 2, 10);
this.renderBackground();
this.entryList.render(mouseX, mouseY, partialTicks);
drawMultiLineCenteredString(font, this.modLoadErrors.isEmpty() ? warningHeader : errorHeader, this.width / 2, 10);
this.buttons.forEach(button -> button.render(mouseX, mouseY, partialTicks));
}
@@ -119,15 +102,15 @@ public class LoadingErrorScreen extends GuiErrorScreen {
y+=fr.FONT_HEIGHT;
}
}
public static class LoadingEntryList extends GuiListExtended<LoadingEntryList.LoadingMessageEntry> {
public static class LoadingEntryList extends ExtendedList<LoadingEntryList.LoadingMessageEntry> {
LoadingEntryList(final LoadingErrorScreen parent, final List<ModLoadingException> errors, final List<ModLoadingWarning> warnings) {
super(parent.mc, parent.width, parent.height, 35, parent.height - 50, 2 * parent.mc.fontRenderer.FONT_HEIGHT + 8);
super(parent.minecraft, parent.width, parent.height, 35, parent.height - 50, 2 * parent.minecraft.fontRenderer.FONT_HEIGHT + 8);
boolean both = !errors.isEmpty() && !warnings.isEmpty();
if (both)
addEntry(new LoadingMessageEntry(parent.errorHeader, true));
errors.forEach(e->addEntry(new LoadingMessageEntry(e.formatToString())));
if (both) {
int maxChars = (this.width - 10) / parent.mc.fontRenderer.getStringWidth("-");
int maxChars = (this.width - 10) / parent.minecraft.fontRenderer.getStringWidth("-");
addEntry(new LoadingMessageEntry("\n" + Strings.repeat("-", maxChars) + "\n"));
addEntry(new LoadingMessageEntry(parent.warningHeader, true));
}
@@ -135,18 +118,18 @@ public class LoadingErrorScreen extends GuiErrorScreen {
}
@Override
protected int getScrollBarX()
protected int getScrollbarPosition()
{
return this.right - 6;
return this.getRight() - 6;
}
@Override
public int getListWidth()
public int getRowWidth()
{
return this.width;
}
public class LoadingMessageEntry extends GuiListExtended.IGuiListEntry<LoadingMessageEntry> {
public class LoadingMessageEntry extends ExtendedList.AbstractListEntry<LoadingMessageEntry> {
private final String message;
private final boolean center;
@@ -160,9 +143,7 @@ public class LoadingErrorScreen extends GuiErrorScreen {
}
@Override
public void drawEntry(final int entryWidth, final int entryHeight, final int mouseX, final int mouseY, final boolean p_194999_5_, final float partialTicks) {
int top = this.getY();
int left = this.getX();
public void render(int entryIdx, int top, int left, final int entryWidth, final int entryHeight, final int mouseX, final int mouseY, final boolean p_194999_5_, final float partialTicks) {
FontRenderer font = Minecraft.getInstance().fontRenderer;
final List<String> strings = font.listFormattedStringToWidth(message, LoadingEntryList.this.width);
int y = top + 2;
@@ -19,11 +19,11 @@
package net.minecraftforge.fml.client.registry;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import net.minecraft.entity.Entity;
public interface IRenderFactory<T extends Entity>
{
Render<? super T> createRenderFor(RenderManager manager);
EntityRenderer<? super T> createRenderFor(EntityRendererManager manager);
}
@@ -22,8 +22,8 @@ package net.minecraftforge.fml.client.registry;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import net.minecraft.entity.Entity;
public class RenderingRegistry
@@ -43,13 +43,13 @@ public class RenderingRegistry
INSTANCE.entityRenderers.put(entityClass, renderFactory);
}
public static void loadEntityRenderers(RenderManager manager, Map<Class<? extends Entity>, Render<? extends Entity>> renderMap)
public static void loadEntityRenderers(EntityRendererManager manager, Map<Class<? extends Entity>, EntityRenderer<? extends Entity>> renderMap)
{
INSTANCE.entityRenderers.forEach((key, value) -> register(manager, renderMap, key, value));
}
@SuppressWarnings("unchecked")
private static <T extends Entity> void register(RenderManager manager, Map<Class<? extends Entity>, Render<? extends Entity>> renderMap, Class<T> entityClass, IRenderFactory<?> renderFactory)
private static <T extends Entity> void register(EntityRendererManager manager, Map<Class<? extends Entity>, EntityRenderer<? extends Entity>> renderMap, Class<T> entityClass, IRenderFactory<?> renderFactory)
{
renderMap.put(entityClass, ((IRenderFactory<T>)renderFactory).createRenderFor(manager));
}
@@ -22,8 +22,8 @@ package net.minecraftforge.fml.common;
import java.util.Random;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.IChunkGenerator;
import net.minecraft.world.chunk.AbstractChunkProvider;
import net.minecraft.world.gen.ChunkGenerator;
/**
@@ -45,5 +45,5 @@ public interface IWorldGenerator
* @param chunkProvider : additionalData[2] {@link IChunkProvider} that is requesting the world generation.
*
*/
void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider);
void generate(Random random, int chunkX, int chunkZ, World world, ChunkGenerator chunkGenerator, AbstractChunkProvider chunkProvider);
}
@@ -18,6 +18,8 @@
*/
package net.minecraftforge.fml.common;
import net.minecraftforge.fml.common.EnhancedRuntimeException.WrappedPrintStream;
public class LoaderException extends EnhancedRuntimeException
{
@@ -19,8 +19,8 @@
package net.minecraftforge.fml.common.gameevent;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.world.dimension.DimensionType;
@@ -29,13 +29,13 @@ import net.minecraftforge.eventbus.api.Event;
import javax.annotation.Nonnull;
public class PlayerEvent extends Event {
private final EntityPlayer player;
private PlayerEvent(EntityPlayer player)
private final PlayerEntity player;
private PlayerEvent(PlayerEntity player)
{
this.player = player;
}
public EntityPlayer getPlayer()
public PlayerEntity getPlayer()
{
return this.player;
}
@@ -44,12 +44,12 @@ public class PlayerEvent extends Event {
/**
* Original EntityItem with current remaining stack size
*/
private final EntityItem originalEntity;
private final ItemEntity originalEntity;
/**
* Clone item stack, containing the item and amount picked up
*/
private final ItemStack stack;
public ItemPickupEvent(EntityPlayer player, EntityItem entPickedUp, ItemStack stack)
public ItemPickupEvent(PlayerEntity player, ItemEntity entPickedUp, ItemStack stack)
{
super(player);
this.originalEntity = entPickedUp;
@@ -60,7 +60,7 @@ public class PlayerEvent extends Event {
return stack;
}
public EntityItem getOriginalEntity() {
public ItemEntity getOriginalEntity() {
return originalEntity;
}
}
@@ -69,7 +69,7 @@ public class PlayerEvent extends Event {
@Nonnull
private final ItemStack crafting;
private final IInventory craftMatrix;
public ItemCraftedEvent(EntityPlayer player, @Nonnull ItemStack crafting, IInventory craftMatrix)
public ItemCraftedEvent(PlayerEntity player, @Nonnull ItemStack crafting, IInventory craftMatrix)
{
super(player);
this.crafting = crafting;
@@ -90,7 +90,7 @@ public class PlayerEvent extends Event {
public static class ItemSmeltedEvent extends PlayerEvent {
@Nonnull
private final ItemStack smelting;
public ItemSmeltedEvent(EntityPlayer player, @Nonnull ItemStack crafting)
public ItemSmeltedEvent(PlayerEntity player, @Nonnull ItemStack crafting)
{
super(player);
this.smelting = crafting;
@@ -104,14 +104,14 @@ public class PlayerEvent extends Event {
}
public static class PlayerLoggedInEvent extends PlayerEvent {
public PlayerLoggedInEvent(EntityPlayer player)
public PlayerLoggedInEvent(PlayerEntity player)
{
super(player);
}
}
public static class PlayerLoggedOutEvent extends PlayerEvent {
public PlayerLoggedOutEvent(EntityPlayer player)
public PlayerLoggedOutEvent(PlayerEntity player)
{
super(player);
}
@@ -120,7 +120,7 @@ public class PlayerEvent extends Event {
public static class PlayerRespawnEvent extends PlayerEvent {
private final boolean endConquered;
public PlayerRespawnEvent(EntityPlayer player, boolean endConquered)
public PlayerRespawnEvent(PlayerEntity player, boolean endConquered)
{
super(player);
this.endConquered = endConquered;
@@ -141,7 +141,7 @@ public class PlayerEvent extends Event {
public static class PlayerChangedDimensionEvent extends PlayerEvent {
private final DimensionType fromDim;
private final DimensionType toDim;
public PlayerChangedDimensionEvent(EntityPlayer player, DimensionType fromDim, DimensionType toDim)
public PlayerChangedDimensionEvent(PlayerEntity player, DimensionType fromDim, DimensionType toDim)
{
super(player);
this.fromDim = fromDim;
@@ -19,8 +19,8 @@
package net.minecraftforge.fml.common.gameevent;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.LogicalSide;
@@ -67,11 +67,11 @@ public class TickEvent extends net.minecraftforge.eventbus.api.Event
}
}
public static class PlayerTickEvent extends TickEvent {
public final EntityPlayer player;
public final PlayerEntity player;
public PlayerTickEvent(Phase phase, EntityPlayer player)
public PlayerTickEvent(Phase phase, PlayerEntity player)
{
super(Type.PLAYER, player instanceof EntityPlayerMP ? LogicalSide.SERVER : LogicalSide.CLIENT, phase);
super(Type.PLAYER, player instanceof ServerPlayerEntity ? LogicalSide.SERVER : LogicalSide.CLIENT, phase);
this.player = player;
}
}
@@ -19,7 +19,7 @@
package net.minecraftforge.fml.common.network;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.world.World;
import javax.annotation.Nullable;
@@ -38,7 +38,7 @@ public interface IGuiHandler
* @return A GuiScreen/Container to be displayed to the user, null if none.
*/
@Nullable
Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z);
Object getServerGuiElement(int ID, PlayerEntity player, World world, int x, int y, int z);
/**
* Returns a Container to be displayed to the user. On the client side, this
@@ -54,5 +54,5 @@ public interface IGuiHandler
* @return A GuiScreen/Container to be displayed to the user, null if none.
*/
@Nullable
Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z);
Object getClientGuiElement(int ID, PlayerEntity player, World world, int x, int y, int z);
}
@@ -31,11 +31,11 @@ import java.util.Iterator;
import java.util.List;
import net.minecraft.network.EnumPacketDirection;
import net.minecraft.network.PacketDirection;
import net.minecraft.network.NettyVarint21FrameDecoder;
import net.minecraft.network.NettyVarint21FrameEncoder;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.IPacket;
import net.minecraft.network.PacketBuffer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -46,14 +46,14 @@ public class PacketLoggingHandler
public static void register(NetworkManager manager)
{
ChannelPipeline pipeline = manager.channel().pipeline();
final EnumPacketDirection direction = manager.getDirection();
final PacketDirection direction = manager.getDirection();
if (manager.isLocalChannel())
{
pipeline.addBefore("packet_handler", "splitter", new SimpleChannelInboundHandler<Packet<?>>()
pipeline.addBefore("packet_handler", "splitter", new SimpleChannelInboundHandler<IPacket<?>>()
{
String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");
String prefix = (direction == PacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");
@Override
protected void channelRead0(ChannelHandlerContext ctx, Packet<?> msg) throws Exception
protected void channelRead0(ChannelHandlerContext ctx, IPacket<?> msg) throws Exception
{
PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
msg.writePacketData(buf);
@@ -63,14 +63,14 @@ public class PacketLoggingHandler
});
pipeline.addBefore("splitter", "prepender", new ChannelOutboundHandlerAdapter()
{
String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");
String prefix = (direction == PacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception
{
if (msg instanceof Packet<?>)
if (msg instanceof IPacket<?>)
{
PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
((Packet<?>)msg).writePacketData(buf);
((IPacket<?>)msg).writePacketData(buf);
LOGGER.debug("{} {}:\n{}", prefix, msg.getClass().getSimpleName(), ByteBufUtils.getContentDump(buf));
}
ctx.write(msg, promise);
@@ -81,7 +81,7 @@ public class PacketLoggingHandler
{
pipeline.replace("splitter", "splitter", new NettyVarint21FrameDecoder()
{
String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");
String prefix = (direction == PacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");
@Override
protected void decode(ChannelHandlerContext context, ByteBuf input, List<Object> output) throws Exception
{
@@ -98,7 +98,7 @@ public class PacketLoggingHandler
});
pipeline.replace("prepender", "prepender", new NettyVarint21FrameEncoder()
{
String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");
String prefix = (direction == PacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");
@Override
protected void encode(ChannelHandlerContext context, ByteBuf input, ByteBuf output) throws Exception
{
@@ -1,366 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2019.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.registry;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.annotation.Nullable;
import org.apache.commons.lang3.Validate;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.minecraft.entity.monster.EntityZombieVillager;
import net.minecraft.entity.passive.EntityVillager;
import net.minecraft.entity.passive.EntityVillager.ITradeList;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.RegistryNamespaced;
import net.minecraft.world.gen.feature.structure.StructurePiece;
import net.minecraft.world.gen.feature.structure.VillagePieces;
import net.minecraft.world.gen.feature.structure.VillagePieces.PieceWeight;
import net.minecraft.world.gen.feature.structure.VillagePieces.Village;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistryEntry;
import net.minecraftforge.registries.GameData;
/**
* Registry for villager trading control
*/
public class VillagerRegistry
{
public static final RegistryObject<VillagerProfession> FARMER = RegistryObject.of("minecraft:farmer", ()->VillagerProfession.class);
private static final VillagerRegistry INSTANCE = new VillagerRegistry();
private Map<Class<?>, IVillageCreationHandler> villageCreationHandlers = Maps.newHashMap();
private VillagerRegistry()
{
init();
}
/**
* Allow access to the {@link net.minecraft.world.gen.structure.StructureVillagePieces} array controlling new village
* creation so you can insert your own new village pieces
*
* @author cpw
*/
public interface IVillageCreationHandler
{
/**
* Called when {@link net.minecraft.world.gen.structure.MapGenVillage} is creating a new village
*
* @param random
* @param i
*/
VillagePieces.PieceWeight getVillagePieceWeight(Random random, int i);
/**
* The class of the root structure component to add to the village
*/
Class<?> getComponentClass();
/**
* Build an instance of the village component {@link net.minecraft.world.gen.structure.StructureVillagePieces}
*
* @param villagePiece
* @param startPiece
* @param pieces
* @param random
* @param p1
* @param p2
* @param p3
* @param facing
* @param p5
*/
Village buildComponent(VillagePieces.PieceWeight villagePiece, VillagePieces.Start startPiece, List<StructurePiece> pieces, Random random, int p1,
int p2, int p3, EnumFacing facing, int p5);
}
public static VillagerRegistry instance()
{
return INSTANCE;
}
/**
* Register a new village creation handler
*
* @param handler
*/
public void registerVillageCreationHandler(IVillageCreationHandler handler)
{
villageCreationHandlers.put(handler.getComponentClass(), handler);
}
public static void addExtraVillageComponents(List<PieceWeight> list, Random random, int i)
{
List<VillagePieces.PieceWeight> parts = list;
for (IVillageCreationHandler handler : instance().villageCreationHandlers.values())
{
parts.add(handler.getVillagePieceWeight(random, i));
}
}
public static Village getVillageComponent(VillagePieces.PieceWeight villagePiece, VillagePieces.Start startPiece, List<StructurePiece> pieces, Random random,
int p1, int p2, int p3, EnumFacing facing, int p5)
{
return instance().villageCreationHandlers.get(villagePiece.villagePieceClass).buildComponent(villagePiece, startPiece, pieces, random, p1, p2, p3, facing, p5);
}
RegistryNamespaced<VillagerProfession> REGISTRY = GameData.getWrapper(VillagerProfession.class);
private void register(VillagerProfession prof, int id)
{
REGISTRY.register(id, prof.name, prof);
}
private boolean hasInit = false;
private void init()
{
if (hasInit)
{
return;
}
VillagerProfession prof = new VillagerProfession("minecraft:farmer",
"minecraft:textures/entity/villager/farmer.png",
"minecraft:textures/entity/zombie_villager/zombie_farmer.png");
{
register(prof, 0);
(new VillagerCareer(prof, "farmer")).init(VanillaTrades.trades[0][0]);
(new VillagerCareer(prof, "fisherman")).init(VanillaTrades.trades[0][1]);
(new VillagerCareer(prof, "shepherd")).init(VanillaTrades.trades[0][2]);
(new VillagerCareer(prof, "fletcher")).init(VanillaTrades.trades[0][3]);
}
prof = new VillagerProfession("minecraft:librarian",
"minecraft:textures/entity/villager/librarian.png",
"minecraft:textures/entity/zombie_villager/zombie_librarian.png");
{
register(prof, 1);
(new VillagerCareer(prof, "librarian")).init(VanillaTrades.trades[1][0]);
(new VillagerCareer(prof, "cartographer")).init(VanillaTrades.trades[1][1]);
}
prof = new VillagerProfession("minecraft:priest",
"minecraft:textures/entity/villager/priest.png",
"minecraft:textures/entity/zombie_villager/zombie_priest.png");
{
register(prof, 2);
(new VillagerCareer(prof, "cleric")).init(VanillaTrades.trades[2][0]);
}
prof = new VillagerProfession("minecraft:smith",
"minecraft:textures/entity/villager/smith.png",
"minecraft:textures/entity/zombie_villager/zombie_smith.png");
{
register(prof, 3);
(new VillagerCareer(prof, "armorer")).init(VanillaTrades.trades[3][0]);
(new VillagerCareer(prof, "weapon_smith")).init(VanillaTrades.trades[3][1]);
(new VillagerCareer(prof, "tool_smith")).init(VanillaTrades.trades[3][2]);
}
prof = new VillagerProfession("minecraft:butcher",
"minecraft:textures/entity/villager/butcher.png",
"minecraft:textures/entity/zombie_villager/zombie_butcher.png");
{
register(prof, 4);
(new VillagerCareer(prof, "butcher")).init(VanillaTrades.trades[4][0]);
(new VillagerCareer(prof, "leatherworker")).init(VanillaTrades.trades[4][1]);
}
prof = new VillagerProfession("minecraft:nitwit",
"minecraft:textures/entity/villager/villager.png",
"minecraft:textures/entity/zombie_villager/zombie_villager.png");
{
register(prof, 5);
(new VillagerCareer(prof, "nitwit")).init(VanillaTrades.trades[5][0]);
}
}
public static class VillagerProfession extends ForgeRegistryEntry<VillagerProfession>
{
private ResourceLocation name;
private ResourceLocation texture;
private ResourceLocation zombie;
private List<VillagerCareer> careers = Lists.newArrayList();
public VillagerProfession(String name, String texture, String zombie)
{
this.name = new ResourceLocation(name);
this.texture = new ResourceLocation(texture);
this.zombie = new ResourceLocation(zombie);
this.setRegistryName(this.name);
}
private void register(VillagerCareer career)
{
Validate.isTrue(!careers.contains(career), "Attempted to register career that is already registered.");
Validate.isTrue(career.profession == this, "Attempted to register career for the wrong profession.");
career.id = careers.size();
careers.add(career);
}
public ResourceLocation getSkin() { return this.texture; }
public ResourceLocation getZombieSkin() { return this.zombie; }
public VillagerCareer getCareer(int id)
{
for (VillagerCareer car : this.careers)
{
if (car.id == id)
return car;
}
return this.careers.get(0);
}
public int getRandomCareer(Random rand)
{
return this.careers.get(rand.nextInt(this.careers.size())).id;
}
}
public static class VillagerCareer
{
private VillagerProfession profession;
private String name;
private int id;
private List<List<ITradeList>> trades = Lists.newArrayList();
public VillagerCareer(VillagerProfession parent, String name)
{
this.profession = parent;
this.name = name;
parent.register(this);
}
public String getName()
{
return this.name;
}
public VillagerCareer addTrade(int level, ITradeList... trades)
{
if (level <= 0)
throw new IllegalArgumentException("Levels start at 1");
List<ITradeList> levelTrades = level <= this.trades.size() ? this.trades.get(level - 1) : null;
if (levelTrades == null)
{
while (this.trades.size() < level)
{
levelTrades = Lists.newArrayList();
this.trades.add(levelTrades);
}
}
if (levelTrades == null) //Not sure how this could happen, but screw it
{
levelTrades = Lists.newArrayList();
this.trades.set(level - 1, levelTrades);
}
for (ITradeList t : trades)
levelTrades.add(t);
return this;
}
@Nullable
public List<ITradeList> getTrades(int level)
{
return level >= 0 && level < this.trades.size() ? Collections.unmodifiableList(this.trades.get(level)) : null;
}
private VillagerCareer init(EntityVillager.ITradeList[][] trades)
{
for (int x = 0; x < trades.length; x++)
this.trades.add(Lists.newArrayList(trades[x]));
return this;
}
@Override
public boolean equals(Object o)
{
if (o == this)
{
return true;
}
if (!(o instanceof VillagerCareer))
{
return false;
}
VillagerCareer oc = (VillagerCareer)o;
return name.equals(oc.name) && profession == oc.profession;
}
}
/**
* Hook called when spawning a Villager, sets it's profession to a random registered profession.
*
* @param entity The new entity
* @param rand The world's RNG
*/
public static void setRandomProfession(EntityVillager entity, Random rand)
{
entity.setProfession(INSTANCE.REGISTRY.getRandom(rand));
}
public static void setRandomProfession(EntityZombieVillager entity, Random rand)
{
entity.setProfession(INSTANCE.REGISTRY.getRandom(rand));
}
//Below this is INTERNAL USE ONLY DO NOT USE MODDERS
public static void onSetProfession(EntityVillager entity, int network)
{
VillagerProfession prof = INSTANCE.REGISTRY.get(network);
if (prof == null || INSTANCE.REGISTRY.getId(prof) != network)
{
throw new RuntimeException("Attempted to set villager profession to unregistered profession: " + network + " " + prof);
}
if (prof != entity.getProfessionForge())
entity.setProfession(prof);
}
public static void onSetProfession(EntityZombieVillager entity, int network)
{
VillagerProfession prof = INSTANCE.REGISTRY.get(network);
if (prof == null && network != -1 || INSTANCE.REGISTRY.getId(prof) != network)
{
throw new RuntimeException("Attempted to set villager profession to unregistered profession: " + network + " " + prof);
}
if (prof != entity.getProfessionForge())
entity.setProfession(prof);
}
@Deprecated public static VillagerProfession getById(int network){ return INSTANCE.REGISTRY.get(network); }
@Deprecated public static int getId(@Nullable VillagerProfession prof){ return INSTANCE.REGISTRY.getId(prof); }
//TODO: Figure out a good generic system for this. Put on hold for Patches.
private static class VanillaTrades
{
//This field is moved from EntityVillager over to here.
//Moved to inner class to stop static initializer issues.
//It is nasty I know but it's vanilla.
private static final ITradeList[][][][] trades = EntityVillager.GET_TRADES_DONT_USE();
}
}
@@ -19,8 +19,8 @@
package net.minecraftforge.fml.hooks;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
@@ -33,37 +33,37 @@ import net.minecraftforge.fml.common.gameevent.TickEvent;
public class BasicEventHooks
{
public static void firePlayerChangedDimensionEvent(EntityPlayer player, DimensionType fromDim, DimensionType toDim)
public static void firePlayerChangedDimensionEvent(PlayerEntity player, DimensionType fromDim, DimensionType toDim)
{
MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerChangedDimensionEvent(player, fromDim, toDim));
}
public static void firePlayerLoggedIn(EntityPlayer player)
public static void firePlayerLoggedIn(PlayerEntity player)
{
MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerLoggedInEvent(player));
}
public static void firePlayerLoggedOut(EntityPlayer player)
public static void firePlayerLoggedOut(PlayerEntity player)
{
MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerLoggedOutEvent(player));
}
public static void firePlayerRespawnEvent(EntityPlayer player, boolean endConquered)
public static void firePlayerRespawnEvent(PlayerEntity player, boolean endConquered)
{
MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerRespawnEvent(player, endConquered));
}
public static void firePlayerItemPickupEvent(EntityPlayer player, EntityItem item, ItemStack clone)
public static void firePlayerItemPickupEvent(PlayerEntity player, ItemEntity item, ItemStack clone)
{
MinecraftForge.EVENT_BUS.post(new PlayerEvent.ItemPickupEvent(player, item, clone));
}
public static void firePlayerCraftingEvent(EntityPlayer player, ItemStack crafted, IInventory craftMatrix)
public static void firePlayerCraftingEvent(PlayerEntity player, ItemStack crafted, IInventory craftMatrix)
{
MinecraftForge.EVENT_BUS.post(new PlayerEvent.ItemCraftedEvent(player, crafted, craftMatrix));
}
public static void firePlayerSmeltedEvent(EntityPlayer player, ItemStack smelted)
public static void firePlayerSmeltedEvent(PlayerEntity player, ItemStack smelted)
{
MinecraftForge.EVENT_BUS.post(new PlayerEvent.ItemSmeltedEvent(player, smelted));
}
@@ -79,12 +79,12 @@ public class BasicEventHooks
MinecraftForge.EVENT_BUS.post(new TickEvent.RenderTickEvent(TickEvent.Phase.END, timer));
}
public static void onPlayerPreTick(EntityPlayer player)
public static void onPlayerPreTick(PlayerEntity player)
{
MinecraftForge.EVENT_BUS.post(new TickEvent.PlayerTickEvent(TickEvent.Phase.START, player));
}
public static void onPlayerPostTick(EntityPlayer player)
public static void onPlayerPostTick(PlayerEntity player)
{
MinecraftForge.EVENT_BUS.post(new TickEvent.PlayerTickEvent(TickEvent.Phase.END, player));
}
@@ -19,12 +19,12 @@
package net.minecraftforge.fml.network;
import net.minecraft.network.login.ServerLoginNetHandler;
import com.google.common.collect.Multimap;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.NetHandlerLoginServer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.fml.config.ConfigTracker;
import net.minecraftforge.fml.loading.AdvancedLogMessageAdapter;
import net.minecraftforge.fml.network.simple.SimpleChannel;
@@ -52,16 +52,16 @@ import static net.minecraftforge.registries.ForgeRegistry.REGISTRIES;
/**
* Instance responsible for handling the overall FML network handshake.
*
* <p>An instance is created during {@link net.minecraft.network.handshake.client.CPacketHandshake} handling, and attached
* <p>An instance is created during {@link net.minecraft.network.handshake.client.CHandshakePacket} handling, and attached
* to the {@link NetworkManager#channel} via {@link FMLNetworkConstants#FML_HANDSHAKE_HANDLER}.
*
* <p>The {@link FMLNetworkConstants#handshakeChannel} is a {@link SimpleChannel} with standard messages flowing in both directions.
*
* <p>The {@link #loginWrapper} transforms these messages into {@link net.minecraft.network.login.client.CPacketCustomPayloadLogin}
* and {@link net.minecraft.network.login.server.SPacketCustomPayloadLogin} compatible messages, by means of wrapping.
* <p>The {@link #loginWrapper} transforms these messages into {@link net.minecraft.network.login.client.CCustomPayloadLoginPacket}
* and {@link net.minecraft.network.login.server.SCustomPayloadLoginPacket} compatible messages, by means of wrapping.
*
* <p>The handshake is ticked {@link #tickLogin(NetworkManager)} from the {@link NetHandlerLoginServer#update()} method,
* utilizing the {@link NetHandlerLoginServer.LoginState#NEGOTIATING} state, which is otherwise unused in vanilla code.
* <p>The handshake is ticked {@link #tickLogin(NetworkManager)} from the {@link ServerLoginNetHandler#update()} method,
* utilizing the {@link ServerLoginNetHandler.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
@@ -69,7 +69,7 @@ import static net.minecraftforge.registries.ForgeRegistry.REGISTRIES;
*
* <p>The collected {@link net.minecraftforge.fml.network.NetworkRegistry.LoginPayload} are sent, one per tick, via
* the {@link FMLLoginWrapper#wrapPacket(ResourceLocation, PacketBuffer)} mechanism to the incoming client connection. Each
* packet is indexed via {@link net.minecraft.network.login.client.CPacketCustomPayloadLogin#transaction}, which is
* packet is indexed via {@link net.minecraft.network.login.client.CCustomPayloadLoginPacket#transaction}, 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
@@ -89,7 +89,7 @@ public class FMLHandshakeHandler {
}
/**
* Create a new handshake instance. Called when connection is first created during the {@link net.minecraft.network.handshake.client.CPacketHandshake}
* Create a new handshake instance. Called when connection is first created during the {@link net.minecraft.network.handshake.client.CHandshakePacket}
* handling.
*
* @param manager The network manager for this connection
@@ -138,7 +138,7 @@ public class FMLHandshakeHandler {
c.get().setPacketHandled(true);
if (!accepted) {
LOGGER.error(FMLHSMARKER, "Terminating connection with server, mismatched mod list");
c.get().getNetworkManager().closeChannel(new TextComponentString("Connection closed - mismatched mod channel list"));
c.get().getNetworkManager().closeChannel(new StringTextComponent("Connection closed - mismatched mod channel list"));
return;
}
FMLNetworkConstants.handshakeChannel.reply(new FMLHandshakeMessages.C2SModListReply(), c.get());
@@ -168,7 +168,7 @@ public class FMLHandshakeHandler {
c.get().setPacketHandled(true);
if (!accepted) {
LOGGER.error(FMLHSMARKER, "Terminating connection with client, mismatched mod list");
c.get().getNetworkManager().closeChannel(new TextComponentString("Connection closed - mismatched mod channel list"));
c.get().getNetworkManager().closeChannel(new StringTextComponent("Connection closed - mismatched mod channel list"));
return;
}
LOGGER.debug(FMLHSMARKER, "Accepted client connection mod list");
@@ -217,7 +217,7 @@ public class FMLHandshakeHandler {
LOGGER.debug(FMLHSMARKER, "Registry load complete, continuing handshake.");
} else {
LOGGER.error(FMLHSMARKER, "Failed to load registry, closing connection.");
this.manager.closeChannel(new TextComponentString("Failed to synchronize registry data from server, closing connection"));
this.manager.closeChannel(new StringTextComponent("Failed to synchronize registry data from server, closing connection"));
}
return successfulConnection.get();
}
@@ -21,17 +21,22 @@ package net.minecraftforge.fml.network;
import io.netty.buffer.Unpooled;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScreenManager;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityTracker;
import net.minecraft.entity.EntityType;
import net.minecraft.inventory.container.ContainerType;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.ExtensionPoint;
import net.minecraftforge.fml.LogicalSidedProvider;
import net.minecraftforge.fml.ModList;
import net.minecraft.util.registry.IRegistry;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData;
import java.util.Optional;
@@ -40,6 +45,13 @@ import java.util.function.Supplier;
public class FMLPlayMessages
{
/**
* Used to spawn a custom entity without the same restrictions as
* {@link net.minecraft.network.play.server.SSpawnObjectPacket} or {@link net.minecraft.network.play.server.SSpawnMobPacket}
*
* Ensure your {@link EntityType} registration supplies a {@link EntityType.Builder#customClientFactory} or the
* mob won't actually spawn on the client.
*/
public static class SpawnEntity
{
private final Entity entity;
@@ -48,13 +60,13 @@ public class FMLPlayMessages
private final UUID uuid;
private final double posX, posY, posZ;
private final byte pitch, yaw, headYaw;
private final short velX, velY, velZ;
private final int velX, velY, velZ;
private final PacketBuffer buf;
SpawnEntity(Entity e)
{
this.entity = e;
this.typeId = IRegistry.field_212629_r.getId(e.getType());
this.typeId = Registry.ENTITY_TYPE.getId(e.getType());
this.entityId = e.getEntityId();
this.uuid = e.getUniqueID();
this.posX = e.posX;
@@ -63,14 +75,18 @@ public class FMLPlayMessages
this.pitch = (byte) MathHelper.floor(e.rotationPitch * 256.0F / 360.0F);
this.yaw = (byte) MathHelper.floor(e.rotationYaw * 256.0F / 360.0F);
this.headYaw = (byte) (e.getRotationYawHead() * 256.0F / 360.0F);
this.velX = (short)(MathHelper.clamp(e.motionX, -3.9D, 3.9D) * 8000.0D);
this.velY = (short)(MathHelper.clamp(e.motionY, -3.9D, 3.9D) * 8000.0D);
this.velZ = (short)(MathHelper.clamp(e.motionZ, -3.9D, 3.9D) * 8000.0D);
Vec3d vec3d = e.func_213322_ci();
double d1 = MathHelper.clamp(vec3d.x, -3.9D, 3.9D);
double d2 = MathHelper.clamp(vec3d.y, -3.9D, 3.9D);
double d3 = MathHelper.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, short velX, short velY, short velZ, PacketBuffer buf)
byte pitch, byte yaw, byte headYaw, int velX, int velY, int velZ, PacketBuffer buf)
{
this.entity = null;
this.typeId = typeId;
@@ -119,43 +135,33 @@ public class FMLPlayMessages
buf.readByte(), buf.readByte(), buf.readByte(),
buf.readShort(), buf.readShort(), buf.readShort(),
buf
);
);
}
public static void handle(SpawnEntity msg, Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() -> {
EntityType<?> type = IRegistry.field_212629_r.get(msg.typeId);
EntityType<?> type = Registry.ENTITY_TYPE.getByValue(msg.typeId);
if (type == null)
{
throw new RuntimeException(String.format("Could not spawn entity (id %d) with unknown type at (%f, %f, %f)", msg.entityId, msg.posX, msg.posY, msg.posZ));
}
Optional<World> world = LogicalSidedProvider.CLIENTWORLD.get(ctx.get().getDirection().getReceptionSide());
Entity e = world.map(w->type.handleSpawnMessage(w, msg)).orElse(null);
Entity e = world.map(w->type.customClientSpawn(msg, w)).orElse(null);
if (e == null)
{
return;
}
EntityTracker.updateServerPosition(e, msg.posX, msg.posY, msg.posZ);
e.func_213312_b(msg.posX, msg.posY, msg.posZ);
e.setPositionAndRotation(msg.posX, msg.posY, msg.posZ, (msg.yaw * 360) / 256.0F, (msg.pitch * 360) / 256.0F);
e.setRotationYawHead((msg.headYaw * 360) / 256.0F);
e.setRenderYawOffset((msg.headYaw * 360) / 256.0F);
Entity[] parts = e.getParts();
if (parts != null)
{
int offset = msg.entityId - e.getEntityId();
for (Entity part : parts)
{
part.setEntityId(part.getEntityId() + offset);
}
}
e.setEntityId(msg.entityId);
e.setUniqueId(msg.uuid);
Minecraft.getInstance().world.addEntityToWorld(msg.entityId, e);
world.filter(ClientWorld.class::isInstance).ifPresent(w->((ClientWorld)w).func_217411_a(msg.entityId, e));
e.setVelocity(msg.velX / 8000.0, msg.velY / 8000.0, msg.velZ / 8000.0);
if (e instanceof IEntityAdditionalSpawnData)
{
@@ -168,47 +174,58 @@ public class FMLPlayMessages
public static class OpenContainer
{
private final ResourceLocation id;
private final int id;
private final int windowId;
private final ITextComponent name;
private final PacketBuffer additionalData;
OpenContainer(ResourceLocation id, int windowId, PacketBuffer additionalData)
OpenContainer(ContainerType<?> id, int windowId, ITextComponent name, PacketBuffer additionalData)
{
this(Registry.field_218366_G.getId(id), windowId, name, additionalData);
}
private OpenContainer(int id, int windowId, ITextComponent name, PacketBuffer additionalData)
{
this.id = id;
this.windowId = windowId;
this.name = name;
this.additionalData = additionalData;
}
public static void encode(OpenContainer msg, PacketBuffer buf)
{
buf.writeResourceLocation(msg.id);
buf.writeVarInt(msg.id);
buf.writeVarInt(msg.windowId);
buf.writeTextComponent(msg.name);
buf.writeByteArray(msg.additionalData.readByteArray());
}
public static OpenContainer decode(PacketBuffer buf)
{
return new OpenContainer(buf.readResourceLocation(), buf.readVarInt(), new PacketBuffer(Unpooled.wrappedBuffer(buf.readByteArray(32600))));
return new OpenContainer(buf.readVarInt(), buf.readVarInt(), buf.readTextComponent(), new PacketBuffer(Unpooled.wrappedBuffer(buf.readByteArray(32600))));
}
public static void handle(OpenContainer msg, Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() -> ModList.get().getModContainerById(msg.id.getNamespace()).ifPresent(mc->
mc.getCustomExtension(ExtensionPoint.GUIFACTORY).map(f -> f.apply(msg)).ifPresent(gui-> {
Minecraft.getInstance().displayGuiScreen(gui);
Minecraft.getInstance().player.openContainer.windowId = msg.windowId;
})));
ctx.get().enqueueWork(() -> {
// TODO extend IScreenFactory to allow for extra data
ScreenManager.func_216909_a(msg.getType(), Minecraft.getInstance(), msg.getWindowId(), msg.getName());
});
ctx.get().setPacketHandled(true);
}
public final ResourceLocation getId() {
return this.id;
public final ContainerType<?> getType() {
return Registry.field_218366_G.getByValue(this.id);
}
public int getWindowId() {
return windowId;
}
public ITextComponent getName() {
return name;
}
public PacketBuffer getAdditionalData() {
return additionalData;
}
@@ -26,7 +26,7 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSyntaxException;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.ExtensionPoint;
import net.minecraftforge.fml.ModList;
@@ -85,17 +85,17 @@ public class FMLStatusPing {
public static class Serializer {
public static FMLStatusPing deserialize(JsonObject forgeData, JsonDeserializationContext ctx) {
try {
final Map<ResourceLocation, Pair<String, Boolean>> channels = StreamSupport.stream(JsonUtils.getJsonArray(forgeData, "channels").spliterator(), false).
final Map<ResourceLocation, Pair<String, Boolean>> channels = StreamSupport.stream(JSONUtils.getJsonArray(forgeData, "channels").spliterator(), false).
map(JsonElement::getAsJsonObject).
collect(Collectors.toMap(jo -> new ResourceLocation(JsonUtils.getString(jo, "res")),
jo -> Pair.of(JsonUtils.getString(jo, "version"), JsonUtils.getBoolean(jo, "required")))
collect(Collectors.toMap(jo -> new ResourceLocation(JSONUtils.getString(jo, "res")),
jo -> Pair.of(JSONUtils.getString(jo, "version"), JSONUtils.getBoolean(jo, "required")))
);
final Map<String, String> mods = StreamSupport.stream(JsonUtils.getJsonArray(forgeData, "mods").spliterator(), false).
final Map<String, String> mods = StreamSupport.stream(JSONUtils.getJsonArray(forgeData, "mods").spliterator(), false).
map(JsonElement::getAsJsonObject).
collect(Collectors.toMap(jo -> JsonUtils.getString(jo, "modId"), jo->JsonUtils.getString(jo, "modmarker")));
collect(Collectors.toMap(jo -> JSONUtils.getString(jo, "modId"), jo->JSONUtils.getString(jo, "modmarker")));
final int remoteFMLVersion = JsonUtils.getInt(forgeData, "fmlNetworkVersion");
final int remoteFMLVersion = JSONUtils.getInt(forgeData, "fmlNetworkVersion");
return new FMLStatusPing(channels, mods, remoteFMLVersion);
} catch (JsonSyntaxException e) {
LOGGER.debug(NETWORK, "Encountered an error parsing status ping data", e);
@@ -20,12 +20,12 @@
package net.minecraftforge.fml.network;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceArrayMap;
import net.minecraft.network.Packet;
import net.minecraft.network.IPacket;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.login.client.CPacketCustomPayloadLogin;
import net.minecraft.network.login.server.SPacketCustomPayloadLogin;
import net.minecraft.network.play.client.CPacketCustomPayload;
import net.minecraft.network.play.server.SPacketCustomPayload;
import net.minecraft.network.login.client.CCustomPayloadLoginPacket;
import net.minecraft.network.login.server.SCustomPayloadLoginPacket;
import net.minecraft.network.play.client.CCustomPayloadPacket;
import net.minecraft.network.play.server.SCustomPayloadPlayPacket;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.unsafe.UnsafeHacks;
@@ -37,13 +37,13 @@ import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public interface ICustomPacket<T extends Packet<?>> {
public interface ICustomPacket<T extends IPacket<?>> {
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
enum Fields {
CPACKETCUSTOMPAYLOAD(CPacketCustomPayload.class),
SPACKETCUSTOMPAYLOAD(SPacketCustomPayload.class),
CPACKETCUSTOMLOGIN(CPacketCustomPayloadLogin.class),
SPACKETCUSTOMLOGIN(SPacketCustomPayloadLogin.class),
CPACKETCUSTOMPAYLOAD(CCustomPayloadPacket.class),
SPACKETCUSTOMPAYLOAD(SCustomPayloadPlayPacket.class),
CPACKETCUSTOMLOGIN(CCustomPayloadLoginPacket.class),
SPACKETCUSTOMLOGIN(SCustomPayloadLoginPacket.class),
;
static final Reference2ReferenceArrayMap<Class<?>, Fields> lookup;
@@ -20,12 +20,12 @@
package net.minecraftforge.fml.network;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceArrayMap;
import net.minecraft.network.Packet;
import net.minecraft.network.IPacket;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.login.client.CPacketCustomPayloadLogin;
import net.minecraft.network.login.server.SPacketCustomPayloadLogin;
import net.minecraft.network.play.client.CPacketCustomPayload;
import net.minecraft.network.play.server.SPacketCustomPayload;
import net.minecraft.network.login.client.CCustomPayloadLoginPacket;
import net.minecraft.network.login.server.SCustomPayloadLoginPacket;
import net.minecraft.network.play.client.CCustomPayloadPacket;
import net.minecraft.network.play.server.SCustomPayloadPlayPacket;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.unsafe.UnsafeHacks;
@@ -39,24 +39,24 @@ import java.util.stream.Stream;
public enum NetworkDirection
{
PLAY_TO_SERVER(NetworkEvent.ClientCustomPayloadEvent::new, LogicalSide.CLIENT, CPacketCustomPayload.class, 1),
PLAY_TO_CLIENT(NetworkEvent.ServerCustomPayloadEvent::new, LogicalSide.SERVER, SPacketCustomPayload.class, 0),
LOGIN_TO_SERVER(NetworkEvent.ClientCustomPayloadLoginEvent::new, LogicalSide.CLIENT, CPacketCustomPayloadLogin.class, 3),
LOGIN_TO_CLIENT(NetworkEvent.ServerCustomPayloadLoginEvent::new, LogicalSide.SERVER, SPacketCustomPayloadLogin.class, 2);
PLAY_TO_SERVER(NetworkEvent.ClientCustomPayloadEvent::new, LogicalSide.CLIENT, CCustomPayloadPacket.class, 1),
PLAY_TO_CLIENT(NetworkEvent.ServerCustomPayloadEvent::new, LogicalSide.SERVER, SCustomPayloadPlayPacket.class, 0),
LOGIN_TO_SERVER(NetworkEvent.ClientCustomPayloadLoginEvent::new, LogicalSide.CLIENT, CCustomPayloadLoginPacket.class, 3),
LOGIN_TO_CLIENT(NetworkEvent.ServerCustomPayloadLoginEvent::new, LogicalSide.SERVER, SCustomPayloadLoginPacket.class, 2);
private final BiFunction<ICustomPacket<?>, Supplier<NetworkEvent.Context>, NetworkEvent> eventSupplier;
private final LogicalSide logicalSide;
private final Class<? extends Packet> packetClass;
private final Class<? extends IPacket> packetClass;
private final int otherWay;
private static final Reference2ReferenceArrayMap<Class<? extends Packet>, NetworkDirection> packetLookup;
private static final Reference2ReferenceArrayMap<Class<? extends IPacket>, NetworkDirection> packetLookup;
static {
packetLookup = Stream.of(values()).
collect(Collectors.toMap(NetworkDirection::getPacketClass, Function.identity(), (m1,m2)->m1, Reference2ReferenceArrayMap::new));
}
NetworkDirection(BiFunction<ICustomPacket<?>, Supplier<NetworkEvent.Context>, NetworkEvent> eventSupplier, LogicalSide logicalSide, Class<? extends Packet> clazz, int i)
NetworkDirection(BiFunction<ICustomPacket<?>, Supplier<NetworkEvent.Context>, NetworkEvent> eventSupplier, LogicalSide logicalSide, Class<? extends IPacket> clazz, int i)
{
this.eventSupplier = eventSupplier;
this.logicalSide = logicalSide;
@@ -64,7 +64,7 @@ public enum NetworkDirection
this.otherWay = i;
}
private Class<? extends Packet> getPacketClass() {
private Class<? extends IPacket> getPacketClass() {
return packetClass;
}
public static <T extends ICustomPacket<?>> NetworkDirection directionFor(Class<T> customPacket)
@@ -87,7 +87,7 @@ public enum NetworkDirection
public LogicalSide getReceptionSide() { return reply().logicalSide; };
@SuppressWarnings("unchecked")
public <T extends Packet<?>> ICustomPacket<T> buildPacket(Pair<PacketBuffer,Integer> packetData, ResourceLocation channelName)
public <T extends IPacket<?>> ICustomPacket<T> buildPacket(Pair<PacketBuffer,Integer> packetData, ResourceLocation channelName)
{
ICustomPacket<T> packet = (ICustomPacket<T>)UnsafeHacks.newInstance(getPacketClass());
packet.setName(channelName);
@@ -22,16 +22,17 @@ package net.minecraftforge.fml.network;
import javax.annotation.Nullable;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.network.INetHandler;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.network.play.ServerPlayNetHandler;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.IThreadListener;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.concurrent.ThreadTaskExecutor;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.LogicalSidedProvider;
@@ -177,19 +178,23 @@ public class NetworkEvent extends Event
@SuppressWarnings("unchecked")
public <V> ListenableFuture<V> enqueueWork(Runnable runnable) {
return (ListenableFuture<V>)LogicalSidedProvider.WORKQUEUE.<IThreadListener>get(getDirection().getReceptionSide()).addScheduledTask(runnable);
ListenableFutureTask<V> f = ListenableFutureTask.create(runnable, null);
LogicalSidedProvider.WORKQUEUE.<ThreadTaskExecutor<?> >get(getDirection().getReceptionSide()).execute(f);
return f;
}
/**
* When available, gets the sender for packets that are sent from a client to the server.
*/
@Nullable
public EntityPlayerMP getSender()
public ServerPlayerEntity getSender()
{
INetHandler netHandler = networkManager.getNetHandler();
if (netHandler instanceof NetHandlerPlayServer)
if (netHandler instanceof ServerPlayNetHandler)
{
NetHandlerPlayServer netHandlerPlayServer = (NetHandlerPlayServer) netHandler;
ServerPlayNetHandler netHandlerPlayServer = (ServerPlayNetHandler) netHandler;
return netHandlerPlayServer.player;
}
return null;
@@ -19,28 +19,30 @@
package net.minecraftforge.fml.network;
import io.netty.buffer.Unpooled;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.Container;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.handshake.client.CPacketHandshake;
import net.minecraft.network.NetHandlerLoginServer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IInteractionObject;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerContainerEvent;
import net.minecraftforge.fml.config.ConfigTracker;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.netty.buffer.Unpooled;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.ContainerType;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.network.IPacket;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.handshake.client.CHandshakePacket;
import net.minecraft.network.login.ServerLoginNetHandler;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerContainerEvent;
import net.minecraftforge.fml.config.ConfigTracker;
public class NetworkHooks
{
private static final Logger LOGGER = LogManager.getLogger();
@@ -55,13 +57,9 @@ public class NetworkHooks
return ConnectionType.forVersionFlag(connection.get().channel().attr(FMLNetworkConstants.FML_NETVERSION).get());
}
public static Packet<?> getEntitySpawningPacket(Entity entity)
public static IPacket<?> getEntitySpawningPacket(Entity entity)
{
if (!entity.getType().usesVanillaSpawning())
{
return FMLNetworkConstants.playChannel.toVanillaPacket(new FMLPlayMessages.SpawnEntity(entity), NetworkDirection.PLAY_TO_CLIENT);
}
return null;
return FMLNetworkConstants.playChannel.toVanillaPacket(new FMLPlayMessages.SpawnEntity(entity), NetworkDirection.PLAY_TO_CLIENT);
}
public static boolean onCustomPayload(final ICustomPacket<?> packet, final NetworkManager manager) {
@@ -69,7 +67,7 @@ public class NetworkHooks
map(ni->ni.dispatch(packet.getDirection(), packet, manager)).orElse(Boolean.FALSE);
}
public static void registerServerLoginChannel(NetworkManager manager, CPacketHandshake packet)
public static void registerServerLoginChannel(NetworkManager manager, CHandshakePacket packet)
{
manager.channel().attr(FMLNetworkConstants.FML_NETVERSION).set(packet.getFMLVersion());
FMLHandshakeHandler.registerHandshake(manager, NetworkDirection.LOGIN_TO_CLIENT);
@@ -91,7 +89,7 @@ public class NetworkHooks
}
}
public static boolean tickNegotiation(NetHandlerLoginServer netHandlerLoginServer, NetworkManager networkManager, EntityPlayerMP player)
public static boolean tickNegotiation(ServerLoginNetHandler netHandlerLoginServer, NetworkManager networkManager, ServerPlayerEntity player)
{
return FMLHandshakeHandler.tickLogin(networkManager);
}
@@ -109,7 +107,7 @@ public class NetworkHooks
* @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 openGui(EntityPlayerMP player, IInteractionObject containerSupplier)
public static void openGui(ServerPlayerEntity player, INamedContainerProvider containerSupplier)
{
openGui(player, containerSupplier, buf -> {});
}
@@ -128,7 +126,7 @@ public class NetworkHooks
* @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 openGui(EntityPlayerMP player, IInteractionObject containerSupplier, BlockPos pos)
public static void openGui(ServerPlayerEntity player, INamedContainerProvider containerSupplier, BlockPos pos)
{
openGui(player, containerSupplier, buf -> buf.writeBlockPos(pos));
}
@@ -147,10 +145,9 @@ public class NetworkHooks
* @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 openGui(EntityPlayerMP player, IInteractionObject containerSupplier, Consumer<PacketBuffer> extraDataWriter)
public static void openGui(ServerPlayerEntity player, INamedContainerProvider containerSupplier, Consumer<PacketBuffer> extraDataWriter)
{
if (player.world.isRemote) return;
ResourceLocation id = new ResourceLocation(containerSupplier.getGuiID());
player.closeContainer();
player.getNextWindowId();
int openContainerId = player.currentWindowId;
@@ -165,12 +162,12 @@ public class NetworkHooks
if (output.readableBytes() > 32600 || output.readableBytes() < 1) {
throw new IllegalArgumentException("Invalid PacketBuffer for openGui, found "+ output.readableBytes()+ " bytes");
}
FMLPlayMessages.OpenContainer msg = new FMLPlayMessages.OpenContainer(id, openContainerId, output);
Container c = containerSupplier.createMenu(openContainerId, player.inventory, player);
ContainerType<?> type = c.func_216957_a();
FMLPlayMessages.OpenContainer msg = new FMLPlayMessages.OpenContainer(type, openContainerId, containerSupplier.getDisplayName(), output);
FMLNetworkConstants.playChannel.sendTo(msg, player.connection.getNetworkManager(), NetworkDirection.PLAY_TO_CLIENT);
Container c = containerSupplier.createContainer(player.inventory, player);
player.openContainer = c;
player.openContainer.windowId = openContainerId;
player.openContainer.addListener(player);
MinecraftForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, c));
}
@@ -21,12 +21,12 @@ package net.minecraftforge.fml.network;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.IPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ServerChunkProvider;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.LogicalSidedProvider;
@@ -49,7 +49,7 @@ public class PacketDistributor<T> {
* <br/>
* {@link #with(Supplier)} Player
*/
public static final PacketDistributor<EntityPlayerMP> PLAYER = new PacketDistributor<>(PacketDistributor::playerConsumer, NetworkDirection.PLAY_TO_CLIENT);
public static final PacketDistributor<ServerPlayerEntity> PLAYER = new PacketDistributor<>(PacketDistributor::playerConsumer, NetworkDirection.PLAY_TO_CLIENT);
/**
* Send to everyone in the dimension specified in the Supplier
* <br/>
@@ -101,7 +101,7 @@ public class PacketDistributor<T> {
public static final class TargetPoint {
private final EntityPlayerMP excluded;
private final ServerPlayerEntity excluded;
private final double x;
private final double y;
private final double z;
@@ -118,7 +118,7 @@ public class PacketDistributor<T> {
* @param r2 Radius
* @param dim DimensionType
*/
public TargetPoint(final EntityPlayerMP excluded, final double x, final double y, final double z, final double r2, final DimensionType dim) {
public TargetPoint(final ServerPlayerEntity excluded, final double x, final double y, final double z, final double r2, final DimensionType dim) {
this.excluded = excluded;
this.x = x;
this.y = y;
@@ -167,14 +167,14 @@ public class PacketDistributor<T> {
*
*/
public static class PacketTarget {
private final Consumer<Packet<?>> packetConsumer;
private final Consumer<IPacket<?>> packetConsumer;
private final PacketDistributor<?> distributor;
PacketTarget(final Consumer<Packet<?>> packetConsumer, final PacketDistributor<?> distributor) {
PacketTarget(final Consumer<IPacket<?>> packetConsumer, final PacketDistributor<?> distributor) {
this.packetConsumer = packetConsumer;
this.distributor = distributor;
}
public void send(Packet<?> packet) {
public void send(IPacket<?> packet) {
packetConsumer.accept(packet);
}
@@ -184,10 +184,10 @@ public class PacketDistributor<T> {
}
private final BiFunction<PacketDistributor<T>, Supplier<T>, Consumer<Packet<?>>> functor;
private final BiFunction<PacketDistributor<T>, Supplier<T>, Consumer<IPacket<?>>> functor;
private final NetworkDirection direction;
public PacketDistributor(BiFunction<PacketDistributor<T>, Supplier<T>, Consumer<Packet<?>>> functor, NetworkDirection direction) {
public PacketDistributor(BiFunction<PacketDistributor<T>, Supplier<T>, Consumer<IPacket<?>>> functor, NetworkDirection direction) {
this.functor = functor;
this.direction = direction;
}
@@ -212,50 +212,50 @@ public class PacketDistributor<T> {
return new PacketTarget(functor.apply(this, ()->null), this);
}
private Consumer<Packet<?>> playerConsumer(final Supplier<EntityPlayerMP> entityPlayerMPSupplier) {
private Consumer<IPacket<?>> playerConsumer(final Supplier<ServerPlayerEntity> entityPlayerMPSupplier) {
return p -> entityPlayerMPSupplier.get().connection.netManager.sendPacket(p);
}
private Consumer<Packet<?>> playerListDimConsumer(final Supplier<DimensionType> dimensionTypeSupplier) {
private Consumer<IPacket<?>> playerListDimConsumer(final Supplier<DimensionType> dimensionTypeSupplier) {
return p->getServer().getPlayerList().sendPacketToAllPlayersInDimension(p, dimensionTypeSupplier.get());
}
private Consumer<Packet<?>> playerListAll(final Supplier<Void> voidSupplier) {
private Consumer<IPacket<?>> playerListAll(final Supplier<Void> voidSupplier) {
return p -> getServer().getPlayerList().sendPacketToAllPlayers(p);
}
private Consumer<Packet<?>> clientToServer(final Supplier<Void> voidSupplier) {
private Consumer<IPacket<?>> clientToServer(final Supplier<Void> voidSupplier) {
return p -> Minecraft.getInstance().getConnection().sendPacket(p);
}
private Consumer<Packet<?>> playerListPointConsumer(final Supplier<TargetPoint> targetPointSupplier) {
private Consumer<IPacket<?>> playerListPointConsumer(final Supplier<TargetPoint> targetPointSupplier) {
return p -> {
final TargetPoint tp = targetPointSupplier.get();
getServer().getPlayerList().sendToAllNearExcept(tp.excluded, tp.x, tp.y, tp.z, tp.r2, tp.dim, p);
};
}
private Consumer<Packet<?>> trackingEntity(final Supplier<Entity> entitySupplier) {
private Consumer<IPacket<?>> trackingEntity(final Supplier<Entity> entitySupplier) {
return p-> {
final Entity entity = entitySupplier.get();
getServer().getWorld(entity.dimension).getEntityTracker().sendToTracking(entity, p);
((ServerChunkProvider)entity.getEntityWorld().getChunkProvider()).func_217218_b(entity, p);
};
}
private Consumer<Packet<?>> trackingEntityAndSelf(final Supplier<Entity> entitySupplier) {
private Consumer<IPacket<?>> trackingEntityAndSelf(final Supplier<Entity> entitySupplier) {
return p-> {
final Entity entity = entitySupplier.get();
getServer().getWorld(entity.dimension).getEntityTracker().sendToTrackingAndSelf(entity, p);
((ServerChunkProvider)entity.getEntityWorld().getChunkProvider()).func_217216_a(entity, p);
};
}
private Consumer<Packet<?>> trackingChunk(final Supplier<Chunk> chunkPosSupplier) {
private Consumer<IPacket<?>> trackingChunk(final Supplier<Chunk> chunkPosSupplier) {
return p -> {
final Chunk chunk = chunkPosSupplier.get();
((WorldServer)chunk.getWorld()).getPlayerChunkMap().getEntry(chunk.x, chunk.z).sendPacket(p);
((ServerChunkProvider)chunk.getWorld().getChunkProvider()).field_217237_a.func_219097_a(chunk.getPos(), false).forEach(e -> e.connection.sendPacket(p));
};
}
private Consumer<Packet<?>> networkManagerList(final Supplier<List<NetworkManager>> nmListSupplier) {
private Consumer<IPacket<?>> networkManagerList(final Supplier<List<NetworkManager>> nmListSupplier) {
return p -> nmListSupplier.get().forEach(nm->nm.sendPacket(p));
}
@@ -22,7 +22,7 @@ package net.minecraftforge.fml.network.simple;
import io.netty.buffer.Unpooled;
import net.minecraft.client.Minecraft;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.IPacket;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.dimension.DimensionType;
import net.minecraftforge.fml.network.*;
@@ -102,7 +102,7 @@ public class SimpleChannel
target.send(toVanillaPacket(message, target.getDirection()));
}
public <MSG> Packet<?> toVanillaPacket(MSG message, NetworkDirection direction)
public <MSG> IPacket<?> toVanillaPacket(MSG message, NetworkDirection direction)
{
return direction.buildPacket(toBuffer(message), instance.getChannelName()).getThis();
}
@@ -19,7 +19,7 @@
package net.minecraftforge.fml.packs;
import net.minecraft.resources.AbstractResourcePack;
import net.minecraft.resources.ResourcePack;
import net.minecraft.resources.ResourcePackInfo;
import net.minecraft.resources.ResourcePackType;
import net.minecraft.util.ResourceLocation;
@@ -52,7 +52,7 @@ import org.apache.logging.log4j.Logger;
import static net.minecraftforge.fml.Logging.CORE;
public class ModFileResourcePack extends AbstractResourcePack
public class ModFileResourcePack extends ResourcePack
{
private static final Logger LOGGER = LogManager.getLogger();
private final ModFile modFile;
@@ -70,7 +70,7 @@ public class ResourcePackLoader
{
IModInfo mod = e.getKey().getModInfos().get(0);
final String name = "mod:" + mod.getModId();
final T packInfo = ResourcePackInfo.func_195793_a(name, true, e::getValue, factory, ResourcePackInfo.Priority.BOTTOM);
final T packInfo = ResourcePackInfo.createResourcePack(name, true, e::getValue, factory, ResourcePackInfo.Priority.BOTTOM);
if (packInfo == null) {
// Vanilla only logs an error, instead of propagating, so handle null and warn that something went wrong
ModLoader.get().addWarning(new ModLoadingWarning(mod, ModLoadingStage.ERROR, "fml.modloading.brokenresources", e.getKey()));
@@ -24,7 +24,7 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.resources.IResource;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.ForgeI18n;
import org.apache.commons.io.IOUtils;
@@ -65,10 +65,10 @@ public class LanguageHook
try
{
JsonElement jsonelement = GSON.fromJson(new InputStreamReader(inputstream, StandardCharsets.UTF_8), JsonElement.class);
JsonObject jsonobject = JsonUtils.getJsonObject(jsonelement, "strings");
JsonObject jsonobject = JSONUtils.getJsonObject(jsonelement, "strings");
jsonobject.entrySet().forEach(entry -> {
String s = PATTERN.matcher(JsonUtils.getString(entry.getValue(), entry.getKey())).replaceAll("%$1s");
String s = PATTERN.matcher(JSONUtils.getString(entry.getValue(), entry.getKey())).replaceAll("%$1s");
modTable.put(entry.getKey(), s);
});
}
@@ -19,12 +19,12 @@
package net.minecraftforge.fml.server;
import net.minecraft.network.EnumConnectionState;
import net.minecraft.network.ProtocolType;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.handshake.client.CPacketHandshake;
import net.minecraft.network.login.server.SPacketDisconnectLogin;
import net.minecraft.network.handshake.client.CHandshakePacket;
import net.minecraft.network.login.server.SDisconnectLoginPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.DistExecutor;
@@ -113,17 +113,17 @@ public class ServerLifecycleHooks
}
private static AtomicBoolean allowLogins = new AtomicBoolean(false);
public static boolean handleServerLogin(final CPacketHandshake packet, final NetworkManager manager) {
public static boolean handleServerLogin(final CHandshakePacket packet, final NetworkManager manager) {
if (!allowLogins.get())
{
TextComponentString text = new TextComponentString("Server is still starting! Please wait before reconnecting.");
StringTextComponent text = new StringTextComponent("Server is still starting! Please wait before reconnecting.");
LOGGER.info(SERVERHOOKS,"Disconnecting Player (server is still starting): {}", text.getUnformattedComponentText());
manager.sendPacket(new SPacketDisconnectLogin(text));
manager.sendPacket(new SDisconnectLoginPacket(text));
manager.closeChannel(text);
return false;
}
if (packet.getRequestedState() == EnumConnectionState.LOGIN) {
if (packet.getRequestedState() == ProtocolType.LOGIN) {
final ConnectionType connectionType = ConnectionType.forVersionFlag(packet.getFMLVersion());
final int versionNumber = connectionType.getFMLVersionNumber(packet.getFMLVersion());
@@ -138,7 +138,7 @@ public class ServerLifecycleHooks
}
}
if (packet.getRequestedState() == EnumConnectionState.STATUS) return true;
if (packet.getRequestedState() == ProtocolType.STATUS) return true;
NetworkHooks.registerServerLoginChannel(manager, packet);
return true;
@@ -146,10 +146,10 @@ public class ServerLifecycleHooks
}
private static void rejectConnection(final NetworkManager manager, ConnectionType type, String message) {
manager.setConnectionState(EnumConnectionState.LOGIN);
manager.setConnectionState(ProtocolType.LOGIN);
LOGGER.info(SERVERHOOKS, "Disconnecting {} connection attempt: ", type, message);
TextComponentString text = new TextComponentString(message);
manager.sendPacket(new SPacketDisconnectLogin(text));
StringTextComponent text = new StringTextComponent(message);
manager.sendPacket(new SDisconnectLoginPacket(text));
manager.closeChannel(text);
}