From 4fc368135d244d56a257bf8686b6a71a78c09154 Mon Sep 17 00:00:00 2001 From: D-Cysteine <54219287+D-Cysteine@users.noreply.github.com> Date: Sat, 16 Oct 2021 11:31:43 -0600 Subject: [PATCH] Fix height hack and add ordering config (#165) * Fix height hack and add ordering config * Use AutoCloseable for height hack * Address comments --- build.properties | 2 +- resources/assets/nei/csv/handlers.csv | 2 +- src/codechicken/nei/ClientHandler.java | 98 ++++++++++++++- src/codechicken/nei/NEIClientConfig.java | 35 +++++- src/codechicken/nei/NEIModContainer.java | 4 +- .../nei/recipe/GuiCraftingRecipe.java | 3 +- src/codechicken/nei/recipe/GuiRecipe.java | 118 ++++++++++++------ src/codechicken/nei/recipe/GuiRecipeTab.java | 5 +- .../nei/recipe/GuiUsageRecipe.java | 3 +- 9 files changed, 220 insertions(+), 50 deletions(-) diff --git a/build.properties b/build.properties index e62aba87..4f1d2dd2 100644 --- a/build.properties +++ b/build.properties @@ -2,4 +2,4 @@ mc_version=1.7.10 forge_version=10.13.4.1614-1.7.10 ccl_version=1.1.3.138 ccc_version=1.0.7.+ -mod_version=2.1.13-GTNH +mod_version=2.1.14-GTNH diff --git a/resources/assets/nei/csv/handlers.csv b/resources/assets/nei/csv/handlers.csv index d861d05d..247df0ba 100644 --- a/resources/assets/nei/csv/handlers.csv +++ b/resources/assets/nei/csv/handlers.csv @@ -170,7 +170,7 @@ ic2.neiIntegration.core.recipehandler.BlockCutterRecipeHandler,IndustrialCraft 2 ic2.neiIntegration.core.recipehandler.CentrifugeRecipeHandler,IndustrialCraft 2,IC2:blockMachine2:3,,IC2,TRUE,,,65,,5,,,,,, ic2.neiIntegration.core.recipehandler.CompressorRecipeHandler,IndustrialCraft 2,IC2:blockMachine:5,,IC2,TRUE,,,65,,5,,,,,, ic2.neiIntegration.core.recipehandler.ExtractorRecipeHandler,IndustrialCraft 2,IC2:blockMachine:4,,IC2,TRUE,,,65,,5,,,,,, -ic2.neiIntegration.core.recipehandler.FluidCannerRecipeHandler,IndustrialCraft 2,IC2:blockMachine:6,,IC2,TRUE,,,65,,5,,,,,, +ic2.neiIntegration.core.recipehandler.FluidCannerRecipeHandler,IndustrialCraft 2,IC2:blockMachine:6,,IC2,TRUE,,,75,,4,,,,,, ic2.neiIntegration.core.recipehandler.LatheRecipeHandler,IndustrialCraft 2,IC2:blockMachine3:8,,IC2,TRUE,,,65,,5,,,,,, ic2.neiIntegration.core.recipehandler.MaceratorRecipeHandler,IndustrialCraft 2,IC2:blockMachine:3,,IC2,TRUE,,,65,,5,,,,,, ic2.neiIntegration.core.recipehandler.MetalFormerRecipeHandlerCutting,IndustrialCraft 2,IC2:blockMachine2:4,,IC2,TRUE,,,55,,6,,,,,, diff --git a/src/codechicken/nei/ClientHandler.java b/src/codechicken/nei/ClientHandler.java index 9d48955e..a8d9cda8 100644 --- a/src/codechicken/nei/ClientHandler.java +++ b/src/codechicken/nei/ClientHandler.java @@ -5,6 +5,8 @@ import codechicken.core.GuiModListScroll; import codechicken.lib.packet.PacketCustom; import codechicken.nei.api.API; import codechicken.nei.api.ItemInfo; +import codechicken.nei.recipe.GuiRecipeTab; +import com.google.common.collect.Lists; import cpw.mods.fml.client.CustomModLoadingErrorDisplayException; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Loader; @@ -24,12 +26,19 @@ import net.minecraft.entity.item.EntityItem; import net.minecraft.world.World; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.common.MinecraftForge; +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; import org.apache.commons.io.IOUtils; +import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -43,6 +52,21 @@ public class ClientHandler private static String[] defaultSerialHandlers = { "WayofTime.alchemicalWizardry.client.nei.NEIAlchemyRecipeHandler" }; + private static String[] defaultHeightHackHandlers = { + "ic2.neiIntegration.core.recipehandler.FluidCannerRecipeHandler", + "tconstruct.plugins.nei.RecipeHandlerAlloying", + "tconstruct.plugins.nei.RecipeHandlerCastingBasin", + "tconstruct.plugins.nei.RecipeHandlerCastingTable", + "tconstruct.plugins.nei.RecipeHandlerMelting", + }; + private static String[] defaultHandlerOrdering = { + "# Each line in this file should either be a comment (starts with '#') or an ordering.", + "# Ordering lines are ,.", + "# Handlers will be sorted in order of number ascending, so smaller numbers first.", + "# Any handlers that are missing from this file will be assigned to 0.", + "# Negative numbers are fine.", + "# If you delete this file, it will be regenerated with all registered handler IDs.", + }; private static ClientHandler instance; private ArrayList SMPmagneticItems = new ArrayList<>(); @@ -128,6 +152,7 @@ public class ClientHandler public static void preInit() { loadSerialHandlers(); + loadHeightHackHandlers(); ItemInfo.preInit(); } @@ -148,7 +173,26 @@ public class ClientHandler } catch (IOException e) { NEIClientConfig.logger.error("Failed to load serial handlers from file {}", file, e); } - + } + + public static void loadHeightHackHandlers() { + File file = NEIClientConfig.heightHackHandlersFile; + if (!file.exists()) { + try (FileWriter writer = new FileWriter(file)) { + NEIClientConfig.logger.info("Creating default height hack handlers list {}", file); + Collection toSave = Loader.isModLoaded("dreamcraft") ? Collections.singletonList("") : Arrays.asList(defaultHeightHackHandlers); + IOUtils.writeLines(toSave, "\n", writer); + } catch (IOException e) { + NEIClientConfig.logger.error("Failed to save default height hack handlers list to file {}", file, e); + } + } + + try (FileReader reader = new FileReader(file)) { + NEIClientConfig.logger.info("Loading height hack handlers from file {}", file); + NEIClientConfig.heightHackHandlers = new HashSet<>(IOUtils.readLines(reader)); + } catch (IOException e) { + NEIClientConfig.logger.error("Failed to load height hack handlers from file {}", file, e); + } } public static void load() { @@ -164,6 +208,58 @@ public class ClientHandler WorldOverlayRenderer.load(); } + public static void postInit() { + loadHandlerOrdering(); + } + + public static void loadHandlerOrdering() { + File file = NEIClientConfig.handlerOrderingFile; + if (!file.exists()) { + try (FileWriter writer = new FileWriter(file)) { + NEIClientConfig.logger.info("Creating default handler ordering CSV {}", file); + + List toWrite = Lists.newArrayList(defaultHandlerOrdering); + GuiRecipeTab.handlerMap.keySet().stream() + .sorted() + .forEach(handlerId -> toWrite.add(String.format("%s,0", handlerId))); + + IOUtils.writeLines(toWrite, "\n", writer); + } catch (IOException e) { + NEIClientConfig.logger.error("Failed to save default handler ordering to file {}", file, e); + } + } + + URL url; + try { + url = file.toURI().toURL(); + } catch (MalformedURLException e) { + NEIClientConfig.logger.info("Invalid URL for handler ordering CSV."); + e.printStackTrace(); + return; + } + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) { + NEIClientConfig.logger.info("Loading handler ordering from file {}", file); + CSVParser csvParser = CSVFormat.EXCEL.withCommentMarker('#').parse(reader); + for (CSVRecord record : csvParser) { + final String handlerId = record.get(0); + + int ordering; + try { + ordering = Integer.parseInt(record.get(1)); + } catch (NumberFormatException e) { + NEIClientConfig.logger.error("Error parsing CSV record {}: {}", record, e); + continue; + } + + NEIClientConfig.handlerOrdering.put(handlerId, ordering); + } + } catch (Exception e) { + NEIClientConfig.logger.info("Error parsing CSV"); + e.printStackTrace(); + } + } + @SubscribeEvent public void tickEvent(TickEvent.ClientTickEvent event) { if(event.phase == Phase.END) diff --git a/src/codechicken/nei/NEIClientConfig.java b/src/codechicken/nei/NEIClientConfig.java index e3a9a113..048d38cf 100644 --- a/src/codechicken/nei/NEIClientConfig.java +++ b/src/codechicken/nei/NEIClientConfig.java @@ -26,8 +26,11 @@ import codechicken.nei.config.OptionToggleButtonBoubs; import codechicken.nei.config.OptionUtilities; import codechicken.nei.event.NEIConfigsLoadedEvent; import codechicken.nei.recipe.GuiRecipeTab; +import codechicken.nei.recipe.IRecipeHandler; import codechicken.nei.recipe.RecipeInfo; +import codechicken.nei.recipe.TemplateRecipeHandler; import codechicken.obfuscator.ObfuscationRun; +import com.google.common.base.Objects; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.item.ItemStack; @@ -40,8 +43,11 @@ import org.apache.logging.log4j.Logger; import org.lwjgl.input.Keyboard; import java.io.File; +import java.util.Comparator; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.function.Function; public class NEIClientConfig { private static boolean configLoaded; @@ -56,10 +62,35 @@ public class NEIClientConfig { public static final File bookmarkFile = new File(configDir, "bookmarks.ini"); public static final File handlerFile = new File(configDir, "handlers.csv"); public static final File serialHandlersFile = new File(configDir, "serialhandlers.cfg"); + public static final File heightHackHandlersFile = new File(configDir, "heighthackhandlers.cfg"); + public static final File handlerOrderingFile = new File(configDir, "handlerordering.csv"); // Set of handlers that need to be run in serial - public static HashSet serialHandlers = new HashSet<>(); - + public static HashSet serialHandlers = new HashSet<>(); + + // Set of handler ID of handlers that need the hack in GuiRecipe.startHeightHack(). + public static HashSet heightHackHandlers = new HashSet<>(); + + // Map of handler ID to sort order. + // Handlers will be sorted in ascending order, so smaller numbers show up earlier. + // Any handler not in the map will be assigned to 0, and negative numbers are fine. + public static HashMap handlerOrdering = new HashMap<>(); + + // Function that extracts the handler ID from a handler, with special logic for + // TemplateRecipeHandler: prefer using the overlay ID if it exists. + public static final Function HANDLER_ID_FUNCTION = + handler -> handler instanceof TemplateRecipeHandler + ? Objects.firstNonNull( + ((TemplateRecipeHandler) handler).getOverlayIdentifier(), + handler.getHandlerId()) + : handler.getHandlerId(); + + // Comparator that compares handlers using the handlerOrdering map. + public static final Comparator HANDLER_COMPARATOR = + Comparator.comparingInt( + handler -> handlerOrdering.getOrDefault( + HANDLER_ID_FUNCTION.apply(handler), 0)); + public static ItemStack[] creativeInv; diff --git a/src/codechicken/nei/NEIModContainer.java b/src/codechicken/nei/NEIModContainer.java index 0646fa8f..c25b4aeb 100644 --- a/src/codechicken/nei/NEIModContainer.java +++ b/src/codechicken/nei/NEIModContainer.java @@ -16,8 +16,8 @@ import cpw.mods.fml.common.MetadataCollection; import cpw.mods.fml.common.ModMetadata; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLInterModComms; -import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; +import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.versioning.ArtifactVersion; import cpw.mods.fml.common.versioning.VersionParser; import cpw.mods.fml.common.versioning.VersionRange; @@ -99,6 +99,8 @@ public class NEIModContainer extends DummyModContainer public void postInit(FMLPostInitializationEvent event) { if (CommonUtils.isClient()) GuiRecipeTab.loadHandlerInfo(); + + ClientHandler.postInit(); } @Subscribe diff --git a/src/codechicken/nei/recipe/GuiCraftingRecipe.java b/src/codechicken/nei/recipe/GuiCraftingRecipe.java index 3711a258..9526898e 100644 --- a/src/codechicken/nei/recipe/GuiCraftingRecipe.java +++ b/src/codechicken/nei/recipe/GuiCraftingRecipe.java @@ -8,7 +8,6 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import java.util.ArrayList; -import java.util.Arrays; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; @@ -44,6 +43,8 @@ public class GuiCraftingRecipe extends GuiRecipe if (handlers.isEmpty()) return false; + handlers.sort(NEIClientConfig.HANDLER_COMPARATOR); + mc.displayGuiScreen(new GuiCraftingRecipe(prevscreen, handlers)); return true; } diff --git a/src/codechicken/nei/recipe/GuiRecipe.java b/src/codechicken/nei/recipe/GuiRecipe.java index 8029ee53..022ff6b0 100644 --- a/src/codechicken/nei/recipe/GuiRecipe.java +++ b/src/codechicken/nei/recipe/GuiRecipe.java @@ -94,6 +94,42 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve } + /** + * Many old mods assumed a fixed NEI window height of {@code 166} pixels. Now that this is no + * longer the case, their fluid mouseover handling is broken. This helper class fixes these old + * mods by hacking the {@link #height} property's value so that these old mods' calculations + * return the correct value for the new height. + * + *

This class is an {@link AutoCloseable} so that it can be used with try-with-resources, + * which will ensure that {@link #height} is returned to the correct value afterwards. + */ + private class HeightHack implements AutoCloseable { + private final int trueHeight; + + private HeightHack() { + trueHeight = height; + + if (NEIClientConfig.heightHackHandlers.contains(handler.getHandlerId())) { + // The old mods use the calculation ((height - 166) / 2) to compute the y-value of + // the top edge of the NEI window. + // guiTop is exactly that: the y-value of the top edge of the NEI window. + // So we set height to be equal to the inverse of this calculation, applied to + // guiTop, so that old mods get the right result back when they use this calculation. + height = (2 * guiTop) + 166; + + // For reference, in case we ever need to modify width as well: + // the legacy calculation used for width is ((width - 176) / 2), which should + // evaluate to be equal to guiWidth (the x-value of the left edge of the NEI window). + // So if we wanted to override width as well, we'd do this: + // width = (2 * guiWidth) + 176; + } + } + + @Override + public void close() { + height = trueHeight; + } + } @Override @SuppressWarnings("unchecked") @@ -129,8 +165,6 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve recipeTabs.initLayout(); refreshPage(); - - } @SuppressWarnings("unchecked") @@ -196,9 +230,11 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve if (GuiContainerManager.getManager(this).lastKeyTyped(i, c)) return; - for (int recipe : getRecipeIndices()) - if (handler.keyTyped(this, c, i, recipe)) - return; + try (HeightHack heightHack = new HeightHack()) { + for (int recipe : getRecipeIndices()) + if (handler.keyTyped(this, c, i, recipe)) + return; + } if (i == mc.gameSettings.keyBindInventory.getKeyCode()) mc.displayGuiScreen(firstGui); @@ -217,16 +253,25 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve @Override protected void mouseClicked(int x, int y, int button) { - for (int recipe : getRecipeIndices()) - if (handler.mouseClicked(this, button, recipe)) - return; + try (HeightHack heightHack = new HeightHack()) { + for (int recipe : getRecipeIndices()) + if (handler.mouseClicked(this, button, recipe)) + return; + } + if (recipeTabs.mouseClicked(x, y, button)) return; + super.mouseClicked(x, y, button); } @Override public void mouseScrolled(int i) { + // Height hacking is not necessary here since mouse scrolling is a new feature, added in + // GTNH NEI. So no old mods will use this. Though not hacking the height here does mean that + // the value of the height field will be different from in other mouseover methods, which + // could be confusing... + for (int recipe : getRecipeIndices()) if (handler.mouseScrolled(this, i, recipe)) return; @@ -268,27 +313,18 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve @Override public List handleTooltip(GuiContainer gui, int mousex, int mousey, List currenttip) { - /* - * Several mods try to figure out the relative mouse position for fluid tooltips. This worked fine - * when it was a static 166.. however now that we're scaling it this no longer works. Rather than - * patching the individual mods (so that we can be as compatible as possible), we'll just fake - * the height for their tooltip rendering. - */ - - // Begin Hax - final int oldHeight = this.height; - this.height = 166 + handlerInfo.getHeight() + 18 + (guiTop - 44) * 2; - for (int i : getRecipeIndices()) - currenttip = handler.handleTooltip(this, currenttip, i); + try (HeightHack heightHack = new HeightHack()) { + for (int i : getRecipeIndices()) + currenttip = handler.handleTooltip(this, currenttip, i); + } recipeTabs.handleTooltip(mousex, mousey, currenttip); - this.height = oldHeight; - // End Hax - return currenttip; } @Override public List handleItemTooltip(GuiContainer gui, ItemStack stack, int mousex, int mousey, List currenttip) { + // Height hacking is probably not needed as it doesn't look like any mods check mouse + // position for this method. for (int i : getRecipeIndices()) currenttip = handler.handleItemTooltip(this, stack, currenttip, i); @@ -436,21 +472,23 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve GL11.glPushMatrix(); GL11.glTranslatef(5, 32 + yShift, 0); - for (int i = page * recipesPerPage; i < handler.numRecipes() && i < (page + 1) * recipesPerPage; i++) { - handler.drawForeground(i); - if (drawItemPresence && isMouseOverOverlayButton(i - page * recipesPerPage) - && firstGui.inventorySlots != null) { - List ingredients = handler.getIngredientStacks(i); - if (itemPresenceCacheRecipe != i || itemPresenceCacheSlots == null || itemPresenceCacheSlots.size() != ingredients.size()) { - updateItemPresenceCache(i); - } - for (int j = 0; j < ingredients.size(); j++) { - PositionedStack stack = ingredients.get(j); - boolean isPresent = itemPresenceCacheSlots.get(j); - LayoutManager.drawItemPresenceOverlay(stack.relx, stack.rely, isPresent); + try (HeightHack heightHack = new HeightHack()) { + for (int i = page * recipesPerPage; i < handler.numRecipes() && i < (page + 1) * recipesPerPage; i++) { + handler.drawForeground(i); + if (drawItemPresence && isMouseOverOverlayButton(i - page * recipesPerPage) + && firstGui.inventorySlots != null) { + List ingredients = handler.getIngredientStacks(i); + if (itemPresenceCacheRecipe != i || itemPresenceCacheSlots == null || itemPresenceCacheSlots.size() != ingredients.size()) { + updateItemPresenceCache(i); + } + for (int j = 0; j < ingredients.size(); j++) { + PositionedStack stack = ingredients.get(j); + boolean isPresent = itemPresenceCacheSlots.get(j); + LayoutManager.drawItemPresenceOverlay(stack.relx, stack.rely, isPresent); + } } + GL11.glTranslatef(0, handlerInfo.getHeight(), 0); } - GL11.glTranslatef(0, handlerInfo.getHeight(), 0); } GL11.glPopMatrix(); } @@ -484,9 +522,11 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve GL11.glPushMatrix(); GL11.glTranslatef(j + 5, k + 32 + yShift, 0); - for (int i = page * recipesPerPage; i < handler.numRecipes() && i < (page + 1) * recipesPerPage; i++) { - handler.drawBackground(i); - GL11.glTranslatef(0, handlerInfo.getHeight(), 0); + try (HeightHack heightHack = new HeightHack()) { + for (int i = page * recipesPerPage; i < handler.numRecipes() && i < (page + 1) * recipesPerPage; i++) { + handler.drawBackground(i); + GL11.glTranslatef(0, handlerInfo.getHeight(), 0); + } } GL11.glPopMatrix(); } diff --git a/src/codechicken/nei/recipe/GuiRecipeTab.java b/src/codechicken/nei/recipe/GuiRecipeTab.java index dcbd3b0d..ecb37a28 100644 --- a/src/codechicken/nei/recipe/GuiRecipeTab.java +++ b/src/codechicken/nei/recipe/GuiRecipeTab.java @@ -209,9 +209,8 @@ public abstract class GuiRecipeTab extends Widget { return; } } - try { - BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); - CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(input); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) { + CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(reader); for (CSVRecord record : csvParser) { final String handler = record.get("handler"); final String modName = record.get("modName"); diff --git a/src/codechicken/nei/recipe/GuiUsageRecipe.java b/src/codechicken/nei/recipe/GuiUsageRecipe.java index 3668c9f4..92e3badf 100644 --- a/src/codechicken/nei/recipe/GuiUsageRecipe.java +++ b/src/codechicken/nei/recipe/GuiUsageRecipe.java @@ -8,7 +8,6 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import java.util.ArrayList; -import java.util.Arrays; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; @@ -44,6 +43,8 @@ public class GuiUsageRecipe extends GuiRecipe if (handlers.isEmpty()) return false; + handlers.sort(NEIClientConfig.HANDLER_COMPARATOR); + mc.displayGuiScreen(new GuiUsageRecipe(prevscreen, handlers)); return true; }