From 037e98c851cd3ee492acf18b2da6d4222ac12e80 Mon Sep 17 00:00:00 2001 From: KnightMiner Date: Sat, 23 Jan 2021 16:53:17 -0500 Subject: [PATCH] Port tag preference system from TiC --- src/main/java/slimeknights/mantle/Mantle.java | 1 + .../slimeknights/mantle/config/Config.java | 34 +++- .../mantle/recipe/ItemOutput.java | 166 ++++++++++++++++++ .../mantle/recipe/TagPreference.java | 129 ++++++++++++++ 4 files changed, 327 insertions(+), 3 deletions(-) create mode 100644 src/main/java/slimeknights/mantle/recipe/ItemOutput.java create mode 100644 src/main/java/slimeknights/mantle/recipe/TagPreference.java diff --git a/src/main/java/slimeknights/mantle/Mantle.java b/src/main/java/slimeknights/mantle/Mantle.java index 995f40f..5f6acad 100644 --- a/src/main/java/slimeknights/mantle/Mantle.java +++ b/src/main/java/slimeknights/mantle/Mantle.java @@ -37,6 +37,7 @@ public class Mantle { /* Proxies for sides, used for graphics processing */ public Mantle() { ModLoadingContext.get().registerConfig(Type.CLIENT, Config.CLIENT_SPEC); + ModLoadingContext.get().registerConfig(Type.SERVER, Config.SERVER_SPEC); instance = this; IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); diff --git a/src/main/java/slimeknights/mantle/config/Config.java b/src/main/java/slimeknights/mantle/config/Config.java index 66d7b26..08a73c8 100644 --- a/src/main/java/slimeknights/mantle/config/Config.java +++ b/src/main/java/slimeknights/mantle/config/Config.java @@ -3,10 +3,12 @@ package slimeknights.mantle.config; import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.common.ForgeConfigSpec.BooleanValue; import net.minecraftforge.common.ForgeConfigSpec.Builder; +import net.minecraftforge.common.ForgeConfigSpec.ConfigValue; import net.minecraftforge.fml.config.ModConfig; import slimeknights.mantle.Mantle; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.function.Function; @@ -16,15 +18,20 @@ import java.util.function.Function; public class Config { /** List of all cached client config values, for cache clearing */ private static final List> CLIENT_VALUES = new ArrayList<>(); + private static final List> SERVER_VALUES = new ArrayList<>(); /** If true, enables the heart renderer */ public static final CachedBoolean EXTRA_HEART_RENDERER; - private static final ForgeConfigSpec.Builder CLIENT_BUILDER; - public static final ForgeConfigSpec CLIENT_SPEC; + /** List of preferences for tag outputs */ + public static final CachedValue> TAG_PREFERENCES; + + private static final ForgeConfigSpec.Builder CLIENT_BUILDER, SERVER_BUILDER; + public static final ForgeConfigSpec CLIENT_SPEC, SERVER_SPEC; static { CLIENT_BUILDER = new ForgeConfigSpec.Builder(); + SERVER_BUILDER = new ForgeConfigSpec.Builder(); // client options EXTRA_HEART_RENDERER = client(builder -> @@ -34,7 +41,14 @@ public class Config { .translation("config.mantle.extraHeartRenderer") .define("extraHeartRenderer", true)); + // server options + TAG_PREFERENCES = server(builder -> + builder.comment("Preferences for outputs from tags used in automatic compat in recipes") + .translation("config.mantle.tagPreferences") + .define("tagPreferences", Arrays.asList("minecraft", "tconstruct", "tmechworks", "immersiveengineering", "mekanism", "thermalfoundation", "thermalexpansion"))); + CLIENT_SPEC = CLIENT_BUILDER.build(); + SERVER_SPEC = SERVER_BUILDER.build(); } /** @@ -48,6 +62,17 @@ public class Config { return cached; } + /** + * Creates a cached boolean value for the client and adds it to the list to be invalidated on reload + * @param function Lambda to get config value + * @return Cached config value + */ + private static CachedValue server(Function> function) { + CachedValue cached = new CachedValue<>(function.apply(SERVER_BUILDER)); + SERVER_VALUES.add(cached); + return cached; + } + /** * Event to call when the config changes * @param configEvent Config event @@ -55,8 +80,11 @@ public class Config { public static void configChanged(final ModConfig.ModConfigEvent configEvent) { ModConfig config = configEvent.getConfig(); if (config.getModId().equals(Mantle.modId)) { - if (config.getSpec() == Config.CLIENT_SPEC) { + ForgeConfigSpec spec = config.getSpec(); + if (spec == Config.CLIENT_SPEC) { CLIENT_VALUES.forEach(CachedValue::invalidate); + } else if (spec == Config.SERVER_SPEC) { + SERVER_VALUES.forEach(CachedValue::invalidate); } } } diff --git a/src/main/java/slimeknights/mantle/recipe/ItemOutput.java b/src/main/java/slimeknights/mantle/recipe/ItemOutput.java new file mode 100644 index 0000000..5cb9c66 --- /dev/null +++ b/src/main/java/slimeknights/mantle/recipe/ItemOutput.java @@ -0,0 +1,166 @@ +package slimeknights.mantle.recipe; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSyntaxException; +import lombok.RequiredArgsConstructor; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.network.PacketBuffer; +import net.minecraft.tags.ITag; +import net.minecraft.tags.TagCollectionManager; +import net.minecraft.util.IItemProvider; +import net.minecraft.util.JSONUtils; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.common.crafting.CraftingHelper; + +import java.util.Objects; +import java.util.function.Supplier; + +/** + * Class representing an item stack output. Supports both direct stacks and tag output, behaving like an ingredient used for output + */ +public abstract class ItemOutput implements Supplier { + /** + * Gets the item output of this recipe + * @return Item output + */ + @Override + public abstract ItemStack get(); + + /** + * Writes this output to JSON + * @return Json element + */ + public abstract JsonElement serialize(); + + /** + * Creates a new output for the given stack + * @param stack Stack + * @return Output + */ + public static ItemOutput fromStack(ItemStack stack) { + return new OfStack(stack); + } + + /** + * Creates a new output for the given item + * @param item Item + * @return Output + */ + public static ItemOutput fromItem(IItemProvider item) { + return fromStack(new ItemStack(item)); + } + + /** + * Creates a new output for the given tag + * @param tag Tag + * @return Output + */ + public static ItemOutput fromTag(ITag tag, int count) { + return new OfTagPreference(tag, count); + } + + /** + * Reads an item output from JSON + * @param element Json element + * @return Read output + */ + public static ItemOutput fromJson(JsonElement element) { + if (element.isJsonPrimitive()) { + return fromItem(JSONUtils.getItem(element, "item")); + } + if (!element.isJsonObject()) { + throw new JsonSyntaxException("Invalid item output, must be a string or an object"); + } + // if it has a tag, parse as tag + JsonObject json = element.getAsJsonObject(); + if (json.has("tag")) { + String name = JSONUtils.getString(json, "tag"); + ITag tag = TagCollectionManager.getManager().getItemTags().get(new ResourceLocation(name)); + if (tag == null) { + throw new JsonSyntaxException("Unknown tag " + name + " for item output"); + } + int count = JSONUtils.getInt(json, "count", 1); + return fromTag(tag, count); + } + + // default: parse as item stack using Forge + return fromStack(CraftingHelper.getItemStack(json, true)); + } + + /** + * Writes this output to the packet buffer + * @param buffer Packet buffer instance + */ + public void write(PacketBuffer buffer) { + buffer.writeItemStack(get()); + } + + /** + * Reads an item output from the packet buffer + * @param buffer Buffer instance + * @return Item output + */ + public static ItemOutput read(PacketBuffer buffer) { + return fromStack(buffer.readItemStack()); + } + + /** Class for an output that is just a stack */ + @RequiredArgsConstructor + private static class OfStack extends ItemOutput { + private final ItemStack stack; + + @Override + public ItemStack get() { + return stack; + } + + @Override + public JsonElement serialize() { + String itemName = Objects.requireNonNull(stack.getItem().getRegistryName()).toString(); + int count = stack.getCount(); + // if the item has NBT or a count, write as object + if (stack.hasTag() || stack.getCount() > 1) { + JsonObject jsonResult = new JsonObject(); + jsonResult.addProperty("item", itemName); + if (count > 1) { + jsonResult.addProperty("count", count); + } + CompoundNBT nbt = stack.getTag(); + if (nbt != null) { + jsonResult.addProperty("nbt", nbt.toString()); + } + return jsonResult; + } else { + return new JsonPrimitive(itemName); + } + } + } + + /** Class for an output from a tag preference */ + @RequiredArgsConstructor + private static class OfTagPreference extends ItemOutput { + private final ITag tag; + private final int count; + + @Override + public ItemStack get() { + return TagPreference.getItems().getPreference(tag) + .map(item -> new ItemStack(item, count)) + .orElse(ItemStack.EMPTY); + } + + @Override + public JsonElement serialize() { + JsonObject json = new JsonObject(); + json.addProperty("tag", TagCollectionManager.getManager().getItemTags().getValidatedIdFromTag(tag).toString()); + if (count != 1) { + json.addProperty("count", count); + } + return json; + } + } +} diff --git a/src/main/java/slimeknights/mantle/recipe/TagPreference.java b/src/main/java/slimeknights/mantle/recipe/TagPreference.java new file mode 100644 index 0000000..43b6ce9 --- /dev/null +++ b/src/main/java/slimeknights/mantle/recipe/TagPreference.java @@ -0,0 +1,129 @@ +package slimeknights.mantle.recipe; + +import com.google.common.collect.Lists; +import net.minecraft.fluid.Fluid; +import net.minecraft.item.Item; +import net.minecraft.tags.ITag; +import net.minecraft.tags.ITagCollection; +import net.minecraft.tags.TagCollectionManager; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.Tags.IOptionalNamedTag; +import net.minecraftforge.event.TagsUpdatedEvent; +import net.minecraftforge.registries.IForgeRegistryEntry; +import slimeknights.mantle.config.Config; + +import java.util.Comparator; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Supplier; + +/** + * Utility that helps get the preferred item from a tag based on mod ID. + * @param Registry type + */ +public class TagPreference> { + /** Map of each tag type to the preference instance for that type */ + private static final Map, TagPreference> PREFERENCE_MAP = new IdentityHashMap<>(); + // cached tag supplier lambdas + private static final Supplier> ITEM_TAG_COLLECTION_SUPPLIER = () -> TagCollectionManager.getManager().getItemTags(); + private static final Supplier> FLUID_TAG_COLLECTION_SUPPLIER = () -> TagCollectionManager.getManager().getFluidTags(); + + /** + * Gets the tag preference instance associated with the given tag collection + * @param clazz Tag class + * @param Tag value type + * @return Tag preference instance + */ + @SuppressWarnings("unchecked") + public static > TagPreference getInstance(Class clazz, Supplier> collection) { + // should always be the right instance as only we add entries to the map + return (TagPreference) PREFERENCE_MAP.computeIfAbsent(clazz, c -> new TagPreference<>(collection)); + } + + /** + * Gets an instance for item tags + * @return Instance for item tags + */ + public static TagPreference getItems() { + return getInstance(Item.class, ITEM_TAG_COLLECTION_SUPPLIER); + } + + /** + * Gets an instance for fluid tags + * @return Instance for fluid tags + */ + public static TagPreference getFluids() { + return getInstance(Fluid.class, FLUID_TAG_COLLECTION_SUPPLIER); + } + + /** Supplier to tag collection */ + private final Supplier> collection; + + /** Specific cache to this tag preference class type */ + private final Map> preferenceCache = new HashMap<>(); + + private TagPreference(Supplier> collection) { + this.collection = collection; + MinecraftForge.EVENT_BUS.addListener(this::clearCache); + } + + /** + * Clears the tag cache from the event + * @param event Tag event + */ + private void clearCache(TagsUpdatedEvent.VanillaTagTypes event) { + preferenceCache.clear(); + } + + /** + * Gets the sort index of an entry based on the tag preference list + * @param entry Registry entry to check + * @return Sort index for that entry + */ + private static int getSortIndex(IForgeRegistryEntry entry) { + List entries = Config.TAG_PREFERENCES.get(); + // check the index of the namespace in the preference list + int index = entries.indexOf(Objects.requireNonNull(entry.getRegistryName()).getNamespace()); + // if missing, declare last + if (index == -1) { + return entries.size(); + } + return index; + } + + /** + * Gets the preferred value from a tag based on mod ID + * @param tag Tag to fetch + * @return Preferred value from the tag, or empty optional if the tag is empty + */ + public Optional getPreference(ITag tag) { + // fetch cached value if we have one + ResourceLocation tagName = collection.get().getValidatedIdFromTag(tag); + return preferenceCache.computeIfAbsent(tagName, name -> { + // if no items, empty optional + if (tag instanceof IOptionalNamedTag && ((IOptionalNamedTag) tag).isDefaulted()) { + return Optional.empty(); + } + List elements = tag.getAllElements(); + if (elements.isEmpty()) { + return Optional.empty(); + } + + // if size 1, quick exit + if (elements.size() == 1) { + return Optional.of(elements.get(0)); + } + + // copy and sort list + List sortedElements = Lists.newArrayList(elements); + sortedElements.sort(Comparator.comparingInt(TagPreference::getSortIndex)); + // return first element, its the preference + return Optional.of(sortedElements.get(0)); + }); + } +}