diff --git a/src/main/java/codechicken/nei/api/ItemInfo.java b/src/main/java/codechicken/nei/api/ItemInfo.java index 07495ef2..a4f71e8b 100644 --- a/src/main/java/codechicken/nei/api/ItemInfo.java +++ b/src/main/java/codechicken/nei/api/ItemInfo.java @@ -59,6 +59,7 @@ import codechicken.nei.SearchTokenParser.SearchMode; import codechicken.nei.config.ArrayDumper; import codechicken.nei.config.HandlerDumper; import codechicken.nei.config.ItemPanelDumper; +import codechicken.nei.config.RecipeDumper; import codechicken.nei.config.RegistryDumper; import codechicken.nei.guihook.GuiContainerManager; import codechicken.nei.item.FluidDisplayRenderer; @@ -284,6 +285,7 @@ public class ItemInfo { }); API.addOption(new ItemPanelDumper("tools.dump.itempanel")); API.addOption(new HandlerDumper("tools.dump.handlers")); + API.addOption(new RecipeDumper("tools.dump.recipes")); } @SuppressWarnings("unchecked") diff --git a/src/main/java/codechicken/nei/config/RecipeDumper.java b/src/main/java/codechicken/nei/config/RecipeDumper.java new file mode 100644 index 00000000..c551fd2e --- /dev/null +++ b/src/main/java/codechicken/nei/config/RecipeDumper.java @@ -0,0 +1,54 @@ +package codechicken.nei.config; + +import java.util.Collections; + +import codechicken.lib.vec.Rectangle4i; +import codechicken.nei.NEIClientUtils; +import codechicken.nei.recipe.RecipeJsonWriter; + +public class RecipeDumper extends DataDumper { + + public RecipeDumper(String name) { + super(name); + } + + @Override + public String[] header() { + return new String[0]; + } + + @Override + public Iterable dump(int mode) { + return Collections.emptyList(); + } + + @Override + public String renderName() { + return translateN(name); + } + + public Rectangle4i separateButtonSize() { + return dumpButtonSize(); + } + + public Rectangle4i combinedButtonSize() { + return modeButtonSize(); + } + + @Override + public void draw(int mousex, int mousey, float frame) { + drawPrefix(); + drawButton(mousex, mousey, combinedButtonSize(), translateN(name + ".combined")); + drawButton(mousex, mousey, separateButtonSize(), translateN(name + ".separate")); + } + + @Override + public void mouseClicked(int mousex, int mousey, int button) { + final boolean combined = combinedButtonSize().contains(mousex, mousey); + + if (combined || separateButtonSize().contains(mousex, mousey)) { + NEIClientUtils.playClickSound(); + RecipeJsonWriter.dumpAll(!combined); + } + } +} diff --git a/src/main/java/codechicken/nei/recipe/GuiRecipe.java b/src/main/java/codechicken/nei/recipe/GuiRecipe.java index b1f826c6..050e60a6 100644 --- a/src/main/java/codechicken/nei/recipe/GuiRecipe.java +++ b/src/main/java/codechicken/nei/recipe/GuiRecipe.java @@ -682,6 +682,10 @@ public abstract class GuiRecipe extends GuiContainer i return this.handlerPages.getRecipeIndices(); } + public List getFilteredRecipes() { + return this.handler.getFilteredRecipes(); + } + @Override public void keyTyped(char c, int i) { diff --git a/src/main/java/codechicken/nei/recipe/RecipeJsonWriter.java b/src/main/java/codechicken/nei/recipe/RecipeJsonWriter.java new file mode 100644 index 00000000..caa421e4 --- /dev/null +++ b/src/main/java/codechicken/nei/recipe/RecipeJsonWriter.java @@ -0,0 +1,303 @@ +package codechicken.nei.recipe; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +import net.minecraft.event.ClickEvent; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.ChatComponentTranslation; +import net.minecraft.util.EnumChatFormatting; + +import com.google.common.base.Stopwatch; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; + +import codechicken.core.CommonUtils; +import codechicken.nei.NEIClientConfig; +import codechicken.nei.NEIClientUtils; +import codechicken.nei.PositionedStack; +import codechicken.nei.config.GuiItemIconDumper; +import codechicken.nei.guihook.GuiContainerManager; +import codechicken.nei.recipe.Recipe.RecipeIngredient; +import codechicken.nei.util.NBTJson; +import cpw.mods.fml.relauncher.ReflectionHelper; + +/** + * Writes recipes as JSON, one object per line, with stacks in the format of {@link StackInfo#itemStackToNBT}. + */ +public class RecipeJsonWriter { + + protected static Field mEUt = null; + protected static Field mDuration = null; + protected static Field mRecipe = null; + + static { + try { + final ClassLoader loader = RecipeJsonWriter.class.getClassLoader(); + final Class gtRecipe = ReflectionHelper + .getClass(loader, "gregtech.api.util.GTRecipe", "gregtech.api.util.GT_Recipe"); + final Class cachedDefaultRecipe = ReflectionHelper.getClass( + loader, + "gregtech.nei.GTNEIDefaultHandler$CachedDefaultRecipe", + "gregtech.nei.GT_NEI_DefaultHandler$CachedDefaultRecipe"); + + mEUt = gtRecipe.getField("mEUt"); + mDuration = gtRecipe.getField("mDuration"); + mRecipe = cachedDefaultRecipe.getField("mRecipe"); + } catch (Exception ignored) {} + } + + private static final File DUMP_DIR = new File(CommonUtils.getMinecraftDir(), "dumps/recipes"); + + // display names by stack NBT without Count, built once per dump + private final Map names = new HashMap<>(); + private int dumped = 0; + private int skipped = 0; + + public static void dump(IRecipeHandler handler, List recipeIndices) { + final RecipeJsonWriter dumper = new RecipeJsonWriter(); + final File file = new File(DUMP_DIR, fileName(handler) + ".jsonl"); + + try { + final Stopwatch stopwatch = Stopwatch.createStarted(); + dumper.writeFile(file, Collections.singletonList(handler), h -> recipeIndices); + NEIClientConfig.logger.info("Writing " + dumper.dumped + " recipes took " + stopwatch.stop()); + dumper.printDumped(file); + } catch (Exception e) { + printFailed(e); + } + } + + /** + * Loads all recipes of every crafting handler and writes them either all to {@code dumps/recipes.jsonl} or each + * handler to its own file in {@code dumps/recipes}. + */ + public static void dumpAll(boolean separate) { + final RecipeJsonWriter dumper = new RecipeJsonWriter(); + + try { + final Stopwatch stopwatch = Stopwatch.createStarted(); + final List handlers = GuiCraftingRecipe.getCraftingHandlers("all"); + NEIClientConfig.logger.info("Loading " + handlers.size() + " recipe handlers took " + stopwatch.stop()); + stopwatch.reset().start(); + + if (separate) { + if (DUMP_DIR.exists()) { + for (File f : DUMP_DIR.listFiles()) if (f.isFile()) f.delete(); + } else DUMP_DIR.mkdirs(); + + for (ICraftingHandler handler : handlers) { + final String name = fileName(handler); + File file = new File(DUMP_DIR, name + ".jsonl"); + for (int i = 2; file.exists(); i++) file = new File(DUMP_DIR, name + '_' + i + ".jsonl"); + + dumper.writeFile(file, Collections.singletonList(handler), RecipeJsonWriter::filteredRecipes); + } + + NEIClientConfig.logger.info("Writing " + dumper.dumped + " recipes took " + stopwatch.stop()); + dumper.printDumped(DUMP_DIR); + } else { + final File file = new File(CommonUtils.getMinecraftDir(), "dumps/recipes.jsonl"); + dumper.writeFile(file, handlers, RecipeJsonWriter::filteredRecipes); + NEIClientConfig.logger.info("Writing " + dumper.dumped + " recipes took " + stopwatch.stop()); + dumper.printDumped(file); + } + } catch (Exception e) { + printFailed(e); + } + } + + private static String fileName(IRecipeHandler handler) { + return GuiItemIconDumper + .cleanFileName(EnumChatFormatting.getTextWithoutFormattingCodes(handler.getRecipeName()).trim()); + } + + private static List filteredRecipes(IRecipeHandler handler) { + return new SearchRecipeHandler<>(handler).getFilteredRecipes(); + } + + private void writeFile(File file, List handlers, + Function> recipeIndices) throws IOException { + file.getParentFile().mkdirs(); + + try (PrintWriter writer = new PrintWriter(file, StandardCharsets.UTF_8.name())) { + for (IRecipeHandler handler : handlers) { + write(writer, handler, recipeIndices.apply(handler)); + } + } + } + + private void printDumped(File file) { + final Path minecraftDir = CommonUtils.getMinecraftDir().getAbsoluteFile().toPath().normalize(); + final String path = minecraftDir.relativize(file.getAbsoluteFile().toPath().normalize()).toString() + .replace('\\', '/'); + final ChatComponentText chatLink = new ChatComponentText(path); + chatLink.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, file.getAbsolutePath())); + chatLink.getChatStyle().setUnderlined(true); + NEIClientUtils.printChatMessage( + new ChatComponentTranslation("nei.options.tools.dump.recipes.dumped", this.dumped, chatLink)); + + if (this.skipped > 0) { + NEIClientUtils.printChatMessage( + new ChatComponentTranslation("nei.options.tools.dump.recipes.skipped", this.skipped)); + } + } + + private static void printFailed(Exception e) { + NEIClientConfig.logger.error("Error dumping recipes", e); + NEIClientUtils.printChatMessage( + new ChatComponentTranslation("nei.options.tools.dump.recipes.failed", e.getMessage())); + } + + private void write(PrintWriter writer, IRecipeHandler handler, List recipeIndices) { + for (int recipeIndex : recipeIndices) { + final String line; + + try { + line = recipeJson(handler, recipeIndex); + } catch (Exception e) { + NEIClientConfig.logger.warn("Skipping recipe {} of {}", recipeIndex, handler.getRecipeName(), e); + this.skipped++; + continue; + } + + writer.println(line); + this.dumped++; + } + } + + private String recipeJson(IRecipeHandler handler, int recipeIndex) throws IllegalAccessException { + final Recipe recipe = Recipe.of(handler, recipeIndex); + final JsonObject json = new JsonObject(); + json.addProperty("handler", recipe.getHandlerName()); + json.add("ingredients", slotsJson(recipe.getIngredients(), handler instanceof ShapedRecipeHandler)); + json.add("results", slotsJson(recipe.getResults(), false)); + + final JsonObject gt = gtJson(handler, recipeIndex); + if (gt != null) { + json.add("gt", gt); + } + + return NBTJson.toJson(json); + } + + /** + * Each slot's shown stack, with {@code anyOf} listing every accepted stack. In a crafting grid, an ingredient's + * container item (an empty bucket, a damaged tool) goes under {@code returns}. + */ + private JsonArray slotsJson(List slots, boolean craftingGrid) { + final JsonArray array = new JsonArray(); + + for (RecipeIngredient slot : slots) { + final ItemStack stack = slot.getItemStack(); + final JsonObject json = stackJson(stack); + + if (json == null) { + continue; + } + + if (slot.getChance() != PositionedStack.CHANCE_FULL) { + json.addProperty("chance", slot.getChance()); + } + + if (slot.getPermutations().size() > 1) { + final JsonArray anyOf = new JsonArray(); + + for (ItemStack permutation : slot.getPermutations()) { + final JsonObject option = stackJson(permutation); + + if (option != null) { + option.remove("Count"); + anyOf.add(option); + } + } + + json.add("anyOf", anyOf); + } + + if (craftingGrid) { + final JsonObject container = stackJson(containerItem(stack)); + + if (container != null) { + json.add("returns", container); + } + } + + array.add(json); + } + + return array; + } + + private JsonObject stackJson(ItemStack stack) { + final NBTTagCompound nbTag = stack != null ? StackInfo.itemStackToNBT(stack) : null; + + if (nbTag == null) { + return null; + } + + final NBTBase count = nbTag.getTag("Count"); + nbTag.removeTag("Count"); + final String name = this.names.computeIfAbsent( + nbTag.toString(), + key -> EnumChatFormatting + .getTextWithoutFormattingCodes(GuiContainerManager.itemDisplayNameShort(stack))); + + if (count != null) { + nbTag.setTag("Count", count); + } + + final JsonObject json = NBTJson.toJsonObject(nbTag).getAsJsonObject(); + json.addProperty("name", name); + return json; + } + + private static ItemStack containerItem(ItemStack stack) { + if (!stack.getItem().hasContainerItem(stack)) { + return null; + } + + final boolean isPausedItemDamageSound = StackInfo.isPausedItemDamageSound(); + + try { + StackInfo.pauseItemDamageSound(true); + return stack.getItem().getContainerItem(stack); + } finally { + StackInfo.pauseItemDamageSound(isPausedItemDamageSound); + } + } + + private static JsonObject gtJson(IRecipeHandler handler, int recipeIndex) throws IllegalAccessException { + if (mRecipe == null || !(handler instanceof TemplateRecipeHandler templateHandler) + || recipeIndex >= templateHandler.arecipes.size()) { + return null; + } + + final Object cachedRecipe = templateHandler.arecipes.get(recipeIndex); + + if (!mRecipe.getDeclaringClass().isInstance(cachedRecipe)) { + return null; + } + + final Object gtRecipe = mRecipe.get(cachedRecipe); + final long eut = ((Number) mEUt.get(gtRecipe)).longValue(); + final long duration = ((Number) mDuration.get(gtRecipe)).longValue(); + final JsonObject gt = new JsonObject(); + gt.addProperty("eut", eut); + gt.addProperty("durationTicks", duration); + gt.addProperty("totalEU", eut * duration); + return gt; + } +} diff --git a/src/main/java/codechicken/nei/recipe/debug/DebugHandlerWidget.java b/src/main/java/codechicken/nei/recipe/debug/DebugHandlerWidget.java index b82398c0..683c9029 100644 --- a/src/main/java/codechicken/nei/recipe/debug/DebugHandlerWidget.java +++ b/src/main/java/codechicken/nei/recipe/debug/DebugHandlerWidget.java @@ -41,6 +41,7 @@ import codechicken.nei.recipe.GuiRecipeTab; import codechicken.nei.recipe.HandlerInfo; import codechicken.nei.recipe.IRecipeHandler; import codechicken.nei.recipe.RecipeHandlerRef; +import codechicken.nei.recipe.RecipeJsonWriter; import codechicken.nei.recipe.ShapedRecipeHandler; import codechicken.nei.recipe.TemplateRecipeHandler; import codechicken.nei.recipe.TemplateRecipeHandler.RecipeTransferRect; @@ -272,6 +273,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl API.addRecipeFilter(() -> this.duplicatesOnly ? this::isDuplicate : null); } + y = addExportWidget("ExportRecipes", y); + this.h = 10 + LINE_HEIGHT + y; this.container.h = this.h - INLINE_PADDING * 2 - LINE_HEIGHT; } @@ -332,6 +335,45 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl return y + value.h + 1; } + private int addExportWidget(String key, int y) { + final LabelWidget label = new LabelWidget(0x888888, false) { + + @Override + public List handleTooltip(int mx, int my, List tooltip) { + if (contains(mx, my)) { + super.handleTooltip(mx, my, tooltip); + tooltip.add( + EnumChatFormatting.GRAY + NEIClientUtils.translate("debug.RecipeHandler.export.tooltip")); + } + + return tooltip; + } + }; + final Button value = new Button(NEIClientUtils.translate("debug.RecipeHandler.export")) { + + @Override + public boolean onButtonPress(boolean rightclick) { + if (rightclick || !(NEIClientUtils.getGuiContainer() instanceof GuiReciperecipe)) return false; + + RecipeJsonWriter.dump(recipe.getHandler(), recipe.getFilteredRecipes()); + return true; + } + }; + + value.w = 58; + value.h = 16; + value.y = label.y = y; + value.x = this.w - INLINE_PADDING * 2 - value.w - 1; + label.w = value.x; + + label.updateValue(NEIClientUtils.translate(TOOLTIP_PREFIX + key)); + + this.container.addWidget(label); + this.container.addWidget(value); + + return y + value.h + 1; + } + private int addOverrideInfoWidget(String key, int y) { final LabelWidget label = new LabelWidget(0x888888, false); final LabelWidget value = new LabelWidget(0xffffff, true); diff --git a/src/main/resources/assets/nei/lang/en_US.lang b/src/main/resources/assets/nei/lang/en_US.lang index 91533493..69e4c78d 100644 --- a/src/main/resources/assets/nei/lang/en_US.lang +++ b/src/main/resources/assets/nei/lang/en_US.lang @@ -612,6 +612,12 @@ nei.options.tools.dump.handlers=NEI Handlers nei.options.tools.dump.handlers.dumped=handlers were dumped to %s nei.options.tools.dump.handlers.mode.0=CSV nei.options.tools.dump.handlers.mode.1=Json +nei.options.tools.dump.recipes=All Handler Recipes +nei.options.tools.dump.recipes.combined=Combined +nei.options.tools.dump.recipes.separate=Separate +nei.options.tools.dump.recipes.dumped=%s recipes were dumped to %s +nei.options.tools.dump.recipes.skipped=%s recipes threw an error and were skipped, see the log +nei.options.tools.dump.recipes.failed=Failed to dump recipes: %s nei.debug.RecipeHandler.title=Debug Recipe Handler nei.debug.RecipeHandler.copy=Copy @@ -633,6 +639,9 @@ nei.debug.RecipeHandler.DuplicatesOnly=Duplicates Only nei.debug.RecipeHandler.AllowOverflowY=Allow Overflow Y nei.debug.RecipeHandler.AllowOverflowX=Allow Overflow X nei.debug.RecipeHandler.Override=Override +nei.debug.RecipeHandler.ExportRecipes=Export Recipes +nei.debug.RecipeHandler.export=Export +nei.debug.RecipeHandler.export.tooltip=Exports the currently visible recipes to JSON. nei.debug.RecipeHandler.checkbox.on=On nei.debug.RecipeHandler.checkbox.off=Off nei.debug.RecipeHandler.yes=Yes