Search in sources :

Example 1 with JsonContext

use of net.minecraftforge.common.crafting.JsonContext in project Wizardry by TeamWizardry.

the class FireRecipeLoader method processRecipes.

public void processRecipes(Map<Ingredient, FireRecipe> recipes) {
    Wizardry.logger.info("<<========================================================================>>");
    Wizardry.logger.info("> Starting fire recipe loading.");
    JsonContext context = new JsonContext("minecraft");
    LinkedList<File> recipeFiles = new LinkedList<>();
    Stack<File> toProcess = new Stack<>();
    toProcess.push(directory);
    while (!toProcess.isEmpty()) {
        File file = toProcess.pop();
        if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null)
                for (File child : children) toProcess.push(child);
        } else if (file.isFile())
            if (file.getName().endsWith(".json"))
                recipeFiles.add(file);
    }
    for (File file : recipeFiles) {
        try {
            if (!file.exists()) {
                Wizardry.logger.error("  > SOMETHING WENT WRONG! " + file.getPath() + " can NOT be found. Ignoring file...");
                continue;
            }
            JsonElement element;
            try {
                element = new JsonParser().parse(new FileReader(file));
            } catch (FileNotFoundException e) {
                Wizardry.logger.error("  > SOMETHING WENT WRONG! " + file.getPath() + " can NOT be found. Ignoring file...");
                continue;
            }
            if (element == null) {
                Wizardry.logger.error("  > SOMETHING WENT WRONG! Could not parse " + file.getPath() + ". Ignoring file...");
                continue;
            }
            if (!element.isJsonObject()) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT contain a JsonObject. Ignoring file...: " + element.toString());
                continue;
            }
            JsonObject fileObject = element.getAsJsonObject();
            int duration = 200;
            if (!fileObject.has("input")) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT provide an initial input item. Ignoring file...: " + element.toString());
                continue;
            }
            JsonElement inputObject = fileObject.get("input");
            Ingredient input = CraftingHelper.getIngredient(inputObject, context);
            if (input == Ingredient.EMPTY) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT provide a valid input. Ignoring file...: " + element.toString());
                continue;
            }
            if (!fileObject.has("output")) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT specify a recipe output. Ignoring file...: " + element.toString());
                continue;
            }
            if (!fileObject.get("output").isJsonObject()) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT provide a valid output. Ignoring file...: " + element.toString());
                continue;
            }
            JsonObject outputObject = fileObject.get("output").getAsJsonObject();
            ItemStack output = CraftingHelper.getItemStack(outputObject, context);
            if (output.isEmpty()) {
                Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT provide a valid output. Ignoring file...: " + element.toString());
                continue;
            }
            if (fileObject.has("duration")) {
                if (!fileObject.get("duration").isJsonPrimitive() || !fileObject.getAsJsonPrimitive("duration").isNumber()) {
                    Wizardry.logger.error("  > WARNING! " + file.getPath() + " does NOT give duration as a number. Ignoring file...:" + element.toString());
                    continue;
                }
                duration = fileObject.get("duration").getAsInt();
            }
            recipes.put(input, new FireRecipe(output, duration));
        } catch (JsonParseException jsonException) {
            Wizardry.logger.error("  > WARNING! Skipping " + file.getPath() + " due to error: ", jsonException);
        }
    }
    Wizardry.logger.info("> Finished fire recipe loading.");
    Wizardry.logger.info("<<========================================================================>>");
}
Also used : FileNotFoundException(java.io.FileNotFoundException) JsonObject(com.google.gson.JsonObject) JsonParseException(com.google.gson.JsonParseException) LinkedList(java.util.LinkedList) Stack(java.util.Stack) ItemStack(net.minecraft.item.ItemStack) JsonContext(net.minecraftforge.common.crafting.JsonContext) Ingredient(net.minecraft.item.crafting.Ingredient) JsonElement(com.google.gson.JsonElement) FileReader(java.io.FileReader) ItemStack(net.minecraft.item.ItemStack) File(java.io.File) JsonParser(com.google.gson.JsonParser)

Example 2 with JsonContext

use of net.minecraftforge.common.crafting.JsonContext in project BaseMetals by MinecraftModDevelopmentMods.

the class ConfigVariedOutput method parse.

