optimization; command translations; recipeid ingr sorting

This commit is contained in:
slprime committed 2025-08-06 13:37:54 +03:00
1 parent 080e49e2bb
commit d5c3552a9a
13 files changed
+181 -90

No files matched your search

@@ -244,7 +244,7 @@ public class FavoriteRecipes {
try (FileOutputStream output = new FileOutputStream(favoriteFile)) {
IOUtils.writeLines(strings, "\n", output, StandardCharsets.UTF_8);
} catch (IOException e) {
NEIClientConfig.logger.error("Filed to save favorites list to file {}", favoriteFile, e);
NEIClientConfig.logger.error("Failed to save favorites list to file {}", favoriteFile, e);
}
}
@@ -236,7 +236,7 @@ public class PresetsList {
try (FileOutputStream output = new FileOutputStream(presetsFile)) {
IOUtils.writeLines(strings, "\n", output, StandardCharsets.UTF_8);
} catch (IOException e) {
NEIClientConfig.logger.error("Filed to save presets list to file {}", presetsFile, e);
NEIClientConfig.logger.error("Failed to save presets list to file {}", presetsFile, e);
}
recipeFilter.cache = null;
@@ -566,9 +566,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, IContain
SubsetTag processedTag = new SubsetTag(subsetNamespace, new ItemStackSet());
for (String itemStr : itemStrings) {
try {
if (itemStr.startsWith("; ")) {
final String handlerName = itemStr.substring(2);
String recipeName = handlerName;
@@ -592,11 +590,9 @@ public class SubsetWidget extends Button implements ItemFilterProvider, IContain
((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);
}
}
}
@@ -359,7 +359,7 @@ public class BookmarkStorage {
IOUtils.writeLines(strings, "\n", output, StandardCharsets.UTF_8);
NEIClientConfig.world.nbt.setTag("bookmark", navigation);
} catch (IOException e) {
NEIClientConfig.logger.error("Filed to save bookmarks list to file {}", bookmarkFile, e);
NEIClientConfig.logger.error("Failed to save bookmarks list to file {}", bookmarkFile, e);
}
}
@@ -7,6 +7,7 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -18,7 +19,8 @@ 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.ChatComponentTranslation;
import net.minecraft.util.ChatStyle;
import net.minecraft.util.EnumChatFormatting;
import org.apache.commons.io.IOUtils;
@@ -29,10 +31,12 @@ import codechicken.core.CommonUtils;
import codechicken.nei.ClientHandler;
import codechicken.nei.ItemList;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.ICraftingHandler;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.RecipeHandlerQuery;
import codechicken.nei.util.NBTJson;
public class CommandRecipeId extends CommandBase {
@@ -53,15 +57,10 @@ public class CommandRecipeId extends CommandBase {
@Override
public void run() {
sendChatInfoMessage(sender, "nei.chat.recipeid.diff.start");
final Set<String> prevRecipes = loadFileContent(this.prevFile);
final Set<String> currRecipes = loadFileContent(this.currFile);
if (prevRecipes == null || currRecipes == null) {
return;
}
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "Generate subset diff!"));
final Set<String> notAllowedRecipes = prevRecipes.stream().filter(recipe -> !currRecipes.contains(recipe))
.collect(Collectors.toSet());
final List<String> subsetsList = new ArrayList<>();
@@ -74,7 +73,7 @@ public class CommandRecipeId extends CommandBase {
saveFile(this.diffFile, subsetsList);
saveFile(getFile("not-allowed-recipes"), new ArrayList<>(notAllowedRecipes));
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "Finished processing recipe diff!"));
sendChatInfoMessage(sender, "nei.chat.recipeid.diff.finish");
}
private Set<String> loadFileContent(File file) {
@@ -83,16 +82,16 @@ public class CommandRecipeId extends CommandBase {
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to load '{}' file {}", file.getName(), file, e);
}
return null;
return new HashSet<>();
}
private Map<String, Set<String>> generateSubsets(Set<String> notAllowedRecipes) {
final JsonParser parser = new JsonParser();
final Map<String, Set<String>> subsetsBuilder = new HashMap<>();
for (String recipe : notAllowedRecipes) {
for (String recipeStr : notAllowedRecipes) {
try {
final NBTTagCompound nbtRecipe = (NBTTagCompound) NBTJson.toNbt(parser.parse(recipe));
final NBTTagCompound nbtRecipe = (NBTTagCompound) NBTJson.toNbt(parser.parse(recipeStr));
if (nbtRecipe.hasKey("result")) {
final NBTTagCompound nbtStack = nbtRecipe.getCompoundTag("result");
@@ -100,10 +99,10 @@ public class CommandRecipeId extends CommandBase {
subsetsBuilder.computeIfAbsent(nbtRecipe.getString("handlerName"), rn -> new HashSet<>())
.add(NBTJson.toJson(nbtStack));
} else {
NEIClientConfig.logger.error("Found Blocken RecipeId {}", recipe);
NEIClientConfig.logger.error("Found Broken RecipeId {}", recipeStr);
}
} catch (Exception ex) {
NEIClientConfig.logger.error("Found Blocken RecipeId {}", recipe, ex);
NEIClientConfig.logger.error("Found Broken RecipeId {}", recipeStr, ex);
}
}
@@ -114,7 +113,7 @@ public class CommandRecipeId extends CommandBase {
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);
NEIClientConfig.logger.error("Failed to save recipeid diff list to file {}", file, e);
}
}
@@ -122,21 +121,31 @@ public class CommandRecipeId extends CommandBase {
protected static class ProcessDumpThread extends Thread {
private Set<String> blacklist;
private ArrayList<ICraftingHandler> craftinghandlers = new ArrayList<>();
private ArrayList<ICraftingHandler> serialCraftingHandlers = new ArrayList<>();
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()));
ClientHandler.loadSettingsFile("recipeidblacklist.cfg", lines -> {
final Set<String> names = lines.collect(Collectors.toSet());
this.craftinghandlers = GuiCraftingRecipe.craftinghandlers.stream()
.filter(h -> !names.contains(GuiRecipeTab.getHandlerInfo(h).getHandlerName()))
.collect(Collectors.toCollection(ArrayList::new));
this.serialCraftingHandlers = GuiCraftingRecipe.serialCraftingHandlers.stream()
.filter(h -> !names.contains(GuiRecipeTab.getHandlerInfo(h).getHandlerName()))
.collect(Collectors.toCollection(ArrayList::new));
});
}
@Override
public void run() {
NEIClientConfig.logger.info("Start processing recipe handlers!");
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "Start processing recipe handlers!"));
sendChatInfoMessage(sender, "nei.chat.recipeid.dump.start");
try {
if (!this.currFile.exists()) this.currFile.createNewFile();
@@ -157,21 +166,20 @@ public class CommandRecipeId extends CommandBase {
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);
for (ICraftingHandler handler : getCraftingHandlers(stack)) {
for (int index = 0; index < handler.numRecipes(); index++) {
try {
final Recipe recipe = Recipe.of(handler, index);
if (recipe != null
&& (!recipe.getIngredients().isEmpty() && !recipe.getResults().isEmpty())) {
recipes.println(NBTJson.toJson(recipe.getRecipeId().toJsonObject()));
}
} catch (Exception ex) {
NEIClientConfig.logger.error(
"Found Broken RecipeId {}:{}",
GuiRecipeTab.getHandlerInfo(handler).getHandlerName(),
stack,
ex);
}
}
}
@@ -183,8 +191,18 @@ public class CommandRecipeId extends CommandBase {
}
NEIClientConfig.logger.info("Finished processing recipe handlers!");
sender.addChatMessage(
new ChatComponentText(EnumChatFormatting.AQUA + "Finished processing recipe handlers!"));
sendChatInfoMessage(sender, "nei.chat.recipeid.dump.finish");
}
private ArrayList<ICraftingHandler> getCraftingHandlers(Object... results) {
return new RecipeHandlerQuery<>(
h -> h.getRecipeHandler("item", results),
this.craftinghandlers,
this.serialCraftingHandlers,
"Error while looking up crafting recipe",
"outputId: item",
"results: " + Arrays.toString(results))
.runWithProfiling(NEIClientUtils.translate("recipe.concurrent.crafting"));
}
}
@@ -221,7 +239,7 @@ public class CommandRecipeId extends CommandBase {
protected void processDiffCommand(ICommandSender sender, String[] args) {
if (args.length > 4) {
sendChatErrorMessage(sender, "Too many parameters! Usage: " + getCommandUsage(sender));
sendChatErrorMessage(sender, "nei.chat.recipeid.many_params", getCommandUsage(sender));
return;
}
@@ -235,12 +253,12 @@ public class CommandRecipeId extends CommandBase {
final File diffFilename = getFile(args.length > 3 ? args[3] : "changelog");
if (!prevFilename.exists()) {
sendChatErrorMessage(sender, "File `" + prevFilename.getName() + "` not found!");
sendChatErrorMessage(sender, "nei.chat.recipeid.not_found", prevFilename.getName());
return;
}
if (!currFilename.exists()) {
sendChatErrorMessage(sender, "File `" + currFilename.getName() + "` not found!");
sendChatErrorMessage(sender, "nei.chat.recipeid.not_found", currFilename.getName());
return;
}
@@ -250,7 +268,7 @@ public class CommandRecipeId extends CommandBase {
protected void processDumpCommand(ICommandSender sender, String[] args) {
if (args.length > 2) {
sendChatErrorMessage(sender, "Too many parameters! Usage: " + getCommandUsage(sender));
sendChatErrorMessage(sender, "nei.chat.recipeid.many_params", getCommandUsage(sender));
return;
}
@@ -265,8 +283,16 @@ public class CommandRecipeId extends CommandBase {
return new File(CommonUtils.getMinecraftDir(), "recipeid/" + filename + ".json");
}
private static void sendChatErrorMessage(ICommandSender sender, String message) {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + message));
private static void sendChatInfoMessage(ICommandSender sender, String translationKey, Object... args) {
sender.addChatMessage(
new ChatComponentTranslation(translationKey, args)
.setChatStyle(new ChatStyle().setColor(EnumChatFormatting.AQUA)));
}
private static void sendChatErrorMessage(ICommandSender sender, String translationKey, Object... args) {
sender.addChatMessage(
new ChatComponentTranslation(translationKey, args)
.setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED)));
}
}
@@ -97,7 +97,7 @@ public class HandlerDumper extends DataDumper {
}
writer.close();
} catch (IOException e) {
NEIClientConfig.logger.error("Filed to save dump handler list to file {}", file, e);
NEIClientConfig.logger.error("Failed to save dump handler list to file {}", file, e);
}
}
@@ -2,6 +2,8 @@ package codechicken.nei.recipe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
@@ -37,10 +39,15 @@ public class Recipe {
this.result = result != null ? StackInfo.withAmount(result, 0) : null;
this.handlerName = handlerName;
this.ingredients = ingredients;
if (!isSharpedRecipe()) {
// sort to ignore ingredients position in shapeless recipes
Collections.sort(this.ingredients, Comparator.comparing(StackInfo::getItemStackGUID));
}
}
public static RecipeId of(Object result, String handlerName, Iterable<?> ingredients) {
return new RecipeId(extractItem(result), handlerName, extractItems(ingredients));
return new RecipeId(extractItem(result), handlerName, extractIngredients(ingredients));
}
public static RecipeId of(JsonObject json) {
@@ -75,22 +82,14 @@ public class Recipe {
return new ArrayList<>(this.ingredients);
}
protected static List<ItemStack> extractItems(Iterable<?> items) {
protected static List<ItemStack> extractIngredients(Iterable<?> items) {
final List<ItemStack> list = new ArrayList<>();
for (Object item : items) {
ItemStack stack = extractItem(item);
final ItemStack stack = extractItem(item);
if (stack != null) {
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);
list.add(prepareIngredient(stack.copy()));
}
}
@@ -124,26 +123,56 @@ public class Recipe {
return false;
}
for (int index = 0; index < stacks.size(); index++) {
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)) {
if (isSharpedRecipe()) {
for (int index = 0; index < stacks.size(); index++) {
if (!containsWithNBT(stacks.get(index), Arrays.asList(this.ingredients.get(index)))) {
return false;
}
}
} else {
for (PositionedStack pStack : stacks) {
if (!containsWithNBT(pStack, this.ingredients)) {
return false;
}
}
}
return true;
}
private static boolean containsWithNBT(PositionedStack pStack, List<ItemStack> ingrStacks) {
for (ItemStack item : pStack.items) {
final ItemStack pItem = prepareIngredient(item);
if (ingrStacks.stream().anyMatch(stack -> StackInfo.equalItemAndNBT(pItem, stack, true))) {
return true;
}
}
return false;
}
private static ItemStack prepareIngredient(ItemStack stack) {
// hack: remove metadata for "Data Stick"
if (stack.hasTagCompound() && stack.getItemDamage() == 32708
&& "gregtech:gt.metaitem.01".equals(Item.itemRegistry.getNameForObject(stack.getItem()))) {
return new ItemStack(stack.getItem(), stack.getItemDamage());
}
// hack: remove metadata for "Circuit Imprint"
if (stack.hasTagCompound() && stack.getItemDamage() == 0
&& "bartworks:gt.bwMetaGeneratedItem0"
.equals(Item.itemRegistry.getNameForObject(stack.getItem()))) {
return new ItemStack(stack.getItem(), stack.getItemDamage());
}
return stack;
}
public boolean isSharpedRecipe() {
return this.handlerName.equals("codechicken.nei.recipe.ShapedRecipeHandler")
|| this.handlerName.equals("fox.spiteful.avaritia.compat.nei.ExtremeShapedRecipeHandler");
}
public JsonObject toJsonObject() {
final JsonObject json = new JsonObject();
@@ -162,8 +191,8 @@ public class Recipe {
protected JsonArray convertItemsToJsonArray(List<ItemStack> items) {
final JsonArray arr = new JsonArray();
for (ItemStack nbTag : items) {
arr.add(NBTJson.toJsonObject(StackInfo.itemStackToNBT(nbTag)));
for (ItemStack stack : items) {
arr.add(NBTJson.toJsonObject(StackInfo.itemStackToNBT(stack)));
}
return arr;
@@ -17,7 +17,7 @@ import codechicken.nei.ItemList;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.util.AsyncTaskProfiler;
class RecipeHandlerQuery<T extends IRecipeHandler> {
public class RecipeHandlerQuery<T extends IRecipeHandler> {
private final Function<T, T> recipeHandlerFunction;
private final List<T> recipeHandlers;
@@ -25,15 +25,15 @@ class RecipeHandlerQuery<T extends IRecipeHandler> {
private final String[] errorMessage;
private boolean error = false;
RecipeHandlerQuery(Function<T, T> recipeHandlerFunction, List<T> recipeHandlers, List<T> serialRecipeHandlers,
String... errorMessage) {
public RecipeHandlerQuery(Function<T, T> recipeHandlerFunction, List<T> recipeHandlers,
List<T> serialRecipeHandlers, String... errorMessage) {
this.recipeHandlerFunction = recipeHandlerFunction;
this.recipeHandlers = recipeHandlers;
this.serialRecipeHandlers = serialRecipeHandlers;
this.errorMessage = errorMessage;
}
ArrayList<T> runWithProfiling(String profilerSection) {
public ArrayList<T> runWithProfiling(String profilerSection) {
TaskProfiler profiler = ProfilerRecipeHandler.getProfiler();
// Save the current config state here, as it may be altered
@@ -23,6 +23,7 @@ import codechicken.nei.api.ItemInfo;
import codechicken.nei.recipe.stackinfo.DefaultStackStringifyHandler;
import codechicken.nei.recipe.stackinfo.GTFluidStackStringifyHandler;
import codechicken.nei.util.ItemStackKey;
import codechicken.nei.util.NBTHelper;
public class StackInfo {
@@ -145,7 +146,7 @@ public class StackInfo {
final NBTTagCompound nbTag = itemStackToNBT(stack, false);
if (nbTag == null) {
return null;
return "unknown";
}
nbTag.removeTag("Count");
@@ -158,9 +159,11 @@ public class StackInfo {
nbTag.removeTag("tag");
}
if (nbTag.hasKey("strId") && guidfilters.containsKey(nbTag.getString("strId"))) {
if (nbTag.hasKey("strId") && (guidfilters.containsKey(nbTag.getString("strId"))
|| guidfilters.containsKey(nbTag.getString("strId") + "&" + nbTag.getShort("Damage")))) {
final String strId = nbTag.getString("strId")
+ (guidfilters.containsKey(nbTag.getString("strId")) ? "" : "&" + nbTag.getShort("Damage"));
final ArrayList<String> keys = new ArrayList<>();
final String strId = nbTag.getString("strId");
keys.add(strId);
@@ -185,7 +188,7 @@ public class StackInfo {
}
if (local instanceof NBTBase item) {
keys.add(item.toString());
keys.add(NBTHelper.toString(item));
} else if (local != null) {
keys.add(String.valueOf(local));
}
@@ -196,7 +199,7 @@ public class StackInfo {
}
} else {
synchronized (guidcache) {
guidcache.put(stack, nbTag.toString());
guidcache.put(stack, NBTHelper.toString(nbTag));
}
}
@@ -219,15 +222,17 @@ public class StackInfo {
}
public static ItemStack getItemStackWithMinimumDamage(ItemStack[] stacks) {
int damage = Short.MAX_VALUE;
ItemStack result = stacks[0];
if (stacks.length > 1) {
for (ItemStack stack : stacks) {
// to optimize compare recipes from permutation, an item with a minimum strId and damage is taken so as
// not to check everything permutation items
if (stack.getItem() != null && !ItemInfo.isHidden(stack)
&& (stack.getItemDamage() < damage || stack.getItemDamage() == damage
&& Item.getIdFromItem(stack.getItem()) < Item.getIdFromItem(result.getItem()))) {
damage = stack.getItemDamage();
&& (stack.getItemDamage() < result.getItemDamage()
|| stack.getItemDamage() == result.getItemDamage()
&& Item.itemRegistry.getNameForObject(stack.getItem()).compareTo(
Item.itemRegistry.getNameForObject(result.getItem())) == -1)) {
result = stack;
}
}
@@ -1,5 +1,9 @@
package codechicken.nei.util;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import net.minecraft.nbt.NBTBase;
@@ -52,4 +56,26 @@ public class NBTHelper {
private static NBTBase get(NBTTagList tag, int idx) {
return idx >= 0 && idx < tag.tagList.size() ? (NBTBase) tag.tagList.get(idx) : null;
}
public static String toString(NBTBase nbt) {
if (nbt instanceof NBTTagCompound nbtTagCompound) {
final Map<String, NBTBase> tagMap = (Map<String, NBTBase>) nbtTagCompound.tagMap;
return "{" + tagMap.entrySet().stream().sorted(Map.Entry.<String, NBTBase>comparingByKey())
.map(nbtEntry -> nbtEntry.getKey() + ":" + toString(nbtEntry.getValue()))
.collect(Collectors.joining(",")) + "}";
} else if (nbt instanceof NBTTagList list) {
if (list.tagList.isEmpty()) {
return "[]";
} else {
final StringJoiner arr = new StringJoiner(",");
list.tagList.forEach(c -> arr.add(toString((NBTBase) c)));
return "[" + arr.toString() + "]";
}
} else {
return nbt.toString();
}
}
}
@@ -54,4 +54,5 @@ miscutils:personalHealingDevice
tectech:item.em.debugContainer,tag.symbols
tinkersdefense:Heater Shield,tag.InfiTool
tinkersdefense:Round Shield,tag.InfiTool
miscutils:itemCustomMetaCover.miscutils.GtMachineCasings,Damage
miscutils:itemCustomMetaCover.miscutils.GtMachineCasings,Damage
gregtech:gt.metaitem.01&32708,tag.output
@@ -1,2 +1,3 @@
# 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.
# If you delete this file, it will be regenerated with the default handlers list.
Unknown
@@ -138,6 +138,13 @@ nei.chat.chunkoverlay.3=Chunk Overlay: GT Ore Veins
nei.chat.item_link.text=<%s> §6Click to add bookmark: %s
nei.chat.bookmark_added.text=Bookmark added!
nei.chat.recipeid.many_params=Too many parameters! Usage: %s
nei.chat.recipeid.not_found=File %s not found!
nei.chat.recipeid.diff.start=Start processing recipe diff!
nei.chat.recipeid.diff.finish=Finished processing recipe diff!
nei.chat.recipeid.dump.start=Start processing recipe handlers!
nei.chat.recipeid.dump.finish=Finished processing recipe handlers!
nei.options=NEI Options
nei.options.back=Back
nei.options.save=Save