diff --git a/build.gradle b/build.gradle index a61026b..f1cf7b0 100644 --- a/build.gradle +++ b/build.gradle @@ -34,6 +34,8 @@ minecraft { repositories { mavenCentral() + maven { url "http://server.bbkr.space:8081/artifactory/libs-snapshot/" } + maven { url "http://server.bbkr.space:8081/artifactory/libs-release/" } } dependencies { @@ -45,6 +47,9 @@ dependencies { // Fabric API. This is technically optional, but you probably want it anyway. modCompile "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + modCompile "io.github.cottonmc:LibCD:${project.libcd_version}" + include "io.github.cottonmc:LibCD:${project.libcd_version}" + compileOnly ("com.google.code.findbugs:jsr305:3.0.2") { transitive = false } implementation ("blue.endless:jankson:1.1.2") { transitive = false } shadow ("blue.endless:jankson:1.1.2") { transitive = false } diff --git a/gradle.properties b/gradle.properties index 9473fa9..cc3bbef 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,10 +8,11 @@ loader_version=0.4.8+build.154 # Mod Properties - mod_version = 0.7.5+1.14.2 + mod_version = 0.7.6+1.14.2 maven_group = io.github.cottonmc archives_base_name = cotton # Dependencies # currently not on the main fabric site, check on the maven: https://maven.fabricmc.net/net/fabricmc/fabric fabric_version=0.3.0-pre+build.156 + libcd_version=1.1.0+1.14.2 diff --git a/src/main/java/io/github/cottonmc/cotton/Cotton.java b/src/main/java/io/github/cottonmc/cotton/Cotton.java index e27b706..ae18410 100644 --- a/src/main/java/io/github/cottonmc/cotton/Cotton.java +++ b/src/main/java/io/github/cottonmc/cotton/Cotton.java @@ -8,18 +8,13 @@ import io.github.cottonmc.cotton.logging.ModLogger; import io.github.cottonmc.cotton.registry.CommonTags; import io.github.cottonmc.cotton.tweaker.*; +import io.github.cottonmc.libcd.tweaker.Tweaker; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder; -import net.fabricmc.fabric.api.resource.ResourceManagerHelper; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.block.Blocks; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.potion.Potion; -import net.minecraft.potion.PotionUtil; -import net.minecraft.potion.Potions; -import net.minecraft.resource.ResourceType; import net.minecraft.util.Identifier; import java.io.File; @@ -42,14 +37,7 @@ public void onInitialize() { //setup PackMetaManager.saveMeta(); CottonRecipes.init(); - ResourceManagerHelper.get(ResourceType.SERVER_DATA).registerReloadListener(new TweakerLoader()); Tweaker.addTweaker(CauldronTweaker.INSTANCE); - Tweaker.addTweaker(RecipeTweaker.INSTANCE); - TweakerStackGetter.registerGetter(new Identifier("minecraft", "potion"), (id) -> { - Potion potion = Potion.byId(id.toString()); - if (potion == Potions.EMPTY) return ItemStack.EMPTY; - return PotionUtil.setPotion(new ItemStack(Items.POTION), potion); - }); //example config and logger code config = ConfigManager.loadConfig(CottonConfig.class); diff --git a/src/main/java/io/github/cottonmc/cotton/impl/RecipeMapAccessor.java b/src/main/java/io/github/cottonmc/cotton/impl/RecipeMapAccessor.java deleted file mode 100644 index 76992bd..0000000 --- a/src/main/java/io/github/cottonmc/cotton/impl/RecipeMapAccessor.java +++ /dev/null @@ -1,11 +0,0 @@ -package io.github.cottonmc.cotton.impl; - -import net.minecraft.recipe.Recipe; -import net.minecraft.recipe.RecipeType; -import net.minecraft.util.Identifier; - -import java.util.Map; - -public interface RecipeMapAccessor { - Map, Map>> getRecipeMap(); -} diff --git a/src/main/java/io/github/cottonmc/cotton/impl/ReloadListenersAccessor.java b/src/main/java/io/github/cottonmc/cotton/impl/ReloadListenersAccessor.java deleted file mode 100644 index 7d8b86c..0000000 --- a/src/main/java/io/github/cottonmc/cotton/impl/ReloadListenersAccessor.java +++ /dev/null @@ -1,9 +0,0 @@ -package io.github.cottonmc.cotton.impl; - -import net.minecraft.resource.ResourceReloadListener; - -import java.util.List; - -public interface ReloadListenersAccessor { - List cotton_getListeners(); -} diff --git a/src/main/java/io/github/cottonmc/cotton/mixins/MixinIngredient.java b/src/main/java/io/github/cottonmc/cotton/mixins/MixinIngredient.java index de3f44e..9caa128 100644 --- a/src/main/java/io/github/cottonmc/cotton/mixins/MixinIngredient.java +++ b/src/main/java/io/github/cottonmc/cotton/mixins/MixinIngredient.java @@ -1,16 +1,7 @@ package io.github.cottonmc.cotton.mixins; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSyntaxException; -import io.github.cottonmc.cotton.tweaker.TweakerUtils; -import net.minecraft.item.ItemStack; import net.minecraft.recipe.Ingredient; -import net.minecraft.util.JsonHelper; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(Ingredient.class) public class MixinIngredient { diff --git a/src/main/java/io/github/cottonmc/cotton/mixins/MixinRecipeManager.java b/src/main/java/io/github/cottonmc/cotton/mixins/MixinRecipeManager.java index a800b56..05361c5 100644 --- a/src/main/java/io/github/cottonmc/cotton/mixins/MixinRecipeManager.java +++ b/src/main/java/io/github/cottonmc/cotton/mixins/MixinRecipeManager.java @@ -5,7 +5,6 @@ import java.util.Map; import java.util.function.Predicate; -import io.github.cottonmc.cotton.impl.RecipeMapAccessor; import net.minecraft.recipe.RecipeType; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -22,16 +21,13 @@ import net.minecraft.util.Identifier; @Mixin(RecipeManager.class) -public class MixinRecipeManager implements RecipeMapAccessor { +public class MixinRecipeManager { @Shadow @Final public static int PREFIX_LENGTH; @Shadow @Final public static int SUFFIX_LENGTH; - @Shadow - @Final - private Map, Map>> recipeMap; @ModifyVariable(method = "apply", at = @At(value = "INVOKE_ASSIGN", target = "Ljava/util/Collection;iterator()Ljava/util/Iterator;", ordinal = 0, remap = false)) public Iterator filterIterator(Iterator iterator) { @@ -61,8 +57,4 @@ public void mixinAdd(Recipe recipe, CallbackInfo info) { } } - @Override - public Map, Map>> getRecipeMap() { - return recipeMap; - } } diff --git a/src/main/java/io/github/cottonmc/cotton/mixins/MixinResourceManagerImpl.java b/src/main/java/io/github/cottonmc/cotton/mixins/MixinResourceManagerImpl.java deleted file mode 100644 index b00ae1e..0000000 --- a/src/main/java/io/github/cottonmc/cotton/mixins/MixinResourceManagerImpl.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.github.cottonmc.cotton.mixins; - -import io.github.cottonmc.cotton.impl.ReloadListenersAccessor; -import net.minecraft.resource.ReloadableResourceManagerImpl; -import net.minecraft.resource.ResourceReloadListener; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -import java.util.List; - -@Mixin(ReloadableResourceManagerImpl.class) -public class MixinResourceManagerImpl implements ReloadListenersAccessor { - - @Shadow @Final private List listeners; - - @Override - public List cotton_getListeners() { - return listeners; - } -} diff --git a/src/main/java/io/github/cottonmc/cotton/tweaker/CauldronTweaker.java b/src/main/java/io/github/cottonmc/cotton/tweaker/CauldronTweaker.java index 80f4202..6b38e50 100644 --- a/src/main/java/io/github/cottonmc/cotton/tweaker/CauldronTweaker.java +++ b/src/main/java/io/github/cottonmc/cotton/tweaker/CauldronTweaker.java @@ -2,6 +2,7 @@ import io.github.cottonmc.cotton.cauldron.CauldronBehavior; import io.github.cottonmc.cotton.cauldron.CauldronContext; +import io.github.cottonmc.libcd.tweaker.Tweaker; import net.minecraft.entity.*; import net.minecraft.entity.mob.MobEntity; import net.minecraft.entity.player.PlayerEntity; diff --git a/src/main/java/io/github/cottonmc/cotton/tweaker/RecipeParser.java b/src/main/java/io/github/cottonmc/cotton/tweaker/RecipeParser.java deleted file mode 100644 index 5b75655..0000000 --- a/src/main/java/io/github/cottonmc/cotton/tweaker/RecipeParser.java +++ /dev/null @@ -1,217 +0,0 @@ -package io.github.cottonmc.cotton.tweaker; - -import com.google.common.collect.Sets; -import io.github.cottonmc.cotton.Cotton; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.recipe.Ingredient; -import net.minecraft.tag.ItemTags; -import net.minecraft.tag.Tag; -import net.minecraft.util.DefaultedList; -import net.minecraft.util.Identifier; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * Helper class to make public versions private recipe methods - */ -public class RecipeParser { - - /** - * Get an Ingredient from a string item or tag id. - * @param input The id to use, with a # at the front if it's a tag or -> between two ids for a getter - * @return the Ingredient for the given id - */ - public static Ingredient processIngredient(String input) throws TweakerSyntaxException { - if (input.indexOf('#') == 0) { - String tag = input.substring(1); - Tag itemTag = ItemTags.getContainer().get(new Identifier(tag)); - if (itemTag == null) throw new TweakerSyntaxException("Failed to get item tag for input: " + input); - return Ingredient.fromTag(itemTag); - } else if (input.indexOf('&') == 0) { - Cotton.logger.warn("Use of deprecated potion-getting method in '" + input + "', this will be removed soon!"); - ItemStack stack = TweakerUtils.getPotion(input.substring(1)); - if (stack.isEmpty()) throw new TweakerSyntaxException("Failed to get potion for input: " + input); - return Ingredient.ofStacks(stack); - } else if (input.contains("->")) { - ItemStack stack = TweakerUtils.getSpecialStack(input); - if (stack.isEmpty()) throw new TweakerSyntaxException("Failed to get special stack for input: " + input); - return Ingredient.ofStacks(stack); - } else { - Item item = TweakerUtils.getItem(input); - if (item == Items.AIR) throw new TweakerSyntaxException("Failed to get item for input: " + input); - return Ingredient.ofItems(item); - } - } - - /** - * Split a getter string into the ids of the getter/id. - * @param base The base getter string to split. - * @return A two-item array of the two parts of the getter. - */ - static String[] processGetter(String base) { - String[] split = new String[2]; - int splitter = base.indexOf("->"); - split[0] = base.substring(0, splitter); - split[1] = base.substring(splitter + 2); - return split; - } - - /** - * Process a grid of inputs CraftTweaker-style. - * @param inputs The array of string arrays to process inputs from - * @return The inputs converted into a single string array if the grid is valid - */ - public static String[] processGrid(String[][] inputs) throws TweakerSyntaxException { - if (inputs.length > 3) throw new TweakerSyntaxException("Invalid pattern: too many columns, 3 is maximum"); - if (inputs.length == 0) throw new TweakerSyntaxException("Invalid pattern: empty pattern is not allowed"); - int width = inputs[0].length; - String[] output = new String[inputs.length * inputs[0].length]; - for (int i = 0; i < inputs.length; i++) { - String[] row = inputs[i]; - if (row.length > 3) throw new TweakerSyntaxException("Invalid pattern: too many columns, 3 is maximum"); - if (row.length != width) throw new TweakerSyntaxException("Invalid pattern: each row must be the same width"); - for (int j = 0; j < width; j++) { - output[j + inputs.length * i] = inputs[i][j]; - } - } - return output; - } - - /** - * validate and parse a recipe pattern. - * @param pattern up to three strings of up to three characters each for the pattern - * @return processed pattern - */ - public static String[] processPattern(String... pattern) throws TweakerSyntaxException { - if (pattern.length > 3) { - throw new TweakerSyntaxException("Invalid pattern: too many rows, 3 is maximum"); - } else if (pattern.length == 0) { - throw new TweakerSyntaxException("Invalid pattern: empty pattern not allowed"); - } else { - for (int i = 0; i < pattern.length; i++) { - String row = pattern[i]; - if (row.length() > 3) { - throw new TweakerSyntaxException("Invalid pattern: too many columns, 3 is maximum"); - } - - if (i > 0 && pattern[0].length() != row.length()) { - throw new TweakerSyntaxException("Invalid pattern: each row must be the same width"); - } - - pattern[i] = row; - } - int nextIndex = 2147483647; - int highIndex = 0; - int checked = 0; - int sinceLastEmpty = 0; - - for (int i = 0; i < pattern.length; ++i) { - String input = pattern[i]; - nextIndex = Math.min(nextIndex, findNextIngredient(input)); - int lastIndex = findNextIngredientReverse(input); - highIndex = Math.max(highIndex, lastIndex); - if (lastIndex < 0) { - if (checked == i) { - ++checked; - } - - ++sinceLastEmpty; - } else { - sinceLastEmpty = 0; - } - } - - if (pattern.length == sinceLastEmpty) { - return new String[0]; - } else { - String[] combined = new String[pattern.length - sinceLastEmpty - checked]; - - for (int i = 0; i < combined.length; ++i) { - combined[i] = pattern[i + checked].substring(nextIndex, highIndex + 1); - } - - return combined; - } - } - } - - /** - * Process dictionaries into a Recipe-readable form. - * @param dictionary a map of keys to values for a recipe to parse. - * @return A map of string keys to ingredient values that a Recipe can read. - */ - public static Map processDictionary(Map dictionary) throws TweakerSyntaxException { - Map map = new HashMap<>(); - for (Map.Entry entry : dictionary.entrySet()) { - if (entry.getKey().length() != 1) { - throw new TweakerSyntaxException("Invalid key entry: '" + entry.getKey() + "' is an invalid symbol (must be 1 character only)."); - } - - if (" ".equals(entry.getKey())) { - throw new TweakerSyntaxException("Invalid key entry: ' ' is a reserved symbol."); - } - map.put(entry.getKey(), processIngredient(entry.getValue())); - } - map.put(" ", Ingredient.EMPTY); - return map; - } - - /** - * Compile a pattern and dictionary into a full ingredient list. - * @param pattern A patern parsed by processPattern. - * @param dictionary A dictionary parsed by processDictionary. - * @param x How many columns there are. - * @param y How many rows there are. - * @return A defaulted list of ingredients. - */ - public static DefaultedList getIngredients(String[] pattern, Map dictionary, int x, int y) throws TweakerSyntaxException { - DefaultedList ingredients = DefaultedList.create(x * y, Ingredient.EMPTY); - Set keys = Sets.newHashSet(dictionary.keySet()); - keys.remove(" "); - - for(int i = 0; i < pattern.length; i++) { - for(int j = 0; j < pattern[i].length(); j++) { - String key = pattern[i].substring(j, j + 1); - Ingredient ingredient = dictionary.get(key); - if (ingredient == null) { - throw new TweakerSyntaxException("Pattern references symbol '" + key + "' but it's not defined in the key"); - } - - keys.remove(key); - ingredients.set(j + x * i, ingredient); - } - } - - if (!keys.isEmpty()) { - throw new TweakerSyntaxException("Key defines symbols that aren't used in pattern: " + keys); - } else { - return ingredients; - } - } - - /** - * Skip forwards through a recipe row to find an ingredient key - * @param input a recipe row to parse - * @return index for the next ingredient character - */ - private static int findNextIngredient(String input) { - int i; - for (i = 0; i < input.length() && input.charAt(i) == ' '; i++) { } - return i; - } - - /** - * Skip backwards through a recipe row to find an ingredient key - * @param input a recipe row to parse - * @return index for the next ingredient character - */ - private static int findNextIngredientReverse(String input) { - int i; - for (i = input.length() - 1; i >= 0 && input.charAt(i) == ' '; i--) { } - return i; - } -} diff --git a/src/main/java/io/github/cottonmc/cotton/tweaker/RecipeTweaker.java b/src/main/java/io/github/cottonmc/cotton/tweaker/RecipeTweaker.java index 8edd6f4..d144ea0 100644 --- a/src/main/java/io/github/cottonmc/cotton/tweaker/RecipeTweaker.java +++ b/src/main/java/io/github/cottonmc/cotton/tweaker/RecipeTweaker.java @@ -1,79 +1,22 @@ package io.github.cottonmc.cotton.tweaker; -import io.github.cottonmc.cotton.Cotton; -import io.github.cottonmc.cotton.impl.RecipeMapAccessor; -import io.github.cottonmc.cotton.impl.ReloadListenersAccessor; import net.minecraft.item.ItemStack; import net.minecraft.recipe.*; -import net.minecraft.resource.ResourceManager; -import net.minecraft.resource.ResourceReloadListener; -import net.minecraft.util.DefaultedList; -import net.minecraft.util.Identifier; -import net.minecraft.util.registry.Registry; -import java.util.List; import java.util.Map; -public class RecipeTweaker implements Tweaker { - public static final RecipeTweaker INSTANCE = new RecipeTweaker(); - private RecipeManager manager; - private int recipeCount; - private int removeCount; - - /** - * Used during data pack loading to set up recipe adding. - * DO NOT CALL THIS YOURSELF, EVER. IT WILL LIKELY MESS THINGS UP. - */ - @Override - public void prepareReload(ResourceManager manager) { - recipeCount = 0; - removeCount = 0; - if (manager instanceof ReloadListenersAccessor) { - List listeners = ((ReloadListenersAccessor)manager).cotton_getListeners(); - for (ResourceReloadListener listener : listeners) { - if (listener instanceof RecipeManager) { - this.manager = (RecipeManager)listener; - return; - } - } - Cotton.logger.error("No recipe manager was found! Tweaker cannot register recipes!"); - throw new IllegalStateException("No recipe manager was found! Tweaker cannot register recipes!"); - } - Cotton.logger.error("No reload listeners accessor found! Tweaker cannot register recipes!"); - throw new IllegalStateException("No reload listeners accessor found! Tweaker cannot register recipes!"); - } - - @Override - public String getApplyMessage() { - return recipeCount + " " + (recipeCount == 1? "recipe" : "recipes" + (removeCount == 0? "" : " (" + removeCount + " removed)")); - } - - /** - * Generate a recipe ID. Call this from Java tweaker classes. - * @param output The output stack of the recipe. - * @return A unique identifier for the recipe. - */ - public static Identifier getRecipeId(ItemStack output) { - String resultName = Registry.ITEM.getId(output.getItem()).getPath(); - return new Identifier(Cotton.MODID, "tweaked/"+resultName+"-"+INSTANCE.recipeCount); - } +/** + * Use {@link io.github.cottonmc.libcd.tweaker.RecipeTweaker} + */ +@Deprecated +public class RecipeTweaker { /** * Remove a recipe from the recipe manager. * @param id The id of the recipe to remove. */ public static void removeRecipe(String id) { - Identifier recipeId = new Identifier(id); - Map, Map>> recipeMap = ((RecipeMapAccessor)INSTANCE.manager).getRecipeMap(); - for (RecipeType type : recipeMap.keySet()) { - Map> map = recipeMap.get(type); - if (map.containsKey(recipeId)) { - map.remove(recipeId); - INSTANCE.removeCount++; - return; - } - } - Cotton.logger.error("Could not find recipe to remove: " + id); + io.github.cottonmc.libcd.tweaker.RecipeTweaker.removeRecipe(id); } /** @@ -81,12 +24,7 @@ public static void removeRecipe(String id) { * @param recipe A constructed recipe. */ public static void addRecipe(Recipe recipe) { - INSTANCE.recipeCount++; - try { - INSTANCE.manager.add(recipe); - } catch (Exception e) { - Cotton.logger.error("Failed to add recipe from tweaker - " + e.getMessage()); - } + io.github.cottonmc.libcd.tweaker.RecipeTweaker.addRecipe(recipe); } /** @@ -109,14 +47,7 @@ public static void addShaped(String[][] inputs, ItemStack output) { * @param group The recipe group to go in, or "" for none. */ public static void addShaped(String[][] inputs, ItemStack output, String group) { - try { - String[] processed = RecipeParser.processGrid(inputs); - int width = inputs[0].length; - int height = inputs.length; - addShaped(processed, output, width, height, group); - } catch (Exception e) { - Cotton.logger.error("Error parsing shaped recipe - " + e.getMessage()); - } + io.github.cottonmc.libcd.tweaker.RecipeTweaker.addShaped(inputs, output, group); } public static void addShaped(String[] inputs, ItemStack output, int width, int height) { @@ -132,18 +63,7 @@ public static void addShaped(String[] inputs, ItemStack output, int width, int h * @param group The recipe group to go in, or "" for none. */ public static void addShaped(String[] inputs, ItemStack output, int width, int height, String group){ - Identifier recipeId = getRecipeId(output); - try { - DefaultedList ingredients = DefaultedList.create(); - for (int i = 0; i < Math.min(inputs.length, width * height); i++) { - String id = inputs[i]; - if (id.equals("")) continue; - ingredients.add(i, RecipeParser.processIngredient(id)); - } - addRecipe(new ShapedRecipe(recipeId, group, width, height, ingredients, output)); - } catch (Exception e) { - Cotton.logger.error("Error parsing shaped recipe - " + e.getMessage()); - } + io.github.cottonmc.libcd.tweaker.RecipeTweaker.addShaped(inputs, output, width, height, group); } public static void addShaped(String[] pattern, Map dictionary, ItemStack output) { @@ -158,17 +78,7 @@ public static void addShaped(String[] pattern, Map dictionary, I * @param group The recipe group to go in, or "" for none. */ public static void addShaped(String[] pattern, Map dictionary, ItemStack output, String group) { - Identifier recipeId = getRecipeId(output); - try { - pattern = RecipeParser.processPattern(pattern); - Map map = RecipeParser.processDictionary(dictionary); - int x = pattern[0].length(); - int y = pattern.length; - DefaultedList ingredients = RecipeParser.getIngredients(pattern, map, x, y); - addRecipe(new ShapedRecipe(recipeId, group, x, y, ingredients, output)); - } catch (Exception e) { - Cotton.logger.error("Error parsing shaped recipe - " + e.getMessage()); - } + io.github.cottonmc.libcd.tweaker.RecipeTweaker.addShaped(pattern, dictionary, output, group); } public static void addShapeless(String[] inputs, ItemStack output) { @@ -182,18 +92,7 @@ public static void addShapeless(String[] inputs, ItemStack output) { * @param group The recipe group to go in, or "" for none. */ public static void addShapeless(String[] inputs, ItemStack output, String group) { - Identifier recipeId = getRecipeId(output); - try { - DefaultedList ingredients = DefaultedList.create(); - for (int i = 0; i < Math.min(inputs.length, 9); i++) { - String id = inputs[i]; - if (id.equals("")) continue; - ingredients.add(i, RecipeParser.processIngredient(id)); - } - addRecipe(new ShapelessRecipe(recipeId, group, output, ingredients)); - } catch (Exception e) { - Cotton.logger.error("Error parsing shapeless recipe - " + e.getMessage()); - } + io.github.cottonmc.libcd.tweaker.RecipeTweaker.addShapeless(inputs, output, group); } public static void addSmelting(String input, ItemStack output, int ticks, float xp) { @@ -209,13 +108,7 @@ public static void addSmelting(String input, ItemStack output, int ticks, float * @param group The recipe group to go in, or "" for none. */ public static void addSmelting(String input, ItemStack output, int cookTime, float xp, String group) { - Identifier recipeId = getRecipeId(output); - try { - Ingredient ingredient = RecipeParser.processIngredient(input); - addRecipe(new SmeltingRecipe(recipeId, group, ingredient, output, xp, cookTime)); - } catch (Exception e) { - Cotton.logger.error("Error parsing smelting recipe - " + e.getMessage()); - } + io.github.cottonmc.libcd.tweaker.RecipeTweaker.addSmelting(input, output, cookTime, xp, group); } public static void addBlasting(String input, ItemStack output, int ticks, float xp) { @@ -231,13 +124,7 @@ public static void addBlasting(String input, ItemStack output, int ticks, float * @param group The recipe group to go in, or "" for none. */ public static void addBlasting(String input, ItemStack output, int cookTime, float xp, String group) { - Identifier recipeId = getRecipeId(output); - try { - Ingredient ingredient = RecipeParser.processIngredient(input); - addRecipe(new BlastingRecipe(recipeId, group, ingredient, output, xp, cookTime)); - } catch (Exception e) { - Cotton.logger.error("Error parsing blasting recipe - " + e.getMessage()); - } + io.github.cottonmc.libcd.tweaker.RecipeTweaker.addBlasting(input, output, cookTime, xp, group); } public static void addSmoking(String input, ItemStack output, int ticks, float xp) { @@ -253,13 +140,7 @@ public static void addSmoking(String input, ItemStack output, int ticks, float x * @param group The recipe group to go in, or "" for none. */ public static void addSmoking(String input, ItemStack output, int cookTime, float xp, String group) { - Identifier recipeId = getRecipeId(output); - try { - Ingredient ingredient = RecipeParser.processIngredient(input); - addRecipe(new SmokingRecipe(recipeId, group, ingredient, output, xp, cookTime)); - } catch (Exception e) { - Cotton.logger.error("Error parsing smokig recipe - " + e.getMessage()); - } + io.github.cottonmc.libcd.tweaker.RecipeTweaker.addSmoking(input, output, cookTime, xp, group); } public static void addCampfire(String input, ItemStack output, int ticks, float xp) { @@ -275,13 +156,7 @@ public static void addCampfire(String input, ItemStack output, int ticks, float * @param group The recipe group to go in, or "" for none. */ public static void addCampfire(String input, ItemStack output, int cookTime, float xp, String group) { - Identifier recipeId = getRecipeId(output); - try { - Ingredient ingredient = RecipeParser.processIngredient(input); - addRecipe(new CampfireCookingRecipe(recipeId, group, ingredient, output, xp, cookTime)); - } catch (Exception e) { - Cotton.logger.error("Error parsing campfire recipe - " + e.getMessage()); - } + io.github.cottonmc.libcd.tweaker.RecipeTweaker.addCampfire(input, output, cookTime, xp, group); } public static void addStonecutting(String input, ItemStack output) { @@ -295,13 +170,7 @@ public static void addStonecutting(String input, ItemStack output) { * @param group The recipe group to go in, or "" for none. */ public static void addStonecutting(String input, ItemStack output, String group) { - Identifier recipeId = getRecipeId(output); - try { - Ingredient ingredient = RecipeParser.processIngredient(input); - addRecipe(new StonecuttingRecipe(recipeId, group, ingredient, output)); - } catch (Exception e) { - Cotton.logger.error("Error parsing stonecutter recipe - " + e.getMessage()); - } + io.github.cottonmc.libcd.tweaker.RecipeTweaker.addStonecutting(input, output, group); } } diff --git a/src/main/java/io/github/cottonmc/cotton/tweaker/Tweaker.java b/src/main/java/io/github/cottonmc/cotton/tweaker/Tweaker.java deleted file mode 100644 index 2823804..0000000 --- a/src/main/java/io/github/cottonmc/cotton/tweaker/Tweaker.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.github.cottonmc.cotton.tweaker; - -import net.minecraft.resource.ResourceManager; - -import java.util.ArrayList; -import java.util.List; - -public interface Tweaker { - List TWEAKERS = new ArrayList<>(); - - /** - * Add a new tweaker to store data in. - * @param tweaker an instanceof Tweaker to call whenever reloading. - */ - static void addTweaker(Tweaker tweaker) { - TWEAKERS.add(tweaker); - } - - /** - * Called whenever the /reload command is run, before scripts are applied. - * Use this time to empty out any lists or maps you need to. - * @param manager The ResourceManager reloading tweakers. - */ - void prepareReload(ResourceManager manager); - - /** - * Called after all scripts have been run, to log what tweakers have been applied. - * @return The number of applied tweaks and the description of what type of tweak it is, ex. "12 recipes" - */ - String getApplyMessage(); -} diff --git a/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerLoader.java b/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerLoader.java deleted file mode 100644 index f074769..0000000 --- a/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerLoader.java +++ /dev/null @@ -1,97 +0,0 @@ -package io.github.cottonmc.cotton.tweaker; - -import io.github.cottonmc.cotton.Cotton; -import net.fabricmc.fabric.api.resource.SimpleResourceReloadListener; -import net.minecraft.resource.Resource; -import net.minecraft.resource.ResourceManager; -import net.minecraft.util.Identifier; -import net.minecraft.util.profiler.Profiler; -import org.apache.commons.io.IOUtils; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; -import java.io.IOException; -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; - -public class TweakerLoader implements SimpleResourceReloadListener { - public static Map TWEAKERS = new HashMap<>(); - public static final ScriptEngineManager SCRIPT_MANAGER = new ScriptEngineManager(); - - @Override - public CompletableFuture load(ResourceManager manager, Profiler profiler, Executor executor) { - return CompletableFuture.supplyAsync(() -> { - TWEAKERS.clear(); - Collection resources = manager.findResources("tweakers", name -> true); - for (Identifier fileId : resources) { - try { - Resource res = manager.getResource(fileId); - String script = IOUtils.toString(res.getInputStream()); - int localPath = fileId.getPath().indexOf('/')+1; - Identifier scriptId = new Identifier(fileId.getNamespace(), fileId.getPath().substring(localPath)); - TWEAKERS.put(scriptId, script); - } catch (IOException e) { - Cotton.logger.error("Error when accessing tweaker script %s: %s", fileId.toString(), e.getMessage()); - } - } - return TWEAKERS; - }); - } - - @Override - public CompletableFuture apply(Object o, ResourceManager manager, Profiler profiler, Executor executor) { - return CompletableFuture.runAsync(() -> { - for (Tweaker tweaker : Tweaker.TWEAKERS) { - tweaker.prepareReload(manager); - } - int loaded = 0; - for (Identifier tweaker : TWEAKERS.keySet()) { - String extension = tweaker.getPath().substring(tweaker.getPath().lastIndexOf('.') + 1); - String script = TWEAKERS.get(tweaker); - if (script == null) { - Cotton.logger.error("Tweaker script not found: " + tweaker.toString()); - continue; - } - ScriptEngine engine = SCRIPT_MANAGER.getEngineByExtension(extension); - if (engine == null) { - Cotton.logger.error("Engine for tweaker script not found: " + tweaker.toString()); - continue; - } - try { - engine.eval(script); - } catch (ScriptException e) { - Cotton.logger.error("Error executing tweaker script %s: %s", tweaker.toString(), e.getMessage()); - continue; - } - loaded++; - } - List applied = new ArrayList<>(); - for (Tweaker tweaker : Tweaker.TWEAKERS) { - applied.add(tweaker.getApplyMessage()); - } - String confirm = formatApplied(applied); - Cotton.logger.info("Applied %s tweaker %s, including %s", loaded, (loaded == 1? "script" : "scripts"), confirm); - }); - } - - public String formatApplied(List messages) { - StringBuilder ret = new StringBuilder(); - for (int i = 0; i < messages.size(); i++) { - String message = messages.get(i); - ret.append(message); - if (i < messages.size() - 1) { - if (messages.size() <= 2) ret.append(" "); - else ret.append(", "); - } - if (i == messages.size() - 2) ret.append("and "); - } - return ret.toString(); - } - - @Override - public Identifier getFabricId() { - return new Identifier(Cotton.MODID, "tweak_loader"); - } -} diff --git a/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerStackGetter.java b/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerStackGetter.java deleted file mode 100644 index de12789..0000000 --- a/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerStackGetter.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.github.cottonmc.cotton.tweaker; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; - -import java.util.HashMap; -import java.util.Map; - -/** - * Some ItemStacks, like vanilla potions, have entirely different functions and names based on NBT. - * Because of that, it's hard to use those stacks in recipes. - * CottonTweaker uses a "[getter id]->[entry id]" syntax to get those recipes - */ -public interface TweakerStackGetter { - public static Map GETTERS = new HashMap<>(); - - static void registerGetter(Identifier id, TweakerStackGetter getter) { - GETTERS.put(id, getter); - } - - /** - * Get an ItemStack from a registered processor - * @param entry The Identifier of the entry to get - * @return the proper ItemStack for the given Identifier, or an empty stack if the entry doesn't exist - */ - ItemStack getSpecialStack(Identifier entry); -} diff --git a/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerSyntaxException.java b/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerSyntaxException.java deleted file mode 100644 index a7fd5e3..0000000 --- a/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerSyntaxException.java +++ /dev/null @@ -1,7 +0,0 @@ -package io.github.cottonmc.cotton.tweaker; - -public class TweakerSyntaxException extends Exception { - public TweakerSyntaxException(String message) { - super(message); - } -} diff --git a/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerUtils.java b/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerUtils.java index b37e976..d237368 100644 --- a/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerUtils.java +++ b/src/main/java/io/github/cottonmc/cotton/tweaker/TweakerUtils.java @@ -1,29 +1,20 @@ package io.github.cottonmc.cotton.tweaker; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import io.github.cottonmc.cotton.Cotton; import net.minecraft.block.Block; import net.minecraft.entity.EntityType; import net.minecraft.fluid.Fluid; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.StringNbtReader; -import net.minecraft.potion.Potion; -import net.minecraft.potion.PotionUtil; -import net.minecraft.potion.Potions; import net.minecraft.sound.SoundEvent; -import net.minecraft.tag.ItemTags; -import net.minecraft.tag.Tag; import net.minecraft.util.DefaultedList; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; /** * Various utilities for writing tweakers, due to the obfuscation of minecraft code. + * Use {@link io.github.cottonmc.libcd.tweaker.TweakerUtils} */ +@Deprecated public class TweakerUtils { /** * Get a registered item inside a script. @@ -119,28 +110,7 @@ public static ItemStack createItemStack(Item item, int amount) { * @return The stack with added NBT. */ public static ItemStack addNbtToStack(ItemStack stack, String nbt) { - StringNbtReader reader = new StringNbtReader(new StringReader(nbt)); - try { - CompoundTag tag = reader.parseCompoundTag(); - stack.setTag(tag); - } catch (CommandSyntaxException e) { - Cotton.logger.error("Error adding NBT to stack: " + e.getMessage()); - } - return stack; - } - - /** - * Get a potion of the specified type. - * Deprecated; use `getSpecialStack("minecraft:potion", id); instead - * @param id The id of the potion to get. - * @see Potion data values - * @return an ItemStack of the desired potion, or an empty stack if the potion doesn't exist. - */ - @Deprecated - public static ItemStack getPotion(String id) { - Potion potion = Potion.byId(id); - if (potion == Potions.EMPTY) return ItemStack.EMPTY; - return PotionUtil.setPotion(new ItemStack(Items.POTION), potion); + return io.github.cottonmc.libcd.tweaker.TweakerUtils.addNbtToStack(stack, nbt); } /** @@ -149,8 +119,7 @@ public static ItemStack getPotion(String id) { * @return the gotten stack, or an empty stack if the getter or id doesn't exist */ public static ItemStack getSpecialStack(String getter) { - String[] split = RecipeParser.processGetter(getter); - return getSpecialStack(split[0], split[1]); + return io.github.cottonmc.libcd.tweaker.TweakerUtils.getSpecialStack(getter); } /** @@ -160,11 +129,7 @@ public static ItemStack getSpecialStack(String getter) { * @return The gotten stack, or an empty stack if the getter or id doesn't exist. */ public static ItemStack getSpecialStack(String getter, String entry) { - Identifier getterId = new Identifier(getter); - Identifier itemId = new Identifier(entry); - if (!TweakerStackGetter.GETTERS.containsKey(getterId)) return ItemStack.EMPTY; - TweakerStackGetter get = TweakerStackGetter.GETTERS.get(getterId); - return get.getSpecialStack(itemId); + return io.github.cottonmc.libcd.tweaker.TweakerUtils.getSpecialStack(getter, entry); } /** @@ -173,13 +138,6 @@ public static ItemStack getSpecialStack(String getter, String entry) { * @return An array of items in the tag. */ public static String[] getItemsInTag(String tagId) { - Tag tag = ItemTags.getContainer().get(new Identifier(tagId)); - if (tag == null) return new String[0]; - Object[] items = tag.values().toArray(); - String[] res = new String[items.length]; - for (int i = 0; i < items.length; i++) { - res[i] = Registry.ITEM.getId((Item)items[i]).toString(); - } - return res; + return io.github.cottonmc.libcd.tweaker.TweakerUtils.getItemsInTag(tagId); } } diff --git a/src/main/resources/cotton.common.json b/src/main/resources/cotton.common.json index 050b8ce..0a221f1 100644 --- a/src/main/resources/cotton.common.json +++ b/src/main/resources/cotton.common.json @@ -8,8 +8,7 @@ "MixinCauldronBehavior", "MixinBucketItem", "MixinRecipeManager", - "MixinPlayerEntity", - "MixinResourceManagerImpl" + "MixinPlayerEntity" ], "client": [ "MixinCottonInitializerClient"