@Override
public IRecipe parse(final JsonContext context, final JsonObject json) {
    String confKey = JsonUtils.getString(json, "config_key");
    int resAmount = 0;
    switch(confKey) {
        case "gear":
            resAmount = Options.gearQuantity();
            break;
        case "plate":
            resAmount = Options.plateQuantity();
            break;
        default:
            BaseMetals.logger.error("Unknown quantity config value {}, setting to 1", confKey);
            resAmount = 1;
    }
    // load the data here, map the ingredients, setup the primer and return the ShapedOreRecipe :)
    final Map<Character, Ingredient> ingMap = Maps.newHashMap();
    JsonUtils.getJsonObject(json, "key").entrySet().stream().filter(ent -> ent.getKey().length() == 1 && !ent.getKey().isEmpty()).forEach(ent -> ingMap.put(ent.getKey().toCharArray()[0], CraftingHelper.getIngredient(ent.getValue(), context)));
    ingMap.put(' ', Ingredient.EMPTY);
    JsonArray patternJ = JsonUtils.getJsonArray(json, "pattern");
    if (patternJ.size() == 0) {
        throw new JsonSyntaxException("Invalid pattern: empty pattern not allows");
    }
    final String[] pattern = new String[patternJ.size()];
    for (int x = 0; x < pattern.length; ++x) {
        final String line = JsonUtils.getString(patternJ.get(x), "pattern[" + x + "]");
        if (x > 0 && pattern[0].length() != line.length()) {
            throw new JsonSyntaxException("Invalid pattern: each row must  be the same width");
        }
        pattern[x] = line;
    }
    final ShapedPrimer primer = new ShapedPrimer();
    primer.width = pattern[0].length();
    primer.height = pattern.length;
    primer.mirrored = true;
    primer.input = NonNullList.withSize(primer.width * primer.height, Ingredient.EMPTY);
    final Set<Character> keys = Sets.newHashSet(ingMap.keySet());
    keys.remove(' ');
    int x = 0;
    for (final String line : pattern) {
        for (final char chr : line.toCharArray()) {
            final Ingredient ing = ingMap.get(chr);
            if (ing == null) {
                throw new JsonSyntaxException("Pattern references symbol '" + chr + "' but it's not defined in the key");
            }
            primer.input.set(x++, ing);
            keys.remove(chr);
        }
    }
    if (!keys.isEmpty()) {
        throw new JsonSyntaxException("Key defines symbols that aren't used in pattern: " + keys);
    }
    final String group = JsonUtils.getString(json, "group", "");
    final ItemStack result = CraftingHelper.getItemStack(JsonUtils.getJsonObject(json, "result"), context);
    result.setCount(resAmount);
    return new ShapedOreRecipe(group.isEmpty() ? null : new ResourceLocation(group), result, primer);
}
Also used : JsonObject(com.google.gson.JsonObject) IRecipe(net.minecraft.item.crafting.IRecipe) Ingredient(net.minecraft.item.crafting.Ingredient) IRecipeFactory(net.minecraftforge.common.crafting.IRecipeFactory) JsonSyntaxException(com.google.gson.JsonSyntaxException) JsonContext(net.minecraftforge.common.crafting.JsonContext) Set(java.util.Set) ShapedOreRecipe(net.minecraftforge.oredict.ShapedOreRecipe) Maps(com.google.common.collect.Maps) Sets(com.google.common.collect.Sets) ItemStack(net.minecraft.item.ItemStack) ShapedPrimer(net.minecraftforge.common.crafting.CraftingHelper.ShapedPrimer) JsonArray(com.google.gson.JsonArray) BaseMetals(com.mcmoddev.basemetals.BaseMetals) Map(java.util.Map) JsonUtils(net.minecraft.util.JsonUtils) ResourceLocation(net.minecraft.util.ResourceLocation) NonNullList(net.minecraft.util.NonNullList) Options(com.mcmoddev.lib.util.ConfigBase.Options) CraftingHelper(net.minecraftforge.common.crafting.CraftingHelper) ShapedOreRecipe(net.minecraftforge.oredict.ShapedOreRecipe) JsonArray(com.google.gson.JsonArray) ShapedPrimer(net.minecraftforge.common.crafting.CraftingHelper.ShapedPrimer) JsonSyntaxException(com.google.gson.JsonSyntaxException) Ingredient(net.minecraft.item.crafting.Ingredient) ResourceLocation(net.minecraft.util.ResourceLocation) ItemStack(net.minecraft.item.ItemStack)

