From 85d6247e132e306b03a474980bc2ed6adfd2a559 Mon Sep 17 00:00:00 2001 From: slprime Date: Sat, 2 Aug 2025 19:02:33 +0300 Subject: [PATCH] Custom Subsets in config; RecipeId Command --- .../java/codechicken/nei/NEIClientConfig.java | 1 + .../java/codechicken/nei/NEIController.java | 2 + .../java/codechicken/nei/SubsetWidget.java | 69 +++++ .../nei/commands/CommandBookmarkAdd.java | 3 +- .../nei/commands/CommandRecipeId.java | 268 ++++++++++++++++++ .../java/codechicken/nei/recipe/Recipe.java | 26 +- .../codechicken/nei/recipe/StackInfo.java | 5 +- .../java/codechicken/nei/util/NBTJson.java | 8 +- .../assets/nei/cfg/recipeidblacklist.cfg | 2 + 9 files changed, 373 insertions(+), 11 deletions(-) create mode 100644 src/main/java/codechicken/nei/commands/CommandRecipeId.java create mode 100644 src/main/resources/assets/nei/cfg/recipeidblacklist.cfg diff --git a/src/main/java/codechicken/nei/NEIClientConfig.java b/src/main/java/codechicken/nei/NEIClientConfig.java index f36d4bf7..79a92040 100644 --- a/src/main/java/codechicken/nei/NEIClientConfig.java +++ b/src/main/java/codechicken/nei/NEIClientConfig.java @@ -921,6 +921,7 @@ public class NEIClientConfig { }); RecipeCatalysts.loadCatalystInfo(); + SubsetWidget.loadCustomSubsets(); SubsetWidget.loadHidden(); CollapsibleItems.load(); ItemSorter.loadConfig(); diff --git a/src/main/java/codechicken/nei/NEIController.java b/src/main/java/codechicken/nei/NEIController.java index dd44a08c..2b52ba77 100644 --- a/src/main/java/codechicken/nei/NEIController.java +++ b/src/main/java/codechicken/nei/NEIController.java @@ -20,6 +20,7 @@ import codechicken.nei.api.IInfiniteItemHandler; import codechicken.nei.api.INEIGuiHandler; import codechicken.nei.api.ItemInfo; import codechicken.nei.commands.CommandBookmarkAdd; +import codechicken.nei.commands.CommandRecipeId; import codechicken.nei.guihook.GuiContainerManager; import codechicken.nei.guihook.IContainerInputHandler; import codechicken.nei.guihook.IContainerSlotClickHandler; @@ -66,6 +67,7 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu @SideOnly(Side.CLIENT) public static void registerClientCommands() { ClientCommandHandler.instance.registerCommand(new CommandBookmarkAdd()); + ClientCommandHandler.instance.registerCommand(new CommandRecipeId()); } public static void updateUnlimitedItems(InventoryPlayer inventory) { diff --git a/src/main/java/codechicken/nei/SubsetWidget.java b/src/main/java/codechicken/nei/SubsetWidget.java index 72886501..6cf43cfe 100644 --- a/src/main/java/codechicken/nei/SubsetWidget.java +++ b/src/main/java/codechicken/nei/SubsetWidget.java @@ -1,6 +1,7 @@ package codechicken.nei; import java.awt.Point; +import java.io.File; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; @@ -13,6 +14,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Collectors; +import java.util.stream.Stream; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; @@ -23,6 +25,9 @@ import net.minecraft.util.EnumChatFormatting; import org.lwjgl.opengl.GL11; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; + import codechicken.core.gui.GuiScrollSlot; import codechicken.lib.gui.GuiDraw; import codechicken.lib.vec.Rectangle4i; @@ -35,6 +40,12 @@ import codechicken.nei.api.ItemFilter; import codechicken.nei.api.ItemFilter.ItemFilterProvider; import codechicken.nei.guihook.GuiContainerManager; import codechicken.nei.guihook.IContainerTooltipHandler; +import codechicken.nei.recipe.GuiCraftingRecipe; +import codechicken.nei.recipe.GuiRecipeTab; +import codechicken.nei.recipe.ICraftingHandler; +import codechicken.nei.recipe.IRecipeHandler; +import codechicken.nei.recipe.StackInfo; +import codechicken.nei.util.NBTJson; import codechicken.nei.util.NEIMouseUtils; public class SubsetWidget extends Button implements ItemFilterProvider, IContainerTooltipHandler { @@ -535,6 +546,64 @@ public class SubsetWidget extends Button implements ItemFilterProvider, IContain } } + public static void loadCustomSubsets() { + File dir = new File(NEIClientConfig.configDir, "subsets"); + + if (!dir.exists() || !dir.isDirectory()) { + return; + } + + Stream.of(dir.listFiles()).filter(file -> !file.isDirectory()).forEach(file -> { + ClientHandler.loadSettingsFile( + "subsets/" + file.getName(), + lines -> parseFile(file.getName(), lines.collect(Collectors.toList()))); + }); + } + + private static void parseFile(String resource, List itemStrings) { + final JsonParser parser = new JsonParser(); + final String subsetNamespace = resource.substring(0, resource.lastIndexOf('.')); + SubsetTag processedTag = new SubsetTag(subsetNamespace, new ItemStackSet()); + + for (String itemStr : itemStrings) { + + try { + + if (itemStr.startsWith("; ")) { + final String handlerName = itemStr.substring(2); + String recipeName = handlerName; + addTag(processedTag); + IRecipeHandler recipeHandler = GuiCraftingRecipe.craftinghandlers.stream() + .filter(handler -> handlerName.equals(getHandlerName(handler))).findAny().orElse(null); + + if (recipeHandler == null) { + recipeHandler = GuiCraftingRecipe.serialCraftingHandlers.stream() + .filter(handler -> handlerName.equals(getHandlerName(handler))).findAny().orElse(null); + } + + if (recipeHandler != null) { + recipeName = recipeHandler.getRecipeName().trim(); + } + + processedTag = new SubsetTag( + subsetNamespace + "." + recipeName.replace(".", ""), + new ItemStackSet()); + } else { + ((ItemStackSet) processedTag.filter) + .add(StackInfo.loadFromNBT((NBTTagCompound) NBTJson.toNbt(parser.parse(itemStr)))); + } + + } catch (IllegalArgumentException | JsonSyntaxException | IllegalStateException e) { + NEIClientConfig.logger.error("Failed to load collapsible items from json string:\n{}", itemStr); + } + + } + } + + private static String getHandlerName(ICraftingHandler handler) { + return GuiRecipeTab.getHandlerInfo(handler).getHandlerName(); + } + public static void loadHidden() { final List itemList = new LinkedList<>(); diff --git a/src/main/java/codechicken/nei/commands/CommandBookmarkAdd.java b/src/main/java/codechicken/nei/commands/CommandBookmarkAdd.java index 190d04d5..f66ac46f 100644 --- a/src/main/java/codechicken/nei/commands/CommandBookmarkAdd.java +++ b/src/main/java/codechicken/nei/commands/CommandBookmarkAdd.java @@ -1,7 +1,6 @@ package codechicken.nei.commands; import net.minecraft.command.CommandBase; -import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.item.ItemStack; import net.minecraft.nbt.JsonToNBT; @@ -12,7 +11,7 @@ import net.minecraft.util.ChatComponentTranslation; import codechicken.nei.ItemPanels; -public class CommandBookmarkAdd extends CommandBase implements ICommand { +public class CommandBookmarkAdd extends CommandBase { @Override public String getCommandName() { diff --git a/src/main/java/codechicken/nei/commands/CommandRecipeId.java b/src/main/java/codechicken/nei/commands/CommandRecipeId.java new file mode 100644 index 00000000..4f6cd5f7 --- /dev/null +++ b/src/main/java/codechicken/nei/commands/CommandRecipeId.java @@ -0,0 +1,268 @@ +package codechicken.nei.commands; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import net.minecraft.command.CommandBase; +import net.minecraft.command.ICommandSender; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.EnumChatFormatting; + +import org.apache.commons.io.IOUtils; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import codechicken.core.CommonUtils; +import codechicken.nei.ClientHandler; +import codechicken.nei.ItemList; +import codechicken.nei.NEIClientConfig; +import codechicken.nei.recipe.GuiCraftingRecipe; +import codechicken.nei.recipe.GuiRecipeTab; +import codechicken.nei.recipe.ICraftingHandler; +import codechicken.nei.recipe.Recipe; +import codechicken.nei.recipe.Recipe.RecipeId; +import codechicken.nei.recipe.StackInfo; +import codechicken.nei.util.NBTJson; + +public class CommandRecipeId extends CommandBase { + + protected static class ProcessDiffThread extends Thread { + + protected final ICommandSender sender; + protected final File prevFile; + protected final File currFile; + protected final File diffFile; + + public ProcessDiffThread(ICommandSender sender, File prevFile, File currFile, File diffFile) { + this.sender = sender; + this.prevFile = prevFile; + this.currFile = currFile; + this.diffFile = diffFile; + } + + @Override + public void run() { + final Set prevRecipes = loadFileContent(this.prevFile); + final Set currRecipes = loadFileContent(this.currFile); + + if (prevRecipes == null || currRecipes == null) { + return; + } + + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "Generate subset diff!")); + + final Set notAllowedRecipes = prevRecipes.stream().filter(recipe -> !currRecipes.contains(recipe)) + .collect(Collectors.toSet()); + final List subsetsList = new ArrayList<>(); + + for (Map.Entry> entry : generateSubsets(notAllowedRecipes).entrySet()) { + subsetsList.add("; " + entry.getKey()); + subsetsList.addAll(entry.getValue()); + } + + saveFile(this.diffFile, subsetsList); + saveFile(getFile("not-allowed-recipes"), new ArrayList<>(notAllowedRecipes)); + + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "Finished processing recipe diff!")); + } + + private Set loadFileContent(File file) { + try (FileReader reader = new FileReader(file)) { + return new HashSet<>(IOUtils.readLines(reader)); + } catch (IOException e) { + NEIClientConfig.logger.error("Failed to load '{}' file {}", file.getName(), file, e); + } + return null; + } + + private Map> generateSubsets(Set notAllowedRecipes) { + final JsonParser parser = new JsonParser(); + final Map> subsetsBuilder = new HashMap<>(); + + for (String recipe : notAllowedRecipes) { + try { + final RecipeId recipeId = RecipeId.of((JsonObject) parser.parse(recipe)); + final NBTTagCompound nbtStack = StackInfo.itemStackToNBT(recipeId.getResult(), false); + nbtStack.removeTag("Count"); + + subsetsBuilder.computeIfAbsent(recipeId.getHandleName(), rn -> new HashSet<>()) + .add(NBTJson.toJson(nbtStack)); + } catch (Exception ex) { + NEIClientConfig.logger.error("Found Blocken RecipeId {}", recipe, ex); + } + } + + return subsetsBuilder; + } + + private void saveFile(File file, List content) { + try (FileOutputStream output = new FileOutputStream(file)) { + IOUtils.writeLines(content, "\n", output, StandardCharsets.UTF_8); + } catch (IOException e) { + NEIClientConfig.logger.error("Filed to save recipeid diff list to file {}", file, e); + } + } + + } + + protected static class ProcessDumpThread extends Thread { + + private Set blacklist; + protected final ICommandSender sender; + protected final File currFile; + + public ProcessDumpThread(ICommandSender sender, File currFile) { + this.sender = sender; + this.currFile = currFile; + ClientHandler + .loadSettingsFile("hiddenhandlers.cfg", lines -> blacklist = lines.collect(Collectors.toSet())); + } + + @Override + public void run() { + NEIClientConfig.logger.info("Start processing recipe handlers!"); + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "Start processing recipe handlers!")); + + try { + if (!this.currFile.exists()) this.currFile.createNewFile(); + + final PrintWriter recipes = new PrintWriter(this.currFile); + int total = ItemList.items.size(); + int count = 0; + + for (ItemStack stack : ItemList.items) { + + if ((count % 100) == 0) { + NEIClientConfig.logger.info( + "({}/{}). Processing {} crafting recipes...", + count++, + total, + stack.getDisplayName()); + } + + count++; + + for (ICraftingHandler handler : GuiCraftingRecipe.getCraftingHandlers("item", stack)) { + if (!blacklist.contains(GuiRecipeTab.getHandlerInfo(handler).getHandlerName())) { + for (int index = 0; index < handler.numRecipes(); index++) { + try { + final Recipe recipe = Recipe.of(handler, index); + if (recipe != null) { + recipes.println(NBTJson.toJson(recipe.getRecipeId().toJsonObject())); + } + } catch (Exception ex) { + NEIClientConfig.logger.error( + "Found Blocken RecipeId {}:{}", + GuiRecipeTab.getHandlerInfo(handler).getHandlerName(), + stack, + ex); + } + } + } + } + } + + recipes.close(); + } catch (Exception e) { + NEIClientConfig.logger.error("Error dumping RecipeId", e); + } + + NEIClientConfig.logger.info("Finished processing recipe handlers!"); + sender.addChatMessage( + new ChatComponentText(EnumChatFormatting.AQUA + "Finished processing recipe handlers!")); + } + + } + + @Override + public String getCommandName() { + return "recipeid"; + } + + @Override + public String getCommandUsage(ICommandSender sender) { + return "/recipeid dump OR /recipeid diff [subset name]"; + } + + @Override + public int getRequiredPermissionLevel() { + return 0; + } + + @Override + public void processCommand(ICommandSender sender, String[] args) { + final String command = args.length == 0 ? null : args[0]; + + if ("dump".equals(command)) { + processDumpCommand(sender, args); + } else if ("diff".equals(command)) { + processDiffCommand(sender, args); + } else { + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + getCommandUsage(sender))); + } + + } + + protected void processDiffCommand(ICommandSender sender, String[] args) { + + if (args.length > 4) { + sender.addChatMessage(new ChatComponentText("Too many parameters! Usage: " + getCommandUsage(sender))); + return; + } + + if (args.length < 3) { + sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + getCommandUsage(sender))); + return; + } + + final File prevFilename = getFile(args[1]); + final File currFilename = getFile(args[2]); + final File diffFilename = getFile(args.length > 3 ? args[3] : "subsets"); + + if (!prevFilename.exists()) { + sender.addChatMessage( + new ChatComponentText("File `" + args[1] + "` not found! Usage: " + getCommandUsage(sender))); + return; + } + + if (!currFilename.exists()) { + sender.addChatMessage( + new ChatComponentText("File `" + args[2] + "` not found! Usage: " + getCommandUsage(sender))); + return; + } + + (new ProcessDiffThread(sender, prevFilename, currFilename, diffFilename)).start(); + } + + protected void processDumpCommand(ICommandSender sender, String[] args) { + if (args.length > 2) { + sender.addChatMessage(new ChatComponentText("Too many parameters! Usage: " + getCommandUsage(sender))); + return; + } + + final File dir = new File(CommonUtils.getMinecraftDir(), "recipeid"); + final String currFilename = args.length == 2 ? args[1] : "recipeId"; + if (!dir.exists()) dir.mkdirs(); + + (new ProcessDumpThread(sender, getFile(currFilename))).start(); + } + + private static File getFile(String filename) { + return new File(CommonUtils.getMinecraftDir(), "recipeid/" + filename + ".json"); + } + +} diff --git a/src/main/java/codechicken/nei/recipe/Recipe.java b/src/main/java/codechicken/nei/recipe/Recipe.java index 9832de85..3c09c390 100644 --- a/src/main/java/codechicken/nei/recipe/Recipe.java +++ b/src/main/java/codechicken/nei/recipe/Recipe.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidContainerRegistry; @@ -81,7 +82,15 @@ public class Recipe { ItemStack stack = extractItem(item); if (stack != null) { - list.add(stack.copy()); + stack = stack.copy(); + + // hack: remove metadata for data stick + if (stack.hasTagCompound() && stack.getItemDamage() == 32708 + && "gregtech:gt.metaitem.01".equals(Item.itemRegistry.getNameForObject(stack.getItem()))) { + stack.stackTagCompound = null; + } + + list.add(stack); } } @@ -116,9 +125,20 @@ public class Recipe { } for (int index = 0; index < stacks.size(); index++) { - if (!stacks.get(index).containsWithNBT(ingredients.get(index))) { - return false; + for (ItemStack item : stacks.get(index).items) { + + // hack: remove metadata for data stick + if (item.hasTagCompound() && item.getItemDamage() == 32708 + && "gregtech:gt.metaitem.01".equals(Item.itemRegistry.getNameForObject(item.getItem()))) { + item = item.copy(); + item.stackTagCompound = null; + } + + if (!StackInfo.equalItemAndNBT(item, this.ingredients.get(index), true)) { + return false; + } } + } return true; diff --git a/src/main/java/codechicken/nei/recipe/StackInfo.java b/src/main/java/codechicken/nei/recipe/StackInfo.java index e2eaa095..81bd86bc 100644 --- a/src/main/java/codechicken/nei/recipe/StackInfo.java +++ b/src/main/java/codechicken/nei/recipe/StackInfo.java @@ -5,6 +5,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; @@ -223,7 +224,9 @@ public class StackInfo { if (stacks.length > 1) { for (ItemStack stack : stacks) { - if (stack.getItem() != null && !ItemInfo.isHidden(stack) && stack.getItemDamage() < damage) { + if (stack.getItem() != null && !ItemInfo.isHidden(stack) + && (stack.getItemDamage() < damage || stack.getItemDamage() == damage + && Item.getIdFromItem(stack.getItem()) < Item.getIdFromItem(result.getItem()))) { damage = stack.getItemDamage(); result = stack; } diff --git a/src/main/java/codechicken/nei/util/NBTJson.java b/src/main/java/codechicken/nei/util/NBTJson.java index 553cd352..f8953a2d 100644 --- a/src/main/java/codechicken/nei/util/NBTJson.java +++ b/src/main/java/codechicken/nei/util/NBTJson.java @@ -43,12 +43,10 @@ public class NBTJson { // NBTTagCompound final NBTTagCompound nbtTagCompound = (NBTTagCompound) nbt; final Map tagMap = (Map) nbtTagCompound.tagMap; + final JsonObject root = new JsonObject(); - JsonObject root = new JsonObject(); - - for (Map.Entry nbtEntry : tagMap.entrySet()) { - root.add(nbtEntry.getKey(), toJsonObject(nbtEntry.getValue())); - } + tagMap.entrySet().stream().sorted(Map.Entry.comparingByKey()) + .forEach(nbtEntry -> { root.add(nbtEntry.getKey(), toJsonObject(nbtEntry.getValue())); }); return root; } else if (nbt instanceof NBTTagByte) { diff --git a/src/main/resources/assets/nei/cfg/recipeidblacklist.cfg b/src/main/resources/assets/nei/cfg/recipeidblacklist.cfg new file mode 100644 index 00000000..7df187b3 --- /dev/null +++ b/src/main/resources/assets/nei/cfg/recipeidblacklist.cfg @@ -0,0 +1,2 @@ +# Each line in this file should either be a comment (line starts with '#'), handler name or handler id. +# If you delete this file, it will be regenerated with the default handlers list. \ No newline at end of file