Example 3 with JsonContext

use of net.minecraftforge.common.crafting.JsonContext in project BuildCraft by BuildCraft.

the class BCSiliconRecipes method registerRecipes.

@SubscribeEvent
public static void registerRecipes(RegistryEvent.Register<IRecipe> event) {
    Loader.instance().getActiveModList().forEach((mod) -> {
        JsonContext ctx = new JsonContext(mod.getModId());
        CraftingHelper.findFiles(mod, "assets/" + mod.getModId() + "/assembly_recipes", null, (root, file) -> {
            String path = root.relativize(file).toString();
            if (!FilenameUtils.getExtension(file.toString()).equals("json"))
                return true;
            String name = FilenameUtils.removeExtension(path).replaceAll("\\\\", "/");
            ResourceLocation key = new ResourceLocation(mod.getModId(), name);
            BufferedReader reader = null;
            try {
                reader = Files.newBufferedReader(file);
                JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class);
                if (json == null || json.isJsonNull())
                    throw new JsonSyntaxException("Json is null (empty file?)");
                ItemStack output = CraftingHelper.getItemStack(json.getAsJsonObject("result"), ctx);
                long powercost = json.get("MJ").getAsLong() * MjAPI.MJ;
                ArrayList<IngredientStack> ingredients = new ArrayList<>();
                json.getAsJsonArray("components").forEach(element -> {
                    JsonObject object = element.getAsJsonObject();
                    ingredients.add(new IngredientStack(CraftingHelper.getIngredient(object.get("ingredient"), ctx), JsonUtils.getInt(object, "amount", 1)));
                });
                AssemblyRecipeRegistry.REGISTRY.put(key, new AssemblyRecipeBasic(key, powercost, ImmutableSet.copyOf(ingredients), output));
            } catch (IOException e) {
                BCLog.logger.error("Couldn't read recipe {} from {}", key, file, e);
                return false;
            } finally {
                IOUtils.closeQuietly(reader);
            }
            return true;
        });
        CraftingHelper.findFiles(mod, "assets/" + mod.getModId() + "/integration_recipes", null, (root, file) -> {
            String path = root.relativize(file).toString();
            if (!FilenameUtils.getExtension(file.toString()).equals("json"))
                return true;
            String name = FilenameUtils.removeExtension(path).replaceAll("\\\\", "/");
            ResourceLocation key = new ResourceLocation(mod.getModId(), name);
            BufferedReader reader = null;
            try {
                reader = Files.newBufferedReader(file);
                JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class);
                if (json == null || json.isJsonNull())
                    throw new JsonSyntaxException("Json is null (empty file?)");
                ItemStack output = CraftingHelper.getItemStack(json.getAsJsonObject("result"), ctx);
                IngredientStack centerStack = IngredientStack.of(CraftingHelper.getIngredient(json.getAsJsonObject("centerStack"), ctx));
                long powercost = json.get("MJ").getAsLong() * MjAPI.MJ;
                ArrayList<IngredientStack> ingredients = new ArrayList<>();
                json.getAsJsonArray("components").forEach(element -> {
                    JsonObject object = element.getAsJsonObject();
                    ingredients.add(new IngredientStack(CraftingHelper.getIngredient(object.get("ingredient"), ctx), JsonUtils.getInt(object, "amount", 1)));
                });
                IntegrationRecipeRegistry.INSTANCE.addRecipe(new IntegrationRecipeBasic(key, powercost, centerStack, ingredients, output));
            } catch (IOException e) {
                BCLog.logger.error("Couldn't read recipe {} from {}", key, file, e);
                return false;
            } finally {
                IOUtils.closeQuietly(reader);
            }
            return true;
        });
    });
}
Also used : ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) JsonContext(net.minecraftforge.common.crafting.JsonContext) AssemblyRecipeBasic(buildcraft.api.recipes.AssemblyRecipeBasic) IntegrationRecipeBasic(buildcraft.lib.recipe.IntegrationRecipeBasic) JsonSyntaxException(com.google.gson.JsonSyntaxException) ResourceLocation(net.minecraft.util.ResourceLocation) BufferedReader(java.io.BufferedReader) ItemStack(net.minecraft.item.ItemStack) IngredientStack(buildcraft.api.recipes.IngredientStack) SubscribeEvent(net.minecraftforge.fml.common.eventhandler.SubscribeEvent)

Example 4 with JsonContext

use of net.minecraftforge.common.crafting.JsonContext in project Gaspunk by Ladysnake.

the class GasRecipeDeserializer method loadRecipes.

private static void loadRecipes(ModContainer container) {
    Loader.instance().setActiveModContainer(container);
    JsonContext context = new JsonContext(container.getModId());
    CraftingHelper.findFiles(container, "assets/" + container.getModId() + "/gaspunk_recipes", p -> true, (root, file) -> loadRecipes(root, file, context), true, true);
}
Also used : JsonContext(net.minecraftforge.common.crafting.JsonContext)

Example 5 with JsonContext

use of net.minecraftforge.common.crafting.JsonContext in project Gaspunk by Ladysnake.

the class GasRecipeDeserializer method loadRecipes.

@SubscribeEvent
public static void loadRecipes(RegistryEvent.Register<IRecipe> event) {
    ModContainer gaspunkContainer = Loader.instance().activeModContainer();
    Loader.instance().getActiveModList().forEach(GasRecipeDeserializer::loadRecipes);
    Loader.instance().setActiveModContainer(gaspunkContainer);
    File configFolder = new File(Loader.instance().getConfigDir(), GasPunk.MOD_ID + "/custom_recipes");
    // if the config folder was just created or couldn't be created, no need to search it
    try {
        if (!configFolder.mkdirs() && configFolder.exists()) {
            JsonContext context = new JsonContext(GasPunk.MOD_ID);
            try {
                Files.walk(configFolder.toPath()).forEach(path -> loadRecipes(configFolder.toPath(), path, context));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (configFolder.exists()) {
            JsonObject recipe = new JsonObject();
            recipe.addProperty("result", "gaspunk:colored_smoke_red");
            JsonObject input = new JsonObject();
            input.addProperty("item", "minecraft:water_bucket");
            recipe.add("input", input);
            JsonObject ingredient = new JsonObject();
            ingredient.addProperty("type", "forge:ore_dict");
            ingredient.addProperty("ore", "dustRedstone");
            recipe.add("ingredient", ingredient);
            recipe.addProperty("result", "gaspunk:colored_smoke_red");
            Files.write(configFolder.toPath().resolve("_example.json"), GSON.toJson(recipe).getBytes(), StandardOpenOption.CREATE_NEW);
        }
    } catch (IOException e) {
        GasPunk.LOGGER.error("Error while loading gas recipes from config", e);
    }
}
Also used : JsonContext(net.minecraftforge.common.crafting.JsonContext) ModContainer(net.minecraftforge.fml.common.ModContainer) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) File(java.io.File) SubscribeEvent(net.minecraftforge.fml.common.eventhandler.SubscribeEvent)

Aggregations

JsonContext (net.minecraftforge.common.crafting.JsonContext)6 JsonObject (com.google.gson.JsonObject)5 ItemStack (net.minecraft.item.ItemStack)4 File (java.io.File)3 Ingredient (net.minecraft.item.crafting.Ingredient)3 ResourceLocation (net.minecraft.util.ResourceLocation)3 JsonArray (com.google.gson.JsonArray)2 JsonElement (com.google.gson.JsonElement)2 JsonParser (com.google.gson.JsonParser)2 JsonSyntaxException (com.google.gson.JsonSyntaxException)2 FileNotFoundException (java.io.FileNotFoundException)2 FileReader (java.io.FileReader)2 IOException (java.io.IOException)2 SubscribeEvent (net.minecraftforge.fml.common.eventhandler.SubscribeEvent)2 AssemblyRecipeBasic (buildcraft.api.recipes.AssemblyRecipeBasic)1 IngredientStack (buildcraft.api.recipes.IngredientStack)1 IntegrationRecipeBasic (buildcraft.lib.recipe.IntegrationRecipeBasic)1 Maps (com.google.common.collect.Maps)1 Sets (com.google.common.collect.Sets)1 JsonParseException (com.google.gson.JsonParseException)1