From 897172bde9128da47181a6db6c1ff4885081ba8d Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 21 Jan 2022 14:21:23 +0200 Subject: Re(moved) most of the old sources --- .../shsupercm/fabric/citresewn/ActiveCITs.java | 187 --------- .../shcm/shsupercm/fabric/citresewn/CITResewn.java | 13 +- .../fabric/citresewn/CITResewnCommand.java | 33 -- .../shsupercm/fabric/citresewn/OptionalCompat.java | 69 --- .../fabric/citresewn/config/CITResewnConfig.java | 8 +- .../config/CITResewnConfigScreenFactory.java | 9 +- .../fabric/citresewn/config/CITResewnModMenu.java | 16 +- .../fabric/citresewn/ex/CITLoadException.java | 13 - .../fabric/citresewn/ex/CITParseException.java | 13 - .../AbstractFileResourcePackMixin.java | 49 --- .../mixin/broken_paths/IdentifierMixin.java | 17 - .../ReloadableResourceManagerImplMixin.java | 31 -- .../ResourcePackCompatibilityMixin.java | 26 -- .../mixin/citarmor/ArmorFeatureRendererMixin.java | 59 --- .../citresewn/mixin/citarmor/ItemStackMixin.java | 25 -- .../citelytra/ElytraFeatureRendererMixin.java | 60 --- .../citresewn/mixin/citelytra/ItemStackMixin.java | 25 -- .../citenchantment/ArmorFeatureRendererMixin.java | 33 -- .../BufferBuilderStorageAccessor.java | 15 - .../citenchantment/ElytraFeatureRendererMixin.java | 33 -- .../mixin/citenchantment/ItemRendererMixin.java | 86 ---- .../mixin/citenchantment/ItemStackMixin.java | 36 -- .../mixin/citenchantment/MinecraftClientMixin.java | 17 - .../mixin/citenchantment/RenderPhaseAccessor.java | 21 - .../citresewn/mixin/cititem/ItemRendererMixin.java | 69 --- .../citresewn/mixin/cititem/ItemStackMixin.java | 40 -- .../mixin/cititem/JsonUnbakedModelAccessor.java | 22 - .../citresewn/mixin/cititem/ModelLoaderMixin.java | 165 -------- .../citresewn/mixin/core/ChatScreenMixin.java | 23 - .../mixin/core/GroupResourcePackAccessor.java | 14 - .../citresewn/mixin/core/ModelLoaderMixin.java | 51 --- .../citresewn/mixin/core/NbtCompoundAccessor.java | 14 - .../mixin/core/SpriteAtlasTextureMixin.java | 18 - .../citresewn/mixin/core/ZipResourcePackMixin.java | 60 --- .../shsupercm/fabric/citresewn/pack/CITPack.java | 65 --- .../shsupercm/fabric/citresewn/pack/CITParser.java | 119 ------ .../citresewn/pack/ResewnItemModelIdentifier.java | 18 - .../citresewn/pack/ResewnTextureIdentifier.java | 14 - .../shsupercm/fabric/citresewn/pack/cits/CIT.java | 435 ------------------- .../fabric/citresewn/pack/cits/CITArmor.java | 42 -- .../fabric/citresewn/pack/cits/CITElytra.java | 28 -- .../fabric/citresewn/pack/cits/CITEnchantment.java | 371 ----------------- .../fabric/citresewn/pack/cits/CITItem.java | 463 --------------------- 43 files changed, 19 insertions(+), 2906 deletions(-) delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/ActiveCITs.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/OptionalCompat.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITLoadException.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParseException.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citarmor/ArmorFeatureRendererMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citarmor/ItemStackMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citelytra/ElytraFeatureRendererMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citelytra/ItemStackMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ArmorFeatureRendererMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/BufferBuilderStorageAccessor.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ElytraFeatureRendererMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ItemRendererMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ItemStackMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/MinecraftClientMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/RenderPhaseAccessor.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ItemRendererMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ItemStackMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/JsonUnbakedModelAccessor.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ModelLoaderMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ChatScreenMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/GroupResourcePackAccessor.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ModelLoaderMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/NbtCompoundAccessor.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/SpriteAtlasTextureMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ZipResourcePackMixin.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/CITPack.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/CITParser.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/ResewnItemModelIdentifier.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/ResewnTextureIdentifier.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CIT.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITArmor.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITElytra.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITEnchantment.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITItem.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/ActiveCITs.java deleted file mode 100644 index 8d56a35..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/ActiveCITs.java +++ /dev/null @@ -1,187 +0,0 @@ -package shcm.shsupercm.fabric.citresewn; - -import net.minecraft.client.render.model.BakedModel; -import net.minecraft.client.world.ClientWorld; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.ArmorItem; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.util.Hand; -import net.minecraft.util.Identifier; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.World; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.pack.CITPack; -import shcm.shsupercm.fabric.citresewn.pack.cits.*; - -import java.util.*; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -public class ActiveCITs { - public final List packs; - public final CITPack effectiveGlobalProperties = new CITPack(null); - - public final List cits; - - public final Map> citItems = new HashMap<>(); - public final Map> citArmor = new HashMap<>(); - public final List citElytra = new ArrayList<>(); - public final List> citEnchantments = new ArrayList<>(); - - - public ActiveCITs(List packs, List cits) { - this.packs = packs; - this.cits = cits; - - for (CITPack pack : packs) - effectiveGlobalProperties.loadGlobalProperties(pack); - for (CITPack pack : packs) - pack.loadGlobalProperties(effectiveGlobalProperties); - - Map> citEnchantmentLayers = new TreeMap<>(); // order citEnchantments by layers - - for (CIT cit : cits.stream().sorted(Comparator.comparingInt(cit -> cit.weight).reversed().thenComparing(cit -> cit.propertiesIdentifier.toString())).collect(Collectors.toList())) { - if (cit instanceof CITItem item) - for (Item type : item.items) - citItems.computeIfAbsent(type, t -> new ArrayList<>()).add(item); - else if (cit instanceof CITArmor armor) - for (Item type : armor.items) - if (type instanceof ArmorItem armorType) - citArmor.computeIfAbsent(armorType, t -> new ArrayList<>()).add(armor); - else - CITResewn.logErrorLoading("Ignoring item type: " + Registry.ITEM.getId(type) + " is not armor in " + cit.pack.resourcePack.getName() + " -> " + cit.propertiesIdentifier.toString()); - else if (cit instanceof CITElytra elytra) - citElytra.add(elytra); - else if (cit instanceof CITEnchantment enchantment) - citEnchantmentLayers.computeIfAbsent(enchantment.layer, l -> new ArrayList<>()).add(enchantment); - } - - for (List layer : citEnchantmentLayers.values()) { - for (CITEnchantment enchantment : layer) - enchantment.activate(); - citEnchantments.add(layer); - } - } - - public void dispose() { - for (CIT cit : cits) - cit.dispose(); - cits.clear(); - citItems.clear(); - citArmor.clear(); - citElytra.clear(); - citEnchantments.clear(); - } - - public CITItem getCITItem(ItemStack stack, World world, LivingEntity entity) { - Hand hand = entity != null && stack == entity.getOffHandStack() ? Hand.OFF_HAND : Hand.MAIN_HAND; - - ((CITItem.Cached) (Object) stack).citresewn_setMojankCIT(false); - - List citItems = this.citItems.get(stack.getItem()); - if (citItems != null) - for (CITItem citItem : citItems) - if (citItem.test(stack, hand, world, entity, true)) { - if (stack.isOf(Items.TRIDENT) || stack.isOf(Items.SPYGLASS)) - ((CITItem.Cached) (Object) stack).citresewn_setMojankCIT(true); - return citItem; - } - return null; - } - - public CITElytra getCITElytra(ItemStack stack, World world, LivingEntity livingEntity) { - for (CITElytra citElytra : citElytra) - if (citElytra.test(stack, Hand.MAIN_HAND, world, livingEntity, true)) - return citElytra; - return null; - } - - public CITArmor getCITArmor(ItemStack stack, World world, LivingEntity livingEntity) { - Item item = stack.getItem(); - if (item instanceof ArmorItem) { - List citArmor = this.citArmor.get(item); - if (citArmor != null) - for (CITArmor armor : citArmor) - if (armor.test(stack, null, world, livingEntity, true)) - return armor; - } - return null; - } - - public List getCITEnchantment(ItemStack stack, World world, LivingEntity livingEntity) { - Hand hand = livingEntity != null && stack == livingEntity.getOffHandStack() ? Hand.OFF_HAND : Hand.MAIN_HAND; - - List applied = new ArrayList<>(); - - for (List layer : this.citEnchantments) - for (CITEnchantment cit : layer) - if (cit.test(stack, hand, world, livingEntity, false)) { - applied.add(cit); - break; - } - - return applied; - } - - public BakedModel getItemModelCached(ItemStack stack, World world, LivingEntity entity, int seed) { - BakedModel bakedModel = null; - - Supplier realtime = () -> getCITItem(stack, world, entity); - - //noinspection ConstantConditions - CITItem citItem = CITResewnConfig.INSTANCE().cache_ms == 0 ? realtime.get() : ((CITItem.Cached) (Object) stack).citresewn_getCachedCITItem(realtime); - - if (citItem != null) - bakedModel = citItem.getItemModel(stack, (ClientWorld) world, entity, seed); - - return bakedModel; - } - - public Identifier getElytraTextureCached(ItemStack stack, World world, LivingEntity livingEntity) { - Supplier realtime = () -> getCITElytra(stack, world, livingEntity); - - //noinspection ConstantConditions - CITElytra citElytra = CITResewnConfig.INSTANCE().cache_ms == 0 ? realtime.get() : ((CITElytra.Cached) (Object) stack).citresewn_getCachedCITElytra(realtime); - - if (citElytra != null) - return citElytra.textureIdentifier; - - return null; - } - - public Map getArmorTexturesCached(ItemStack stack, World world, LivingEntity livingEntity) { - Supplier realtime = () -> getCITArmor(stack, world, livingEntity); - - //noinspection ConstantConditions - CITArmor citArmor = CITResewnConfig.INSTANCE().cache_ms == 0 ? realtime.get() : ((CITArmor.Cached) (Object) stack).citresewn_getCachedCITArmor(realtime); - - if (citArmor != null) - return citArmor.textures; - - return null; - } - - public void setEnchantmentAppliedContextCached(ItemStack stack, World world, LivingEntity entity) { - if (stack == null) { - CITEnchantment.appliedContext = null; - return; - } - - Supplier> realtime = () -> getCITEnchantment(stack, world, entity); - - //noinspection ConstantConditions - List citEnchantments = CITResewnConfig.INSTANCE().cache_ms == 0 ? realtime.get() : ((CITEnchantment.Cached) (Object) stack).citresewn_getCachedCITEnchantment(realtime); - - if (citEnchantments == null || citEnchantments.isEmpty()) { - CITEnchantment.appliedContext = null; - return; - } - - if (effectiveGlobalProperties.method != null) - effectiveGlobalProperties.method.applyMethod(citEnchantments, stack); - - CITEnchantment.appliedContext = citEnchantments; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java index e53ba52..4ebfff8 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java @@ -12,20 +12,11 @@ public class CITResewn implements ClientModInitializer { public static final Logger LOG = LogManager.getLogger("CITResewn"); public static CITResewn INSTANCE; - public ActiveCITs activeCITs = null; - - public CITResewnConfig config = null; - - public boolean processingBrokenPaths = false; @Override public void onInitializeClient() { INSTANCE = this; - - config = CITResewnConfig.read(); - - CITResewnCommand.register(); } public static void info(String message) { @@ -33,13 +24,13 @@ public class CITResewn implements ClientModInitializer { } public static void logWarnLoading(String message) { - if (CITResewnConfig.INSTANCE().mute_warns) + if (CITResewnConfig.INSTANCE.mute_warns) return; LOG.error("[citresewn] " + message); } public static void logErrorLoading(String message) { - if (CITResewnConfig.INSTANCE().mute_errors) + if (CITResewnConfig.INSTANCE.mute_errors) return; LOG.error("{citresewn} " + message); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java deleted file mode 100644 index 483cbfb..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java +++ /dev/null @@ -1,33 +0,0 @@ -package shcm.shsupercm.fabric.citresewn; - -import net.fabricmc.fabric.api.client.command.v1.ClientCommandManager; -import net.fabricmc.loader.api.FabricLoader; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; - -import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal; -import static net.minecraft.text.Text.of; - -public class CITResewnCommand { - public static boolean openConfig = false; - - public static void register() { - ClientCommandManager.DISPATCHER.register(literal("citresewn") - .executes(context -> { - context.getSource().sendFeedback(of("CIT Resewn v" + FabricLoader.getInstance().getModContainer("citresewn").get().getMetadata().getVersion() + ":")); - boolean active = CITResewnConfig.INSTANCE().enabled && CITResewn.INSTANCE.activeCITs != null; - context.getSource().sendFeedback(of(" Active: " + (active ? "yes" : "no"))); - if (active) { - context.getSource().sendFeedback(of(" Loaded: " + CITResewn.INSTANCE.activeCITs.cits.size() + " CITs from " + CITResewn.INSTANCE.activeCITs.packs.size() + " resourcepacks")); - } - context.getSource().sendFeedback(of(" ")); - - return 1; - }) - .then(literal("config") - .executes(context -> { - openConfig = true; - - return 1; - }))); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/OptionalCompat.java b/src/main/java/shcm/shsupercm/fabric/citresewn/OptionalCompat.java deleted file mode 100644 index 580aef5..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/OptionalCompat.java +++ /dev/null @@ -1,69 +0,0 @@ -package shcm.shsupercm.fabric.citresewn; - -import io.github.apace100.cosmetic_armor.CosmeticArmor; -import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.screen.NoticeScreen; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.entity.EquipmentSlot; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.text.Text; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfigScreenFactory; - -import java.util.function.Function; -import java.util.function.Predicate; - -public final class OptionalCompat { - private static final OptionalCompat INSTANCE = new OptionalCompat(s -> FabricLoader.getInstance().isModLoaded(s)); - - public final CompatClothConfig compatClothConfig; - - public final CompatCosmeticArmor compatCosmeticArmor; - - private OptionalCompat(Predicate isLoaded) { - compatClothConfig = isLoaded.test("cloth-config2") ? CompatClothConfig.impl() : null; - compatCosmeticArmor = isLoaded.test("cosmetic-armor") ? CompatCosmeticArmor.impl() : null; - } - - public static Function getModConfigScreenFactory() { - if (INSTANCE.compatClothConfig != null) { - return INSTANCE.compatClothConfig.getModConfigScreenFactory(); - } - - return parent -> new NoticeScreen(() -> MinecraftClient.getInstance().setScreen(parent), Text.of("CIT Resewn"), Text.of("CIT Resewn requires Cloth Config 2 to be able to show the config.")); - } - - public static ItemStack getCosmeticArmor(ItemStack original, LivingEntity entity, EquipmentSlot slot, boolean elytra) { - if (INSTANCE.compatCosmeticArmor != null) { - ItemStack stackInCosmeticSlot = INSTANCE.compatCosmeticArmor.getStackInCosmeticSlot(entity, slot); - if (!stackInCosmeticSlot.isEmpty() && (!elytra || stackInCosmeticSlot.isOf(Items.ELYTRA))) - return stackInCosmeticSlot; - } - - return original; - } - - /** - * Compatibility with 'cloth-config2': Custom gui for CITResewn's config - */ - public interface CompatClothConfig { - private static CompatClothConfig impl() { - return () -> CITResewnConfigScreenFactory::create; - } - - Function getModConfigScreenFactory(); - } - - /** - * Compatibility with 'cosmetic-armor': Display cits for cosmetic armors instead of equipped armors - */ - public interface CompatCosmeticArmor { - private static CompatCosmeticArmor impl() { - return CosmeticArmor::getCosmeticArmor; - } - - ItemStack getStackInCosmeticSlot(LivingEntity entity, EquipmentSlot slot); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfig.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfig.java index 04b3166..2f051f0 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfig.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfig.java @@ -4,8 +4,6 @@ import com.google.gson.Gson; import com.google.gson.stream.JsonWriter; import org.apache.commons.io.IOUtils; import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.pack.CITParser; -import shcm.shsupercm.fabric.citresewn.pack.cits.CITItem; import java.io.*; @@ -13,14 +11,12 @@ public class CITResewnConfig { public boolean enabled = true; public boolean mute_errors = false; public boolean mute_warns = false; - public float citenchantment_scroll_multiplier = 8f; public int cache_ms = 50; public boolean broken_paths = false; private static final File FILE = new File("config/citresewn.json"); - public static CITResewnConfig INSTANCE() { - return CITResewn.INSTANCE.config; - } + + public static final CITResewnConfig INSTANCE = read(); public static CITResewnConfig read() { if (!FILE.exists()) diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java index 055c976..33f4950 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java @@ -11,7 +11,7 @@ import net.minecraft.util.Formatting; public class CITResewnConfigScreenFactory { public static Screen create(Screen parent) { - CITResewnConfig currentConfig = CITResewnConfig.INSTANCE(), defaultConfig = new CITResewnConfig(); + CITResewnConfig currentConfig = CITResewnConfig.INSTANCE, defaultConfig = new CITResewnConfig(); ConfigBuilder builder = ConfigBuilder.create() .setParentScreen(parent) @@ -44,13 +44,6 @@ public class CITResewnConfigScreenFactory { .setDefaultValue(defaultConfig.mute_warns) .build()); - category.addEntry(entryBuilder.startFloatField(new TranslatableText("config.citresewn.citenchantment_scroll_multiplier.title"), currentConfig.citenchantment_scroll_multiplier) - .setTooltip(new TranslatableText("config.citresewn.citenchantment_scroll_multiplier.tooltip")) - .setSaveConsumer(newConfig -> currentConfig.citenchantment_scroll_multiplier = newConfig) - .setDefaultValue(defaultConfig.citenchantment_scroll_multiplier) - .setMin(0f) - .build()); - category.addEntry(entryBuilder.startIntSlider(new TranslatableText("config.citresewn.cache_ms.title"), currentConfig.cache_ms / 50, 0, 5 * 20) .setTooltip(new TranslatableText("config.citresewn.cache_ms.tooltip")) .setSaveConsumer(newConfig -> currentConfig.cache_ms = newConfig * 50) diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java index 7a4954c..cf6d9bd 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java @@ -3,11 +3,23 @@ package shcm.shsupercm.fabric.citresewn.config; import com.terraformersmc.modmenu.api.ConfigScreenFactory; import com.terraformersmc.modmenu.api.ModMenuApi; import net.fabricmc.loader.api.FabricLoader; -import shcm.shsupercm.fabric.citresewn.OptionalCompat; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.screen.NoticeScreen; +import net.minecraft.text.Text; public class CITResewnModMenu implements ModMenuApi { @Override public ConfigScreenFactory getModConfigScreenFactory() { - return OptionalCompat.getModConfigScreenFactory()::apply; + if (FabricLoader.getInstance().isModLoaded("cloth-config2")) + return new ClothConfigOpenImpl().getModConfigScreenFactory(); + + return parent -> new NoticeScreen(() -> MinecraftClient.getInstance().setScreen(parent), Text.of("CIT Resewn"), Text.of("CIT Resewn requires Cloth Config to be able to show the config.")); + } + + private static class ClothConfigOpenImpl implements ModMenuApi { + @Override + public ConfigScreenFactory getModConfigScreenFactory() { + return CITResewnConfigScreenFactory::create; + } } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITLoadException.java b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITLoadException.java deleted file mode 100644 index c40bc80..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITLoadException.java +++ /dev/null @@ -1,13 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.ex; - -import net.minecraft.resource.ResourcePack; -import net.minecraft.util.Identifier; - -/** - * Thrown when a cit failed to be loaded - */ -public class CITLoadException extends Exception { - public CITLoadException(ResourcePack resourcePack, Identifier identifier, String message) { - super("Couldn't load CIT: " + message + " in " + resourcePack.getName() + " -> " + identifier.toString()); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParseException.java b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParseException.java deleted file mode 100644 index 95bc386..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParseException.java +++ /dev/null @@ -1,13 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.ex; - -import net.minecraft.resource.ResourcePack; -import net.minecraft.util.Identifier; - -/** - * Thrown when a cit failed to be parsed - */ -public class CITParseException extends Exception { - public CITParseException(ResourcePack resourcePack, Identifier identifier, String message) { - super("Skipped CIT: " + message + " in " + resourcePack.getName() + " -> " + identifier.toString()); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java deleted file mode 100644 index 281150b..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java +++ /dev/null @@ -1,49 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.broken_paths; - -import net.minecraft.resource.AbstractFileResourcePack; -import net.minecraft.resource.DirectoryResourcePack; -import net.minecraft.resource.ResourcePack; -import net.minecraft.resource.ZipResourcePack; -import net.minecraft.resource.metadata.PackResourceMetadata; -import net.minecraft.resource.metadata.ResourceMetadataReader; -import net.minecraft.util.Identifier; -import net.minecraft.util.InvalidIdentifierException; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.io.File; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.zip.ZipFile; - -/* if (CITResewnConfig.read().broken_paths) */ @Mixin(AbstractFileResourcePack.class) -public abstract class AbstractFileResourcePackMixin implements ResourcePack { - @Shadow @Final protected File base; - - @SuppressWarnings({"unchecked", "ConstantConditions", "EqualsBetweenInconvertibleTypes"}) - @Inject(method = "parseMetadata(Lnet/minecraft/resource/metadata/ResourceMetadataReader;)Ljava/lang/Object;", cancellable = true, at = @At("RETURN")) - public void parseMetadata(ResourceMetadataReader metaReader, CallbackInfoReturnable cir) { - if (cir.getReturnValue() != null) - try { - if (this.getClass().equals(ZipResourcePack.class)) { - try (ZipFile zipFile = new ZipFile(base)) { - zipFile.stream() - .forEach(entry -> { - if (entry.getName().startsWith("assets")) - new Identifier("minecraft", entry.getName()); - }); - } - } else if (this.getClass().equals(DirectoryResourcePack.class)) { - final Path assets = new File(base, "assets").toPath(); - Files.walk(assets) - .forEach(path -> new Identifier("minecraft", assets.relativize(path).toString().replace('\\', '/'))); - } - } catch (InvalidIdentifierException e) { - cir.setReturnValue((T) new PackResourceMetadata(cir.getReturnValue().getDescription(), Integer.MAX_VALUE - 53)); - } catch (Exception ignored) {} - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java deleted file mode 100644 index da9888f..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.broken_paths; - -import net.minecraft.util.Identifier; -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; -import shcm.shsupercm.fabric.citresewn.CITResewn; - -/* if (CITResewnConfig.read().broken_paths) */ @Mixin(Identifier.class) -public class IdentifierMixin { - @Inject(method = "isPathValid", cancellable = true, at = @At("HEAD")) - private static void processBrokenPaths(String path, CallbackInfoReturnable cir) { - if (CITResewn.INSTANCE != null && CITResewn.INSTANCE.processingBrokenPaths) - cir.setReturnValue(true); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java deleted file mode 100644 index e2b193a..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java +++ /dev/null @@ -1,31 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.broken_paths; - -import net.minecraft.resource.ReloadableResourceManagerImpl; -import net.minecraft.resource.ResourcePack; -import net.minecraft.resource.ResourceReload; -import net.minecraft.resource.ResourceType; -import net.minecraft.util.Unit; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import shcm.shsupercm.fabric.citresewn.CITResewn; - -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; - -/* if (CITResewnConfig.read().broken_paths) */ @Mixin(ReloadableResourceManagerImpl.class) -public class ReloadableResourceManagerImplMixin { - @Shadow @Final private ResourceType type; - - @Inject(method = "reload", at = @At("RETURN")) - public void onReload(Executor prepareExecutor, Executor applyExecutor, CompletableFuture initialStage, List packs, CallbackInfoReturnable cir) { - if (CITResewn.INSTANCE.processingBrokenPaths = this.type == ResourceType.CLIENT_RESOURCES) { - CITResewn.LOG.error("[citresewn] Caution! Broken paths is enabled!"); - cir.getReturnValue().whenComplete().thenRun(() -> CITResewn.INSTANCE.processingBrokenPaths = false); - } - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java deleted file mode 100644 index f62221b..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java +++ /dev/null @@ -1,26 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.broken_paths; - -import net.minecraft.resource.ResourcePackCompatibility; -import net.minecraft.resource.ResourceType; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -/* if (CITResewnConfig.read().broken_paths) */ @Mixin(ResourcePackCompatibility.class) -public abstract class ResourcePackCompatibilityMixin { - private static final ResourcePackCompatibility BROKEN_PATHS = ResourcePackCompatibility("BROKEN_PATHS", -1, "broken_paths"); - - @SuppressWarnings("InvokerTarget") - @Invoker("") - public static ResourcePackCompatibility ResourcePackCompatibility(String internalName, int internalId, String translationSuffix) { - throw new AssertionError(); - } - - @Inject(method = "from(ILnet/minecraft/resource/ResourceType;)Lnet/minecraft/resource/ResourcePackCompatibility;", cancellable = true, at = @At("HEAD")) - private static void redirectBrokenPathsCompatibility(int packVersion, ResourceType type, CallbackInfoReturnable cir) { - if (packVersion == Integer.MAX_VALUE - 53) - cir.setReturnValue(BROKEN_PATHS); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citarmor/ArmorFeatureRendererMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citarmor/ArmorFeatureRendererMixin.java deleted file mode 100644 index 72a0ade..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citarmor/ArmorFeatureRendererMixin.java +++ /dev/null @@ -1,59 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.citarmor; - -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.entity.feature.ArmorFeatureRenderer; -import net.minecraft.client.render.entity.model.BipedEntityModel; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.EquipmentSlot; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.ArmorItem; -import net.minecraft.item.ItemStack; -import net.minecraft.util.Identifier; -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.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.OptionalCompat; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; - -import java.lang.ref.WeakReference; -import java.util.Map; - -@Mixin(ArmorFeatureRenderer.class) -public class ArmorFeatureRendererMixin, A extends BipedEntityModel> { - private WeakReference> armorTexturesCached = null; - - @Inject(method = "renderArmor", at = @At("HEAD")) - private void renderArmor(MatrixStack matrices, VertexConsumerProvider vertexConsumers, T entity, EquipmentSlot armorSlot, int light, A model, CallbackInfo ci) { - if (!CITResewnConfig.INSTANCE().enabled || CITResewn.INSTANCE.activeCITs == null) - return; - - ItemStack itemStack = entity.getEquippedStack(armorSlot); - - //compat Cosmetic Armor - itemStack = OptionalCompat.getCosmeticArmor(itemStack, entity, armorSlot, false); - - Map armorTextures = CITResewn.INSTANCE.activeCITs.getArmorTexturesCached(itemStack, entity.world, entity); - if (armorTextures != null) { - armorTexturesCached = new WeakReference<>(armorTextures); - return; - } - - armorTexturesCached = null; - } - - @Inject(method = "getArmorTexture", cancellable = true, at = @At("HEAD")) - private void getArmorTexture(ArmorItem item, boolean legs, String overlay, CallbackInfoReturnable cir) { - if (armorTexturesCached == null) - return; - Map armorTextures = armorTexturesCached.get(); - if (armorTextures == null) - return; - - Identifier identifier = armorTextures.get(item.getMaterial().getName() + "_layer_" + (legs ? "2" : "1") + (overlay == null ? "" : "_" + overlay)); - if (identifier != null) - cir.setReturnValue(identifier); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citarmor/ItemStackMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citarmor/ItemStackMixin.java deleted file mode 100644 index 6041c9b..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citarmor/ItemStackMixin.java +++ /dev/null @@ -1,25 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.citarmor; - -import net.minecraft.item.ItemStack; -import org.spongepowered.asm.mixin.Mixin; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.pack.cits.CITArmor; - -import java.lang.ref.WeakReference; -import java.util.function.Supplier; - -@Mixin(ItemStack.class) -public class ItemStackMixin implements CITArmor.Cached { - private WeakReference citresewn_cachedCITArmor = new WeakReference<>(null); - private long citresewn_cacheTimeCITArmor = 0; - - @Override - public CITArmor citresewn_getCachedCITArmor(Supplier realtime) { - if (System.currentTimeMillis() - citresewn_cacheTimeCITArmor >= CITResewnConfig.INSTANCE().cache_ms) { - citresewn_cachedCITArmor = new WeakReference<>(realtime.get()); - citresewn_cacheTimeCITArmor = System.currentTimeMillis(); - } - - return citresewn_cachedCITArmor.get(); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citelytra/ElytraFeatureRendererMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citelytra/ElytraFeatureRendererMixin.java deleted file mode 100644 index b4151f8..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citelytra/ElytraFeatureRendererMixin.java +++ /dev/null @@ -1,60 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.citelytra; - -import net.minecraft.client.render.RenderLayer; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.entity.feature.ElytraFeatureRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.EquipmentSlot; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.util.Identifier; -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.ModifyArg; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.OptionalCompat; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; - -import java.lang.ref.WeakReference; - -@Mixin(ElytraFeatureRenderer.class) -public class ElytraFeatureRendererMixin { - private WeakReference elytraItemCached = new WeakReference<>(null); - private WeakReference livingEntityCached = new WeakReference<>(null); - - @Inject(method = "render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;ILnet/minecraft/entity/LivingEntity;FFFFFF)V", at = - @At("HEAD")) - private void render(MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int i, LivingEntity livingEntity, float f, float g, float h, float j, float k, float l, CallbackInfo ci) { - if (!CITResewnConfig.INSTANCE().enabled || CITResewn.INSTANCE.activeCITs == null) - return; - - ItemStack itemStack = livingEntity.getEquippedStack(EquipmentSlot.CHEST); - - //compat Cosmetic Armor - itemStack = OptionalCompat.getCosmeticArmor(itemStack, livingEntity, EquipmentSlot.CHEST, true); - - this.elytraItemCached = new WeakReference<>(itemStack); - this.livingEntityCached = new WeakReference<>(livingEntity); - } - - @ModifyArg(method = "render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;ILnet/minecraft/entity/LivingEntity;FFFFFF)V", at = - @At(value = "INVOKE", target = "Lnet/minecraft/client/render/item/ItemRenderer;getArmorGlintConsumer(Lnet/minecraft/client/render/VertexConsumerProvider;Lnet/minecraft/client/render/RenderLayer;ZZ)Lnet/minecraft/client/render/VertexConsumer;"), index = 1) - private RenderLayer getArmorCutoutNoCull(RenderLayer original) { - if (CITResewnConfig.INSTANCE().enabled && CITResewn.INSTANCE.activeCITs != null) { - ItemStack itemStack = this.elytraItemCached.get(); - LivingEntity livingEntity = this.livingEntityCached.get(); - if (itemStack != null && itemStack.isOf(Items.ELYTRA) && livingEntity != null) { - Identifier elytraTexture = CITResewn.INSTANCE.activeCITs.getElytraTextureCached(itemStack, livingEntity.world, livingEntity); - this.elytraItemCached = new WeakReference<>(null); - this.livingEntityCached = new WeakReference<>(null); - if (elytraTexture != null) - return RenderLayer.getArmorCutoutNoCull(elytraTexture); - } - } - - return original; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citelytra/ItemStackMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citelytra/ItemStackMixin.java deleted file mode 100644 index aaf4037..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citelytra/ItemStackMixin.java +++ /dev/null @@ -1,25 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.citelytra; - -import net.minecraft.item.ItemStack; -import org.spongepowered.asm.mixin.Mixin; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.pack.cits.CITElytra; - -import java.lang.ref.WeakReference; -import java.util.function.Supplier; - -@Mixin(ItemStack.class) -public class ItemStackMixin implements CITElytra.Cached { - private WeakReference citresewn_cachedCITElytra = new WeakReference<>(null); - private long citresewn_cacheTimeCITElytra = 0; - - @Override - public CITElytra citresewn_getCachedCITElytra(Supplier realtime) { - if (System.currentTimeMillis() - citresewn_cacheTimeCITElytra >= CITResewnConfig.INSTANCE().cache_ms) { - citresewn_cachedCITElytra = new WeakReference<>(realtime.get()); - citresewn_cacheTimeCITElytra = System.currentTimeMillis(); - } - - return citresewn_cachedCITElytra.get(); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ArmorFeatureRendererMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ArmorFeatureRendererMixin.java deleted file mode 100644 index b4d81c7..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ArmorFeatureRendererMixin.java +++ /dev/null @@ -1,33 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.citenchantment; - -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.entity.feature.ArmorFeatureRenderer; -import net.minecraft.client.render.entity.model.BipedEntityModel; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.EquipmentSlot; -import net.minecraft.entity.LivingEntity; -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.CallbackInfo; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.pack.cits.CITEnchantment; - -@Mixin(ArmorFeatureRenderer.class) -public class ArmorFeatureRendererMixin, A extends BipedEntityModel> { - @Inject(method = "renderArmor", at = @At("HEAD")) - private void setAppliedContextAndStartApplyingArmor(MatrixStack matrices, VertexConsumerProvider vertexConsumers, T livingEntity, EquipmentSlot armorSlot, int light, A model, CallbackInfo ci) { - if (CITResewnConfig.INSTANCE().enabled && CITResewn.INSTANCE.activeCITs != null) { - CITResewn.INSTANCE.activeCITs.setEnchantmentAppliedContextCached(livingEntity.getEquippedStack(armorSlot), livingEntity.world, livingEntity); - CITEnchantment.shouldApply = true; - } - } - - @Inject(method = "renderArmor", at = @At("RETURN")) - private void stopApplyingArmor(MatrixStack matrices, VertexConsumerProvider vertexConsumers, T livingEntity, EquipmentSlot armorSlot, int light, A model, CallbackInfo ci) { - CITEnchantment.shouldApply = false; - if (CITResewn.INSTANCE.activeCITs != null) - CITResewn.INSTANCE.activeCITs.setEnchantmentAppliedContextCached(null, null, null); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/BufferBuilderStorageAccessor.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/BufferBuilderStorageAccessor.java deleted file mode 100644 index 619a82d..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/BufferBuilderStorageAccessor.java +++ /dev/null @@ -1,15 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.citenchantment; - -import net.minecraft.client.render.BufferBuilder; -import net.minecraft.client.render.BufferBuilderStorage; -import net.minecraft.client.render.RenderLayer; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.SortedMap; - -@Mixin(BufferBuilderStorage.class) -public interface BufferBuilderStorageAccessor { - @Accessor("entityBuilders") - SortedMap entityBuilders(); -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ElytraFeatureRendererMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ElytraFeatureRendererMixin.java deleted file mode 100644 index 03fb4c0..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ElytraFeatureRendererMixin.java +++ /dev/null @@ -1,33 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.citenchantment; - -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.entity.feature.ElytraFeatureRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.EquipmentSlot; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.ItemStack; -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.CallbackInfo; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.pack.cits.CITEnchantment; - -@Mixin(ElytraFeatureRenderer.class) -public class ElytraFeatureRendererMixin { - @Inject(method = "render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;ILnet/minecraft/entity/LivingEntity;FFFFFF)V", at = @At("HEAD")) - private void setAppliedContextAndStartApplyingElytra(MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int i, LivingEntity livingEntity, float f, float g, float h, float j, float k, float l, CallbackInfo ci) { - if (CITResewnConfig.INSTANCE().enabled && CITResewn.INSTANCE.activeCITs != null) { - CITResewn.INSTANCE.activeCITs.setEnchantmentAppliedContextCached(livingEntity.getEquippedStack(EquipmentSlot.CHEST), livingEntity.world, livingEntity); - CITEnchantment.shouldApply = true; - } - } - - @Inject(method = "render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;ILnet/minecraft/entity/LivingEntity;FFFFFF)V", at = @At("RETURN")) - private void stopApplyingElytra(MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int i, LivingEntity livingEntity, float f, float g, float h, float j, float k, float l, CallbackInfo ci) { - CITEnchantment.shouldApply = false; - if (CITResewn.INSTANCE.activeCITs != null) - CITResewn.INSTANCE.activeCITs.setEnchantmentAppliedContextCached(null, null, null); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ItemRendererMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ItemRendererMixin.java deleted file mode 100644 index 13d91c7..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ItemRendererMixin.java +++ /dev/null @@ -1,86 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.citenchantment; - -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.*; -import net.minecraft.client.render.item.ItemRenderer; -import net.minecraft.client.render.model.BakedModel; -import net.minecraft.client.render.model.json.ModelTransformation; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; -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.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.pack.cits.CITEnchantment; - -@Mixin(ItemRenderer.class) -public class ItemRendererMixin { - @Inject(method = "getModel", at = @At("TAIL")) - private void setAppliedContext(ItemStack stack, World world, LivingEntity entity, int seed, CallbackInfoReturnable cir) { - if (CITResewnConfig.INSTANCE().enabled && CITResewn.INSTANCE.activeCITs != null) - CITResewn.INSTANCE.activeCITs.setEnchantmentAppliedContextCached(stack, world, entity); - } - - @Inject(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;IILnet/minecraft/client/render/model/BakedModel;)V", at = @At("HEAD")) - private void startApplyingItem(ItemStack stack, ModelTransformation.Mode renderMode, boolean leftHanded, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay, BakedModel model, CallbackInfo ci) { - if (CITResewnConfig.INSTANCE().enabled) - CITEnchantment.shouldApply = true; - } - - @Inject(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;IILnet/minecraft/client/render/model/BakedModel;)V", at = @At("TAIL")) - private void stopApplyingItem(ItemStack stack, ModelTransformation.Mode renderMode, boolean leftHanded, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay, BakedModel model, CallbackInfo ci) { - CITEnchantment.shouldApply = false; - if (CITResewn.INSTANCE.activeCITs != null) - CITResewn.INSTANCE.activeCITs.setEnchantmentAppliedContextCached(null, null, null); - } - - @Inject(method = "getArmorGlintConsumer", cancellable = true, at = @At("RETURN")) - private static void getArmorGlintConsumer(VertexConsumerProvider provider, RenderLayer layer, boolean solid, boolean glint, CallbackInfoReturnable cir) { - if (!CITEnchantment.shouldApply) - return; - VertexConsumer vertexConsumer = solid ? CITEnchantment.GlintRenderLayer.ARMOR_GLINT.tryApply(cir.getReturnValue(), layer, provider) : CITEnchantment.GlintRenderLayer.ARMOR_ENTITY_GLINT.tryApply(cir.getReturnValue(), layer, provider); - if (vertexConsumer != null) - cir.setReturnValue(vertexConsumer); - } - - @Inject(method = "getCompassGlintConsumer", cancellable = true, at = @At("RETURN")) - private static void getCompassGlintConsumer(VertexConsumerProvider provider, RenderLayer layer, MatrixStack.Entry entry, CallbackInfoReturnable cir) { - if (!CITEnchantment.shouldApply) - return; - VertexConsumer vertexConsumer = CITEnchantment.GlintRenderLayer.GLINT.tryApply(null, layer, provider); - if (vertexConsumer != null) - cir.setReturnValue(VertexConsumers.union(new OverlayVertexConsumer(vertexConsumer, entry.getPositionMatrix(), entry.getNormalMatrix()), cir.getReturnValue())); - } - - @Inject(method = "getDirectCompassGlintConsumer", cancellable = true, at = @At("RETURN")) - private static void getDirectCompassGlintConsumer(VertexConsumerProvider provider, RenderLayer layer, MatrixStack.Entry entry, CallbackInfoReturnable cir) { - if (!CITEnchantment.shouldApply) - return; - VertexConsumer vertexConsumer = CITEnchantment.GlintRenderLayer.DIRECT_GLINT.tryApply(null, layer, provider); - if (vertexConsumer != null) - cir.setReturnValue(VertexConsumers.union(new OverlayVertexConsumer(vertexConsumer, entry.getPositionMatrix(), entry.getNormalMatrix()), cir.getReturnValue())); - } - - @Inject(method = "getItemGlintConsumer", cancellable = true, at = @At("RETURN")) - private static void getItemGlintConsumer(VertexConsumerProvider provider, RenderLayer layer, boolean solid, boolean glint, CallbackInfoReturnable cir) { - if (!CITEnchantment.shouldApply) - return; - VertexConsumer vertexConsumer = MinecraftClient.isFabulousGraphicsOrBetter() && layer == TexturedRenderLayers.getItemEntityTranslucentCull() ? CITEnchantment.GlintRenderLayer.GLINT_TRANSLUCENT.tryApply(cir.getReturnValue(), layer, provider) : (solid ? CITEnchantment.GlintRenderLayer.GLINT.tryApply(cir.getReturnValue(), layer, provider) : CITEnchantment.GlintRenderLayer.ENTITY_GLINT.tryApply(cir.getReturnValue(), layer, provider)); - if (vertexConsumer != null) - cir.setReturnValue(vertexConsumer); - } - - @Inject(method = "getDirectItemGlintConsumer", cancellable = true, at = @At("RETURN")) - private static void getDirectItemGlintConsumer(VertexConsumerProvider provider, RenderLayer layer, boolean solid, boolean glint, CallbackInfoReturnable cir) { - if (!CITEnchantment.shouldApply) - return; - VertexConsumer vertexConsumer = solid ? CITEnchantment.GlintRenderLayer.DIRECT_GLINT.tryApply(cir.getReturnValue(), layer, provider) : CITEnchantment.GlintRenderLayer.DIRECT_ENTITY_GLINT.tryApply(cir.getReturnValue(), layer, provider); - if (vertexConsumer != null) - cir.setReturnValue(vertexConsumer); - } -} \ No newline at end of file diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ItemStackMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ItemStackMixin.java deleted file mode 100644 index 033bf8e..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/ItemStackMixin.java +++ /dev/null @@ -1,36 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.citenchantment; - -import net.minecraft.item.ItemStack; -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; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.pack.cits.CITEnchantment; - -import java.lang.ref.WeakReference; -import java.util.List; -import java.util.function.Supplier; - -@Mixin(ItemStack.class) -public class ItemStackMixin implements CITEnchantment.Cached { - private WeakReference> citresewn_cachedCITEnchantment = new WeakReference<>(null); - private long citresewn_cacheTimeCITEnchantment = 0; - - @Override - public List citresewn_getCachedCITEnchantment(Supplier> realtime) { - if (System.currentTimeMillis() - citresewn_cacheTimeCITEnchantment >= CITResewnConfig.INSTANCE().cache_ms) { - citresewn_cachedCITEnchantment = new WeakReference<>(realtime.get()); - citresewn_cacheTimeCITEnchantment = System.currentTimeMillis(); - } - - return citresewn_cachedCITEnchantment.get(); - } - - @Inject(method = "hasGlint", cancellable = true, at = @At("HEAD")) - private void disableDefaultGlint(CallbackInfoReturnable cir) { - if (CITResewn.INSTANCE.activeCITs != null && ((!CITResewn.INSTANCE.activeCITs.effectiveGlobalProperties.useGlint) || (CITEnchantment.appliedContext != null && CITEnchantment.shouldApply && !CITEnchantment.appliedContext.get(0).useGlint))) - cir.setReturnValue(false); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/MinecraftClientMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/MinecraftClientMixin.java deleted file mode 100644 index a9bea56..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/MinecraftClientMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.citenchantment; - -import net.minecraft.client.MinecraftClient; -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.CallbackInfo; - -import static shcm.shsupercm.fabric.citresewn.pack.cits.CITEnchantment.MergeMethod.ticks; - -@Mixin(MinecraftClient.class) -public class MinecraftClientMixin { - @Inject(method = "tick", at = @At("HEAD")) - public void onTick(CallbackInfo ci) { - ticks++; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/RenderPhaseAccessor.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/RenderPhaseAccessor.java deleted file mode 100644 index 24e7c3c..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/citenchantment/RenderPhaseAccessor.java +++ /dev/null @@ -1,21 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.citenchantment; - -import net.minecraft.client.render.RenderPhase; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -@Mixin(RenderPhase.class) -public interface RenderPhaseAccessor { - @Accessor("ARMOR_GLINT_SHADER") static RenderPhase.Shader ARMOR_GLINT_SHADER() { throw new RuntimeException(); } - @Accessor("ARMOR_ENTITY_GLINT_SHADER") static RenderPhase.Shader ARMOR_ENTITY_GLINT_SHADER() { throw new RuntimeException(); } - @Accessor("TRANSLUCENT_GLINT_SHADER") static RenderPhase.Shader TRANSLUCENT_GLINT_SHADER() { throw new RuntimeException(); } - @Accessor("GLINT_SHADER") static RenderPhase.Shader GLINT_SHADER() { throw new RuntimeException(); } - @Accessor("DIRECT_GLINT_SHADER") static RenderPhase.Shader DIRECT_GLINT_SHADER() { throw new RuntimeException(); } - @Accessor("ENTITY_GLINT_SHADER") static RenderPhase.Shader ENTITY_GLINT_SHADER() { throw new RuntimeException(); } - @Accessor("DIRECT_ENTITY_GLINT_SHADER") static RenderPhase.Shader DIRECT_ENTITY_GLINT_SHADER() { throw new RuntimeException(); } - @Accessor("DISABLE_CULLING") static RenderPhase.Cull DISABLE_CULLING() { throw new RuntimeException(); } - @Accessor("EQUAL_DEPTH_TEST") static RenderPhase.DepthTest EQUAL_DEPTH_TEST() { throw new RuntimeException(); } - @Accessor("COLOR_MASK") static RenderPhase.WriteMaskState COLOR_MASK() { throw new RuntimeException(); } - @Accessor("VIEW_OFFSET_Z_LAYERING") static RenderPhase.Layering VIEW_OFFSET_Z_LAYERING() { throw new RuntimeException(); } - @Accessor("ITEM_TARGET") static RenderPhase.Target ITEM_TARGET() { throw new RuntimeException(); } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ItemRendererMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ItemRendererMixin.java deleted file mode 100644 index 2cb5662..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ItemRendererMixin.java +++ /dev/null @@ -1,69 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.cititem; - -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.item.ItemModels; -import net.minecraft.client.render.item.ItemRenderer; -import net.minecraft.client.render.model.BakedModel; -import net.minecraft.client.render.model.json.ModelTransformation; -import net.minecraft.client.util.ModelIdentifier; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.world.World; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyVariable; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.pack.cits.CITItem; - -import java.lang.ref.WeakReference; - -@Mixin(ItemRenderer.class) -public class ItemRendererMixin { - @Shadow @Final private ItemModels models; - - private static WeakReference mojankCITModel = null; - - @Inject(method = "getModel", cancellable = true, at = @At("HEAD")) - private void getItemModel(ItemStack stack, World world, LivingEntity entity, int seed, CallbackInfoReturnable cir) { - if (!CITResewnConfig.INSTANCE().enabled || CITResewn.INSTANCE.activeCITs == null) - return; - - BakedModel citModel = CITResewn.INSTANCE.activeCITs.getItemModelCached(stack, world == null ? MinecraftClient.getInstance().world : world, entity, seed); - if (citModel != null) - cir.setReturnValue(citModel); - } - - @Inject(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;IILnet/minecraft/client/render/model/BakedModel;)V", at = @At("HEAD")) - private void fixMojankCITsContext(ItemStack stack, ModelTransformation.Mode renderMode, boolean leftHanded, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay, BakedModel model, CallbackInfo ci) { - mojankCITModel = null; - if (((CITItem.Cached) (Object) stack).citresewn_isMojankCIT()) { - boolean bl = renderMode == ModelTransformation.Mode.GUI || renderMode == ModelTransformation.Mode.GROUND || renderMode == ModelTransformation.Mode.FIXED; - if (bl) - mojankCITModel = new WeakReference<>(model); - else { // rendered in hand model of trident/spyglass - if (stack.isOf(Items.TRIDENT)) - mojankCITModel = new WeakReference<>(this.models.getModelManager().getModel(new ModelIdentifier("minecraft:trident_in_hand#inventory"))); - else if (stack.isOf(Items.SPYGLASS)) - mojankCITModel = new WeakReference<>(this.models.getModelManager().getModel(new ModelIdentifier("minecraft:spyglass_in_hand#inventory"))); - } - } else - mojankCITModel = null; - } - - @ModifyVariable(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;IILnet/minecraft/client/render/model/BakedModel;)V", at = @At(value = "LOAD", ordinal = 0, target = "Lnet/minecraft/client/render/model/BakedModel;getTransformation()Lnet/minecraft/client/render/model/json/ModelTransformation;"), argsOnly = true) - private BakedModel fixMojankCITs(BakedModel original) { - if (mojankCITModel != null) - return mojankCITModel.get(); - - return original; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ItemStackMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ItemStackMixin.java deleted file mode 100644 index 4c888d8..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ItemStackMixin.java +++ /dev/null @@ -1,40 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.cititem; - -import net.minecraft.item.ItemStack; -import org.spongepowered.asm.mixin.Mixin; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.pack.cits.CITItem; - -import java.lang.ref.WeakReference; -import java.util.function.Supplier; - -@Mixin(ItemStack.class) -public class ItemStackMixin implements CITItem.Cached { - private WeakReference citresewn_cachedCITItem = new WeakReference<>(null); - private long citresewn_cacheTimeCITItem = 0; - - /** - * Used by tridents and spy glasses to force their unique overrides to be applied correctly - */ - private boolean citresewn_mojankCIT = false; - - @Override - public CITItem citresewn_getCachedCITItem(Supplier realtime) { - if (System.currentTimeMillis() - citresewn_cacheTimeCITItem >= CITResewnConfig.INSTANCE().cache_ms) { - citresewn_cachedCITItem = new WeakReference<>(realtime.get()); - citresewn_cacheTimeCITItem = System.currentTimeMillis(); - } - - return citresewn_cachedCITItem.get(); - } - - @Override - public boolean citresewn_isMojankCIT() { - return citresewn_mojankCIT; - } - - @Override - public void citresewn_setMojankCIT(boolean mojankCIT) { - citresewn_mojankCIT = mojankCIT; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/JsonUnbakedModelAccessor.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/JsonUnbakedModelAccessor.java deleted file mode 100644 index f997d3e..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/JsonUnbakedModelAccessor.java +++ /dev/null @@ -1,22 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.cititem; - -import com.mojang.datafixers.util.Either; -import net.minecraft.client.render.model.json.JsonUnbakedModel; -import net.minecraft.client.util.SpriteIdentifier; -import net.minecraft.util.Identifier; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.Map; - -@Mixin(JsonUnbakedModel.class) -public interface JsonUnbakedModelAccessor { - @Accessor - Map> getTextureMap(); - - @Accessor - Identifier getParentId(); - - @Accessor - void setParentId(Identifier parentId); -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ModelLoaderMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ModelLoaderMixin.java deleted file mode 100644 index ec04910..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/cititem/ModelLoaderMixin.java +++ /dev/null @@ -1,165 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.cititem; - -import com.mojang.datafixers.util.Either; -import net.minecraft.client.render.model.BakedModel; -import net.minecraft.client.render.model.ModelLoader; -import net.minecraft.client.render.model.SpriteAtlasManager; -import net.minecraft.client.render.model.UnbakedModel; -import net.minecraft.client.render.model.json.JsonUnbakedModel; -import net.minecraft.client.render.model.json.ModelOverride; -import net.minecraft.client.texture.TextureManager; -import net.minecraft.client.util.ModelIdentifier; -import net.minecraft.client.util.SpriteIdentifier; -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 org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.pack.ResewnItemModelIdentifier; -import shcm.shsupercm.fabric.citresewn.pack.ResewnTextureIdentifier; -import shcm.shsupercm.fabric.citresewn.pack.cits.CIT; -import shcm.shsupercm.fabric.citresewn.pack.cits.CITItem; - -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.stream.Collectors; - -import static shcm.shsupercm.fabric.citresewn.CITResewn.info; - -@Mixin(ModelLoader.class) -public class ModelLoaderMixin { - @Shadow @Final private ResourceManager resourceManager; - @Shadow @Final private Set modelsToLoad; - @Shadow @Final private Map modelsToBake; - @Shadow @Final private Map unbakedModels; - @Shadow @Final private Map bakedModels; - - @Inject(method = "addModel", at = @At("TAIL")) - public void addCITItemModels(ModelIdentifier eventModelId, CallbackInfo ci) { if (eventModelId != ModelLoader.MISSING_ID) return; - if (CITResewn.INSTANCE.activeCITs == null) - return; - - info("Loading CITItem models..."); - CITResewn.INSTANCE.activeCITs.citItems.values().stream() - .flatMap(Collection::stream) - .distinct() - .forEach(citItem -> { - try { - citItem.loadUnbakedAssets(resourceManager); - - for (JsonUnbakedModel unbakedModel : citItem.unbakedAssets.values()) { - ResewnItemModelIdentifier id = new ResewnItemModelIdentifier(unbakedModel.id); - this.unbakedModels.put(id, unbakedModel); - this.modelsToLoad.addAll(unbakedModel.getModelDependencies()); - this.modelsToBake.put(id, unbakedModel); - } - } catch (Exception e) { - CITResewn.logErrorLoading(e.getMessage()); - } - }); - - CITItem.GENERATED_SUB_CITS_SEEN.clear(); - } - - @Inject(method = "upload", at = @At("RETURN")) - public void linkBakedCITItemModels(TextureManager textureManager, Profiler profiler, CallbackInfoReturnable cir) { - if (CITResewn.INSTANCE.activeCITs == null) - return; - - profiler.push("citresewn_linking"); - info("Linking baked models to CITItems..."); - - if (CITResewn.INSTANCE.activeCITs != null) { - for (CITItem citItem : CITResewn.INSTANCE.activeCITs.citItems.values().stream().flatMap(Collection::stream).distinct().collect(Collectors.toList())) { - for (Map.Entry, JsonUnbakedModel> citModelEntry : citItem.unbakedAssets.entrySet()) { - if (citModelEntry.getKey() == null) { - citItem.bakedModel = this.bakedModels.get(new ResewnItemModelIdentifier(citModelEntry.getValue().id)); - } else { - BakedModel bakedModel = bakedModels.get(new ResewnItemModelIdentifier(citModelEntry.getValue().id)); - - if (bakedModel == null) - CITResewn.logWarnLoading("Skipping sub cit: Failed loading model for \"" + citModelEntry.getValue().id + "\" in " + citItem.pack.resourcePack.getName() + " -> " + citItem.propertiesIdentifier.getPath()); - else - citItem.bakedSubModels.override(citModelEntry.getKey(), bakedModel); - } - } - citItem.unbakedAssets = null; - } - } - - profiler.pop(); - } - - - @Inject(method = "loadModelFromJson", cancellable = true, at = @At("HEAD")) - public void forceLiteralResewnModelIdentifier(Identifier id, CallbackInfoReturnable cir) { - if (id instanceof ResewnItemModelIdentifier) { - InputStream is = null; - Resource resource = null; - try { - JsonUnbakedModel json = JsonUnbakedModel.deserialize(IOUtils.toString(is = (resource = resourceManager.getResource(id)).getInputStream(), StandardCharsets.UTF_8)); - json.id = id.toString(); - json.id = json.id.substring(0, json.id.length() - 5); - - ((JsonUnbakedModelAccessor) json).getTextureMap().replaceAll((layer, original) -> { - Optional left = original.left(); - if (left.isPresent()) { - String originalPath = left.get().getTextureId().getPath(); - String[] split = originalPath.split("/"); - if (originalPath.startsWith("./") || (split.length > 2 && split[1].equals("cit"))) { - Identifier resolvedIdentifier = CIT.resolvePath(id, originalPath, ".png", identifier -> resourceManager.containsResource(identifier)); - if (resolvedIdentifier != null) - return Either.left(new SpriteIdentifier(left.get().getAtlasId(), new ResewnTextureIdentifier(resolvedIdentifier))); - } - } - return original; - }); - - Identifier parentId = ((JsonUnbakedModelAccessor) json).getParentId(); - if (parentId != null) { - String[] parentIdPathSplit = parentId.getPath().split("/"); - if (parentId.getPath().startsWith("./") || (parentIdPathSplit.length > 2 && parentIdPathSplit[1].equals("cit"))) { - parentId = CIT.resolvePath(id, parentId.getPath(), ".json", identifier -> resourceManager.containsResource(identifier)); - if (parentId != null) - ((JsonUnbakedModelAccessor) json).setParentId(new ResewnItemModelIdentifier(parentId)); - } - } - - json.getOverrides().replaceAll(override -> { - String[] modelIdPathSplit = override.getModelId().getPath().split("/"); - if (override.getModelId().getPath().startsWith("./") || (modelIdPathSplit.length > 2 && modelIdPathSplit[1].equals("cit"))) { - Identifier resolvedOverridePath = CIT.resolvePath(id, override.getModelId().getPath(), ".json", identifier -> resourceManager.containsResource(identifier)); - if (resolvedOverridePath != null) - return new ModelOverride(new ResewnItemModelIdentifier(resolvedOverridePath), override.streamConditions().collect(Collectors.toList())); - } - - return override; - }); - - cir.setReturnValue(json); - } catch (Exception ignored) { - } finally { - IOUtils.closeQuietly(is, resource); - } - } - } - - @ModifyArg(method = "loadModelFromJson", at = - @At(value = "INVOKE", target = "Lnet/minecraft/resource/ResourceManager;getResource(Lnet/minecraft/util/Identifier;)Lnet/minecraft/resource/Resource;")) - public Identifier fixDuplicatePrefixSuffix(Identifier original) { - if (original.getPath().startsWith("models/models/") && original.getPath().endsWith(".json.json") && original.getPath().contains("cit")) - return new Identifier(original.getNamespace(), original.getPath().substring(7, original.getPath().length() - 5)); - - return original; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ChatScreenMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ChatScreenMixin.java deleted file mode 100644 index cdd9eb1..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ChatScreenMixin.java +++ /dev/null @@ -1,23 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.core; - -import net.minecraft.client.gui.screen.ChatScreen; -import net.minecraft.client.gui.screen.Screen; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import shcm.shsupercm.fabric.citresewn.OptionalCompat; - -import static shcm.shsupercm.fabric.citresewn.CITResewnCommand.openConfig; - -@Mixin(ChatScreen.class) -public class ChatScreenMixin { - @ModifyArg(method = "keyPressed", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/MinecraftClient;setScreen(Lnet/minecraft/client/gui/screen/Screen;)V")) - public Screen redirectConfigScreen(Screen original) { - if (original == null && openConfig) { - openConfig = false; - return OptionalCompat.getModConfigScreenFactory().apply(null); - } - - return original; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/GroupResourcePackAccessor.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/GroupResourcePackAccessor.java deleted file mode 100644 index 7ab1c16..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/GroupResourcePackAccessor.java +++ /dev/null @@ -1,14 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.core; - -import net.fabricmc.fabric.api.resource.ModResourcePack; -import net.fabricmc.fabric.impl.resource.loader.GroupResourcePack; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.List; - -/* if (FabricLoader.getInstance().isModLoaded("fabric-resource-loader-v0")) */ @Mixin(GroupResourcePack.class) -public interface GroupResourcePackAccessor { - @Accessor - List getPacks(); -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ModelLoaderMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ModelLoaderMixin.java deleted file mode 100644 index d65ffb8..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ModelLoaderMixin.java +++ /dev/null @@ -1,51 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.core; - -import net.minecraft.client.render.model.ModelLoader; -import net.minecraft.client.util.ModelIdentifier; -import net.minecraft.resource.ResourceManager; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import shcm.shsupercm.fabric.citresewn.ActiveCITs; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.pack.CITPack; -import shcm.shsupercm.fabric.citresewn.pack.CITParser; -import shcm.shsupercm.fabric.citresewn.pack.cits.CIT; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - -import static shcm.shsupercm.fabric.citresewn.CITResewn.info; - -@Mixin(value = ModelLoader.class, priority = 999) -public abstract class ModelLoaderMixin { - @Shadow @Final private ResourceManager resourceManager; - - @Inject(method = "addModel", at = @At("TAIL")) - public void initCITs(ModelIdentifier eventModelId, CallbackInfo ci) { if (eventModelId != ModelLoader.MISSING_ID) return; - if (CITResewn.INSTANCE.activeCITs != null) { - info("Clearing active CITs.."); - CITResewn.INSTANCE.activeCITs.dispose(); - CITResewn.INSTANCE.activeCITs = null; - } - - if (!CITResewnConfig.INSTANCE().enabled) - return; - - info("Parsing CITs..."); - List parsedPacks = CITParser.parseCITs(resourceManager.streamResourcePacks().collect(Collectors.toCollection(ArrayList::new))); - List parsed = parsedPacks.stream().flatMap(pack -> pack.cits.stream()).collect(Collectors.toCollection(ArrayList::new)); - - if (parsed.size() > 0) { - info("Activating CITs..."); - CITResewn.INSTANCE.activeCITs = new ActiveCITs(parsedPacks, parsed); - } else - info("No cit packs found."); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/NbtCompoundAccessor.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/NbtCompoundAccessor.java deleted file mode 100644 index 8ced305..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/NbtCompoundAccessor.java +++ /dev/null @@ -1,14 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.core; - -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtElement; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.Map; - -@Mixin(NbtCompound.class) -public interface NbtCompoundAccessor { - @Accessor - Map getEntries(); -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/SpriteAtlasTextureMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/SpriteAtlasTextureMixin.java deleted file mode 100644 index 8cc195b..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/SpriteAtlasTextureMixin.java +++ /dev/null @@ -1,18 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.core; - -import net.minecraft.client.texture.SpriteAtlasTexture; -import net.minecraft.util.Identifier; -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; -import shcm.shsupercm.fabric.citresewn.pack.ResewnTextureIdentifier; - -@Mixin(SpriteAtlasTexture.class) -public class SpriteAtlasTextureMixin { - @Inject(method = "getTexturePath", cancellable = true, at = @At("HEAD")) - public void forceLiteralResewnTextureIdentifier(Identifier id, CallbackInfoReturnable cir) { - if (id instanceof ResewnTextureIdentifier) - cir.setReturnValue(id); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ZipResourcePackMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ZipResourcePackMixin.java deleted file mode 100644 index 7acbcb7..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/core/ZipResourcePackMixin.java +++ /dev/null @@ -1,60 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin.core; - -import com.google.common.collect.Lists; -import net.minecraft.resource.ResourceType; -import net.minecraft.resource.ZipResourcePack; -import net.minecraft.util.Identifier; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.function.Predicate; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -@Mixin(ZipResourcePack.class) -public abstract class ZipResourcePackMixin { - @Shadow protected abstract ZipFile getZipFile() throws IOException; - - @Inject(method = "findResources", cancellable = true, at = @At("HEAD")) - public void fixDepthBug(ResourceType type, String namespace, String prefix, int maxDepth, Predicate pathFilter, CallbackInfoReturnable> cir) { - if (maxDepth != Integer.MAX_VALUE - 53) - return; - - ZipFile zipFile2; - try { - zipFile2 = this.getZipFile(); - } catch (IOException var15) { - cir.setReturnValue(Collections.emptySet()); return; - } - - Enumeration enumeration = zipFile2.entries(); - List list = Lists.newArrayList(); - String var10000 = type.getDirectory(); - String string = var10000 + "/" + namespace + "/"; - String string2 = string + prefix + "/"; - - while(enumeration.hasMoreElements()) { - ZipEntry zipEntry = enumeration.nextElement(); - if (!zipEntry.isDirectory()) { - String string3 = zipEntry.getName(); - if (!string3.endsWith(".mcmeta") && string3.startsWith(string2)) { - String string4 = string3.substring(string.length()); - String[] strings = string4.split("/"); - if (pathFilter.test(strings[strings.length - 1])) { - list.add(new Identifier(namespace, string4)); - } - } - } - } - - cir.setReturnValue(list); return; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/CITPack.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/CITPack.java deleted file mode 100644 index aadf518..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/CITPack.java +++ /dev/null @@ -1,65 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack; - -import net.minecraft.resource.ResourcePack; -import shcm.shsupercm.fabric.citresewn.pack.cits.CIT; -import shcm.shsupercm.fabric.citresewn.pack.cits.CITEnchantment; - -import java.util.*; - -public class CITPack { - public final ResourcePack resourcePack; - public final Collection cits = new ArrayList<>(); - - public CITEnchantment.MergeMethod method = CITEnchantment.MergeMethod.AVERAGE; - public Integer cap = 8; - public Float fade = 0.5f; - public Boolean useGlint = true; - - public CITPack(ResourcePack resourcePack) { - this.resourcePack = resourcePack; - } - - public void loadGlobalProperties(Properties properties) throws Exception { - try { - this.method = properties.containsKey("method") ? CITEnchantment.MergeMethod.valueOf(properties.getProperty("method").toUpperCase(Locale.ENGLISH)) : null; - - if (properties.containsKey("cap")) { - this.cap = Integer.parseInt(properties.getProperty("cap")); - if (this.cap < 0) - throw new Exception("cap cannot be negative"); - } else - this.cap = null; - - if (properties.containsKey("fade")) { - this.fade = Float.parseFloat(properties.getProperty("fade")); - if (this.fade < 0f) - throw new Exception("fade cannot be negative"); - } else - this.fade = null; - - this.useGlint = properties.containsKey("useGlint") ? switch (properties.getProperty("useGlint").toLowerCase(Locale.ENGLISH)) { - case "true" -> true; - case "false" -> false; - default -> throw new Exception("useGlint is not a boolean"); - } : null; - } catch (Exception e) { - this.method = null; - this.cap = null; - this.fade = null; - this.useGlint = null; - throw e; - } - } - - public void loadGlobalProperties(CITPack properties) { - if (properties.method != null) - this.method = properties.method; - if (properties.cap != null) - this.cap = properties.cap; - if (properties.fade != null) - this.fade = properties.fade; - if (properties.useGlint != null) - this.useGlint = properties.useGlint; - } - -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/CITParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/CITParser.java deleted file mode 100644 index 974d2ec..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/CITParser.java +++ /dev/null @@ -1,119 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack; - -import net.fabricmc.fabric.impl.resource.loader.GroupResourcePack; -import net.minecraft.resource.ResourcePack; -import net.minecraft.resource.ResourceType; -import net.minecraft.util.Identifier; -import org.apache.commons.lang3.StringUtils; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.ex.CITParseException; -import shcm.shsupercm.fabric.citresewn.mixin.core.GroupResourcePackAccessor; -import shcm.shsupercm.fabric.citresewn.pack.cits.*; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * Parses cits from resourcepacks - */ -public final class CITParser { private CITParser() {} - /** - * CIT type registry. - */ - public static final Map REGISTRY = new HashMap<>(); - static { - REGISTRY.put("item", CITItem::new); - REGISTRY.put("armor", CITArmor::new); - REGISTRY.put("elytra", CITElytra::new); - REGISTRY.put("enchantment", CITEnchantment::new); - } - - /** - * Parses cit entries from an ordered collection of resourcepacks. - * @param packs packs to parse - * @return a collection of parsed CITs - */ - public static List parseCITs(Collection packs) { - return packs.stream() - .map(CITParser::parse) - .flatMap(Collection::stream) - .collect(Collectors.toList()); - } - - /** - * Parses a resourcepack into a possible collection of citpacks that are contained within. - * @param resourcePack pack to parse - * @return a collection of CITPacks or an empty collection if resourcepack contains none - */ - public static Collection parse(ResourcePack resourcePack) { - if (resourcePack instanceof GroupResourcePack) - return ((GroupResourcePackAccessor) resourcePack).getPacks().stream() - .map(CITParser::parse) - .flatMap(Collection::stream) - .collect(Collectors.toList()); - - final CITPack citPack = new CITPack(resourcePack); - - Collection packProperties = new ArrayList<>(); - for (String namespace : resourcePack.getNamespaces(ResourceType.CLIENT_RESOURCES)) - if (Identifier.isValid(namespace)) - for (String citRoot : new String[] { "citresewn", "optifine", "mcpatcher" }) { - packProperties.addAll(resourcePack.findResources(ResourceType.CLIENT_RESOURCES, namespace, citRoot + "/cit", Integer.MAX_VALUE - 53, s -> s.endsWith(".properties"))); - Identifier global = new Identifier(namespace, citRoot + "/cit.properties"); - if (resourcePack.contains(ResourceType.CLIENT_RESOURCES, global)) - packProperties.add(global); - } - - boolean readGlobalProperties = false; - for (Iterator iterator = packProperties.iterator(); iterator.hasNext(); ) { - Identifier propertiesIdentifier = iterator.next(); - try { - if (StringUtils.countMatches(propertiesIdentifier.getPath(), '/') <= 2 && propertiesIdentifier.getPath().endsWith("cit.properties")) { - iterator.remove(); - if (!readGlobalProperties) - try (InputStream is = resourcePack.open(ResourceType.CLIENT_RESOURCES, propertiesIdentifier)) { - Properties citProperties = new Properties(); - citProperties.load(is); - citPack.loadGlobalProperties(citProperties); - readGlobalProperties = true; - } - } - } catch (Exception e) { - CITResewn.logErrorLoading("Skipped global properties: " + e.getMessage() + " in " + resourcePack.getName() + " -> " + propertiesIdentifier); - } - } - - packProperties.stream() - .flatMap(citIdentifier -> { - try (InputStream is = resourcePack.open(ResourceType.CLIENT_RESOURCES, citIdentifier)) { - Properties citProperties = new Properties(); - citProperties.load(new InputStreamReader(is, StandardCharsets.UTF_8)); - - CITConstructor type = REGISTRY.get(citProperties.getProperty("type", "item")); - if (type == null) - throw new CITParseException(citPack.resourcePack, citIdentifier, "Unknown cit type \"" + citProperties.getProperty("type") + "\""); - - return Stream.of(type.cit(citPack, citIdentifier, citProperties)); - } catch (Exception e) { - CITResewn.logErrorLoading(e.getMessage()); - return Stream.empty(); - } - }) - .collect(Collectors.toCollection(() -> citPack.cits)); - - if (citPack.cits.isEmpty()) - return Collections.emptySet(); - else { - CITResewn.info("Found " + citPack.cits.size() + " CIT" + (citPack.cits.size() == 1 ? "" : "s") + " in " + resourcePack.getName()); - return Collections.singleton(citPack); - } - } - - public interface CITConstructor { - CIT cit(CITPack pack, Identifier identifier, Properties properties) throws CITParseException; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ResewnItemModelIdentifier.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ResewnItemModelIdentifier.java deleted file mode 100644 index c531983..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ResewnItemModelIdentifier.java +++ /dev/null @@ -1,18 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack; - -import net.minecraft.util.Identifier; -import shcm.shsupercm.fabric.citresewn.mixin.core.ModelLoaderMixin; - -/** - * Marks models as cit item models. - * @see ModelLoaderMixin - */ -public class ResewnItemModelIdentifier extends Identifier { - public ResewnItemModelIdentifier(String id) { - super(id); - } - - public ResewnItemModelIdentifier(Identifier identifier) { - super(identifier.getNamespace(), identifier.getPath()); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ResewnTextureIdentifier.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ResewnTextureIdentifier.java deleted file mode 100644 index 033c567..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ResewnTextureIdentifier.java +++ /dev/null @@ -1,14 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack; - -import net.minecraft.util.Identifier; -import shcm.shsupercm.fabric.citresewn.mixin.core.SpriteAtlasTextureMixin; - -/** - * Marks path identifiers as forced literal texture paths. - * @see SpriteAtlasTextureMixin - */ -public class ResewnTextureIdentifier extends Identifier { - public ResewnTextureIdentifier(Identifier identifier) { - super(identifier.getNamespace(), identifier.getPath()); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CIT.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CIT.java deleted file mode 100644 index a58c946..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CIT.java +++ /dev/null @@ -1,435 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack.cits; - -import net.minecraft.enchantment.EnchantmentHelper; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.EnchantedBookItem; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.nbt.*; -import net.minecraft.text.Text; -import net.minecraft.util.Hand; -import net.minecraft.util.Identifier; -import net.minecraft.util.Pair; -import net.minecraft.util.registry.Registry; -import net.minecraft.world.World; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.ex.CITParseException; -import shcm.shsupercm.fabric.citresewn.mixin.core.NbtCompoundAccessor; -import shcm.shsupercm.fabric.citresewn.pack.CITPack; - -import java.util.*; -import java.util.function.Predicate; -import java.util.regex.Pattern; - -public abstract class CIT { - public final CITPack pack; - public final Identifier propertiesIdentifier; - - public final Set items = new HashSet<>(); - - public final int damageMin, damageMax; - public final boolean damageAny, damageRange, damagePercentage; - public final Integer damageMask; - - public final int stackMin, stackMax; - public final boolean stackAny, stackRange; - - public final Set enchantments = new HashSet<>(); - public final List> enchantmentLevels = new ArrayList<>(); - public final boolean enchantmentsAny, enchantmentLevelsAny; - - public final Hand hand; - - public final Predicate nbt; - - public final int weight; - - public CIT(CITPack pack, Identifier identifier, Properties properties) throws CITParseException { - this.pack = pack; - this.propertiesIdentifier = identifier; - try { - for (String itemId : (properties.getProperty("items", properties.getProperty("matchItems", " "))).split(" ")) - if (!itemId.isEmpty()) { - Identifier itemIdentifier = new Identifier(itemId); - if (!Registry.ITEM.containsId(itemIdentifier)) - throw new Exception("Unknown item " + itemId); - this.items.add(Registry.ITEM.get(itemIdentifier)); - } - if (this.items.isEmpty()) - try { - String id = propertiesIdentifier.getPath().substring(0, propertiesIdentifier.getPath().length() - 11); - String[] split = id.split("/"); - id = split[split.length - 1]; - Identifier itemId = new Identifier(propertiesIdentifier.getNamespace(), id); - if (Registry.ITEM.containsId(itemId)) - this.items.add(Registry.ITEM.get(itemId)); - } catch (Exception ignored) { } - - String damage = properties.getProperty("damage"); - if (damageAny = damage == null) { - this.damageRange = false; - this.damagePercentage = false; - this.damageMin = 0; - this.damageMax = 0; - } else { - if (this.damagePercentage = damage.contains("%")) - damage = damage.replace("%", ""); - - if (damage.contains("-")) { - String[] split = damage.split("-"); - if (split.length > 2) - throw new Exception("damage range must have up to 2 numbers"); - - this.damageMin = split[0].isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(split[0]); - this.damageMax = split.length == 1 ? Integer.MAX_VALUE : Integer.parseInt(split[1]); - - if (this.damageMin > this.damageMax) - throw new Exception("damage range min is higher than max"); - - this.damageRange = this.damageMin < this.damageMax; - } else { - this.damageRange = false; - this.damageMin = this.damageMax = Integer.parseInt(damage); - } - } - - this.damageMask = properties.containsKey("damageMask") ? Integer.parseInt(properties.getProperty("damageMask")) : null; - - String stackSize = properties.getProperty("stackSize"); - if (stackAny = stackSize == null) { - this.stackRange = false; - this.stackMin = 0; - this.stackMax = 0; - } else { - if (stackSize.contains("-")) { - String[] split = stackSize.split("-"); - if (split.length > 2) - throw new Exception("stackSize range must have up to 2 numbers"); - - this.stackMin = split[0].isEmpty() ? Integer.MIN_VALUE : Integer.parseInt(split[0]); - this.stackMax = split.length == 1 ? Integer.MAX_VALUE : Integer.parseInt(split[1]); - - if (this.stackMin > this.stackMax) - throw new Exception("stackSize range min is higher than max"); - - this.stackRange = this.stackMin < this.stackMax; - } else { - this.stackRange = false; - this.stackMin = this.stackMax = Integer.parseInt(stackSize); - } - } - - String enchantmentIDs = properties.getProperty("enchantments", properties.getProperty("enchantmentIDs")); - if (!(this.enchantmentsAny = enchantmentIDs == null)) { - for (String ench : enchantmentIDs.split(" ")) { - Identifier enchIdentifier = new Identifier(ench); - if (!Registry.ENCHANTMENT.containsId(enchIdentifier)) - CITResewn.logWarnLoading("CIT Warning: Unknown enchantment " + enchIdentifier); - this.enchantments.add(enchIdentifier); - } - } - - String enchantmentLevelsProp = properties.getProperty("enchantmentLevels"); - if (!(this.enchantmentLevelsAny = enchantmentLevelsProp == null)) { - for (String range : enchantmentLevelsProp.split(" ")) { - if (range.contains("-")) { - if (range.startsWith("-")) { - range = range.substring(1); - if (range.contains("-")) - throw new Exception("enchantmentLevels ranges must have up to 2 numbers each"); - this.enchantmentLevels.add(new Pair<>(0, Integer.parseInt(range))); - } else if (range.endsWith("-")) { - range = range.substring(0, range.length() - 1); - if (range.contains("-")) - throw new Exception("enchantmentLevels ranges must have up to 2 numbers each"); - this.enchantmentLevels.add(new Pair<>(Integer.parseInt(range), Integer.MAX_VALUE)); - } else { - String[] split = range.split("-"); - if (split.length != 2) - throw new Exception("enchantmentLevels ranges must have up to 2 numbers each"); - Pair minMaxPair = new Pair<>(Integer.parseInt(split[0]), Integer.parseInt(split[1])); - if (minMaxPair.getLeft() > minMaxPair.getRight()) - throw new Exception("enchantmentLevels range min is higher than max"); - this.enchantmentLevels.add(minMaxPair); - } - } else { - int level = Integer.parseInt(range); - this.enchantmentLevels.add(new Pair<>(level, level)); - } - } - } - - this.hand = switch (properties.getProperty("hand", "any")) { - case "main" -> Hand.MAIN_HAND; - case "off" -> Hand.OFF_HAND; - default -> null; - }; - - List> nbtPredicates = new ArrayList<>(); - for (Object o : properties.keySet()) - if (o instanceof String property && property.startsWith("nbt.")) { - String matchProperty = properties.getProperty(property); - final String[] path = property.substring(4).split("\\."); - final Predicate match; - final boolean caseSensitive = !matchProperty.startsWith("i"); - - if (matchProperty.startsWith(caseSensitive ? "pattern:" : "ipattern:")) { - matchProperty = caseSensitive ? matchProperty.substring(8) : matchProperty.substring(9).toLowerCase(Locale.ENGLISH); - final String pattern = matchProperty; - match = s -> matchesPattern(caseSensitive ? s : s.toLowerCase(), pattern, 0, s.length(), 0, pattern.length()); - } else if (matchProperty.startsWith(caseSensitive ? "regex:" : "iregex:")) { - matchProperty = caseSensitive ? matchProperty.substring(6) : matchProperty.substring(7).toLowerCase(Locale.ENGLISH); - final Pattern pattern = Pattern.compile(matchProperty); - match = s -> pattern.matcher(caseSensitive ? s : s.toLowerCase()).matches(); - } else { - if (property.equals("nbt.display.color") && matchProperty.startsWith("#")) - try { - matchProperty = String.valueOf(Integer.parseInt(matchProperty.substring(1).toLowerCase(Locale.ENGLISH), 16)); - } catch (Exception ignored) { } - - final String pattern = matchProperty; - match = s -> s.equals(pattern); - } - - final boolean checkJson = (path[path.length - 1].equals("Name") || (path.length >= 2 && path[path.length - 2].equals("Lore"))) && !((matchProperty.startsWith("{") || matchProperty.startsWith("\\{")) && matchProperty.endsWith("}")); - - nbtPredicates.add(new Predicate() { - public boolean test(NbtElement nbtElement, int index) { - if (index >= path.length) { - if (nbtElement instanceof NbtString nbtString) { - String text = nbtString.asString(); - if (checkJson) - try { - //noinspection ConstantConditions - text = Text.Serializer.fromJson(text).getString(); - } catch (Exception ignored) { } - - return match.test(text); - } else if (nbtElement instanceof AbstractNbtNumber nbtNumber) - return match.test(String.valueOf(nbtNumber.numberValue())); - } else { - String name = path[index]; - if (name.equals("*")) { - if (nbtElement instanceof NbtCompound nbtCompound) { - for (NbtElement subElement : ((NbtCompoundAccessor) nbtCompound).getEntries().values()) - if (test(subElement, index + 1)) - return true; - } else if (nbtElement instanceof NbtList nbtList) { - for (NbtElement subElement : nbtList) - if (test(subElement, index + 1)) - return true; - } - } else { - if (nbtElement instanceof NbtCompound nbtCompound) { - NbtElement subElement = nbtCompound.get(name); - return subElement != null && test(subElement, index + 1); - } else if (nbtElement instanceof NbtList nbtList) { - try { - NbtElement subElement = nbtList.get(Integer.parseInt(name)); - return subElement != null && test(subElement, index + 1); - } catch (Exception ignored) { - return false; - } - } - } - } - return false; - } - - @Override - public boolean test(NbtCompound nbtCompound) { - return test(nbtCompound, 0); - } - }); - } - this.nbt = nbtCompound -> { - for (Predicate predicate : nbtPredicates) - if(!predicate.test(nbtCompound)) - return false; - return true; - }; - - this.weight = Integer.parseInt(properties.getProperty("weight", "0")); - } catch (Exception e) { - throw new CITParseException(pack.resourcePack, identifier, (e.getClass() == Exception.class ? "" : e.getClass().getSimpleName() + ": ") + e.getMessage()); - } - } - - public boolean test(ItemStack stack, Hand hand, World world, LivingEntity entity, boolean ignoreItemType) { - if (!ignoreItemType && !items.isEmpty() && !items.contains(stack.getItem())) - return false; - - if (!damageAny && stack.getItem().isDamageable()) { - int damage = stack.getDamage(); - if (damageMask != null) - damage &= damageMask; - if (damagePercentage) - damage = Math.round(100f * (float) stack.getDamage() / (float) stack.getMaxDamage()); - if (damageRange ? (damage < damageMin || damage > damageMax) : (damage != damageMin)) - return false; - } - - if (!stackAny) { - int count = stack.getCount(); - if (stackRange ? (count < stackMin || count > stackMax) : (count != stackMin)) - return false; - } - - if (this.hand != null && this.hand != hand) - return false; - - if (!enchantmentsAny) { - Map stackEnchantments = new LinkedHashMap<>(); - for (NbtElement nbtElement : stack.isOf(Items.ENCHANTED_BOOK) ? EnchantedBookItem.getEnchantmentNbt(stack) : stack.getEnchantments()) - stackEnchantments.put(EnchantmentHelper.getIdFromNbt((NbtCompound) nbtElement), EnchantmentHelper.getLevelFromNbt((NbtCompound) nbtElement)); - - boolean matches = false; - for (Identifier enchantment : enchantments) { - Integer level = stackEnchantments.get(enchantment); - if (level != null) - if (enchantmentLevelsAny) { - if (level > 0) { - matches = true; - break; - } - } else - for (Pair levelRange : enchantmentLevels) - if (level >= levelRange.getLeft() && level <= levelRange.getRight()) { - matches = true; - break; - } - } - - if (!matches) - return false; - } else if (!enchantmentLevelsAny) { - Collection levels = new ArrayList<>(); - levels.add(0); - for (NbtElement nbtElement : stack.isOf(Items.ENCHANTED_BOOK) ? EnchantedBookItem.getEnchantmentNbt(stack) : stack.getEnchantments()) - levels.add(EnchantmentHelper.getLevelFromNbt((NbtCompound) nbtElement)); - - boolean matches = false; - - l: for (Integer level : levels) { - for (Pair levelRange : enchantmentLevels) { - if (level >= levelRange.getLeft() && level <= levelRange.getRight()) { - matches = true; - break l; - } - } - } - - if (!matches) - return false; - } - - return nbt == null || nbt.test(stack.getNbt()); - } - - public void dispose() { - //stub - } - - /** - * Takes a defined path and resolves it to an identifier pointing to the resourcepack's path of the specified extension(returns null if no path can be resolved).
- * If definedPath is null, will try to resolve a relative file with the same name as the propertyIdentifier with the extension, otherwise:
- * definedPath will be formatted to replace "\\" with "/" the extension will be appended if not there already.
- * It will first try using definedPath as an absolute path, if it cant resolve(or definedPath starts with ./), definedPath will be considered relative.
- * Relative paths support going to parent directories using "..". - */ - public static Identifier resolvePath(Identifier propertyIdentifier, String path, String extension, Predicate packContains) { - if (path == null) { - path = propertyIdentifier.getPath().substring(0, propertyIdentifier.getPath().length() - 11); - if (!path.endsWith(extension)) - path = path + extension; - Identifier pathIdentifier = new Identifier(propertyIdentifier.getNamespace(), path); - return packContains.test(pathIdentifier) ? pathIdentifier : null; - } - - Identifier pathIdentifier = new Identifier(path); - - path = pathIdentifier.getPath().replace('\\', '/'); - if (!path.endsWith(extension)) - path = path + extension; - - if (path.startsWith("./")) - path = path.substring(2); - else if (!path.contains("..")) { - pathIdentifier = new Identifier(pathIdentifier.getNamespace(), path); - if (packContains.test(pathIdentifier)) - return pathIdentifier; - else if (path.startsWith("assets/")) { - path = path.substring(7); - int sep = path.indexOf('/'); - pathIdentifier = new Identifier(path.substring(0, sep), path.substring(sep + 1)); - if (packContains.test(pathIdentifier)) - return pathIdentifier; - } - pathIdentifier = new Identifier(pathIdentifier.getNamespace(), switch (extension) { - case ".png" -> "textures/"; - case ".json" -> "models/"; - - /* UNREACHABLE FAILSAFE */ - default -> ""; - } + path); - if (packContains.test(pathIdentifier)) - return pathIdentifier; - } - - LinkedList pathParts = new LinkedList<>(Arrays.asList(propertyIdentifier.getPath().split("/"))); - pathParts.removeLast(); - - if (path.contains("/")) { - for (String part : path.split("/")) { - if (part.equals("..")) { - if (pathParts.size() == 0) - return null; - pathParts.removeLast(); - } else - pathParts.addLast(part); - } - } else - pathParts.addLast(path); - path = String.join("/", pathParts); - - pathIdentifier = new Identifier(propertyIdentifier.getNamespace(), path); - - return packContains.test(pathIdentifier) ? pathIdentifier : null; - } - - /** - * Author: Paul "prupe" Rupe
- * Taken from MCPatcher under public domain licensing.
- * https://bitbucket.org/prupe/mcpatcher/src/1aa45839b2cd029143809edfa60ec59e5ef75f80/newcode/src/com/prupe/mcpatcher/mal/nbt/NBTRule.java#lines-269:301 - */ - public static boolean matchesPattern(String value, String pattern, int curV, int maxV, int curG, int maxG) { - for (; curG < maxG; curG++, curV++) { - char g = pattern.charAt(curG); - if (g == '*') { - while (true) { - if (matchesPattern(value, pattern, curV, maxV, curG + 1, maxG)) { - return true; - } - if (curV >= maxV) { - break; - } - curV++; - } - return false; - } else if (curV >= maxV) { - break; - } else if (g == '?') { - continue; - } - if (g == '\\' && curG + 1 < maxG) { - curG++; - g = pattern.charAt(curG); - } - - if (g != value.charAt(curV)) - return false; - } - return curG == maxG && curV == maxV; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITArmor.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITArmor.java deleted file mode 100644 index e919a86..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITArmor.java +++ /dev/null @@ -1,42 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack.cits; - -import net.minecraft.item.ArmorItem; -import net.minecraft.item.Item; -import net.minecraft.resource.ResourceType; -import net.minecraft.util.Identifier; -import net.minecraft.util.registry.Registry; -import shcm.shsupercm.fabric.citresewn.ex.CITParseException; -import shcm.shsupercm.fabric.citresewn.pack.CITPack; - -import java.util.*; -import java.util.function.Supplier; - -public class CITArmor extends CIT { - public final Map textures = new HashMap<>(); - - public CITArmor(CITPack pack, Identifier identifier, Properties properties) throws CITParseException { - super(pack, identifier, properties); - try { - if (this.items.size() == 0) - throw new Exception("CIT must target at least one item type"); - for (Item item : this.items) - if (!(item instanceof ArmorItem)) - throw new Exception("Armor CIT must target armor items only(" + Registry.ITEM.getId(item) + " is not armor)"); - - for (Object o : properties.keySet()) - if (o instanceof String property && property.startsWith("texture.")) { - Identifier textureIdentifier = resolvePath(identifier, properties.getProperty(property), ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (textureIdentifier == null) - throw new Exception("Cannot resolve path for " + property); - - this.textures.put(property.substring(8), textureIdentifier); - } - } catch (Exception e) { - throw new CITParseException(pack.resourcePack, identifier, (e.getClass() == Exception.class ? "" : e.getClass().getSimpleName() + ": ") + e.getMessage()); - } - } - - public interface Cached { - CITArmor citresewn_getCachedCITArmor(Supplier realtime); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITElytra.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITElytra.java deleted file mode 100644 index 5c9aa1a..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITElytra.java +++ /dev/null @@ -1,28 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack.cits; - -import net.minecraft.resource.ResourceType; -import net.minecraft.util.Identifier; -import shcm.shsupercm.fabric.citresewn.ex.CITParseException; -import shcm.shsupercm.fabric.citresewn.pack.CITPack; - -import java.util.Properties; -import java.util.function.Supplier; - -public class CITElytra extends CIT { - public final Identifier textureIdentifier; - - public CITElytra(CITPack pack, Identifier identifier, Properties properties) throws CITParseException { - super(pack, identifier, properties); - try { - textureIdentifier = resolvePath(identifier, properties.getProperty("texture"), ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (textureIdentifier == null) - throw new Exception("Cannot resolve texture"); - } catch (Exception e) { - throw new CITParseException(pack.resourcePack, identifier, (e.getClass() == Exception.class ? "" : e.getClass().getSimpleName() + ": ") + e.getMessage()); - } - } - - public interface Cached { - CITElytra citresewn_getCachedCITElytra(Supplier realtime); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITEnchantment.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITEnchantment.java deleted file mode 100644 index 7c4fa94..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITEnchantment.java +++ /dev/null @@ -1,371 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack.cits; - -import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.*; -import net.minecraft.enchantment.EnchantmentHelper; -import net.minecraft.item.EnchantedBookItem; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtElement; -import net.minecraft.resource.ResourceType; -import net.minecraft.util.Identifier; -import net.minecraft.util.Util; -import net.minecraft.util.math.Matrix4f; -import net.minecraft.util.math.Vec3f; -import org.lwjgl.opengl.GL11; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.ex.CITParseException; -import shcm.shsupercm.fabric.citresewn.mixin.citenchantment.BufferBuilderStorageAccessor; -import shcm.shsupercm.fabric.citresewn.mixin.citenchantment.RenderPhaseAccessor; -import shcm.shsupercm.fabric.citresewn.pack.CITPack; - -import java.util.*; -import java.util.function.Consumer; -import java.util.function.Supplier; - -import static org.lwjgl.opengl.GL11.*; -import static com.mojang.blaze3d.systems.RenderSystem.*; -import static shcm.shsupercm.util.logic.Loops.statelessFadingLoop; - -public class CITEnchantment extends CIT { - public static List appliedContext = null; - public static boolean shouldApply = false; - - public final Identifier textureIdentifier; - public final float speed, rotation, duration, r, g, b, a; - public final int layer; - public final boolean useGlint, blur; - public final Blend blend; - - private final WrappedMethodIntensity methodIntensity = new WrappedMethodIntensity(); - - public final Map renderLayers = new EnumMap<>(GlintRenderLayer.class); - - public CITEnchantment(CITPack pack, Identifier identifier, Properties properties) throws CITParseException { - super(pack, identifier, properties); - try { - textureIdentifier = resolvePath(identifier, properties.getProperty("texture"), ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (textureIdentifier == null) - throw new Exception("Cannot resolve texture"); - - speed = Float.parseFloat(properties.getProperty("speed", "1")); - - rotation = Float.parseFloat(properties.getProperty("rotation", "0")); - - duration = Float.max(0f, Float.parseFloat(properties.getProperty("duration", "0"))); - - layer = Integer.parseInt(properties.getProperty("layer", "0")); - - r = Math.max(0f, Float.parseFloat(properties.getProperty("r", "1"))); - g = Math.max(0f, Float.parseFloat(properties.getProperty("g", "1"))); - b = Math.max(0f, Float.parseFloat(properties.getProperty("b", "1"))); - a = Math.max(0f, Float.parseFloat(properties.getProperty("a", "1"))); - - useGlint = switch (properties.getProperty("useGlint", "false").toLowerCase(Locale.ENGLISH)) { - case "true" -> true; - case "false" -> false; - default -> throw new Exception("useGlint is not a boolean"); - }; - - blur = switch (properties.getProperty("blur", "true").toLowerCase(Locale.ENGLISH)) { - case "true" -> true; - case "false" -> false; - default -> throw new Exception("blur is not a boolean"); - }; - - blend = Blend.getBlend(properties.getProperty("blend", "add")); - } catch (Exception e) { - throw new CITParseException(pack.resourcePack, identifier, (e.getClass() == Exception.class ? "" : e.getClass().getSimpleName() + ": ") + e.getMessage()); - } - } - - public void activate() { - for (GlintRenderLayer glintLayer : GlintRenderLayer.values()) { - RenderLayer renderLayer = glintLayer.build(this); - - renderLayers.put(glintLayer, renderLayer); - ((BufferBuilderStorageAccessor) MinecraftClient.getInstance().getBufferBuilders()).entityBuilders().put(renderLayer, new BufferBuilder(renderLayer.getExpectedBufferSize())); - } - } - - @Override - public void dispose() { - appliedContext = null; - for (RenderLayer renderLayer : renderLayers.values()) - ((BufferBuilderStorageAccessor) MinecraftClient.getInstance().getBufferBuilders()).entityBuilders().remove(renderLayer); - } - - public enum GlintRenderLayer { - ARMOR_GLINT("armor_glint", 8f, layer -> layer - .shader(RenderPhaseAccessor.ARMOR_GLINT_SHADER()) - .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) - .cull(RenderPhaseAccessor.DISABLE_CULLING()) - .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST()) - .layering(RenderPhaseAccessor.VIEW_OFFSET_Z_LAYERING())), - ARMOR_ENTITY_GLINT("armor_entity_glint", 0.16f, layer -> layer - .shader(RenderPhaseAccessor.ARMOR_ENTITY_GLINT_SHADER()) - .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) - .cull(RenderPhaseAccessor.DISABLE_CULLING()) - .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST()) - .layering(RenderPhaseAccessor.VIEW_OFFSET_Z_LAYERING())), - GLINT_TRANSLUCENT("glint_translucent", 8f, layer -> layer - .shader(RenderPhaseAccessor.TRANSLUCENT_GLINT_SHADER()) - .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) - .cull(RenderPhaseAccessor.DISABLE_CULLING()) - .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST()) - .target(RenderPhaseAccessor.ITEM_TARGET())), - GLINT("glint", 8f, layer -> layer - .shader(RenderPhaseAccessor.GLINT_SHADER()) - .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) - .cull(RenderPhaseAccessor.DISABLE_CULLING()) - .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST())), - DIRECT_GLINT("glint_direct", 8f, layer -> layer - .shader(RenderPhaseAccessor.DIRECT_GLINT_SHADER()) - .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) - .cull(RenderPhaseAccessor.DISABLE_CULLING()) - .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST())), - ENTITY_GLINT("entity_glint", 0.16f, layer -> layer - .shader(RenderPhaseAccessor.ENTITY_GLINT_SHADER()) - .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) - .cull(RenderPhaseAccessor.DISABLE_CULLING()) - .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST()) - .target(RenderPhaseAccessor.ITEM_TARGET())), - DIRECT_ENTITY_GLINT("entity_glint_direct", 0.16f, layer -> layer - .shader(RenderPhaseAccessor.DIRECT_ENTITY_GLINT_SHADER()) - .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) - .cull(RenderPhaseAccessor.DISABLE_CULLING()) - .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST())); - - public final String name; - private final Consumer setup; - private final float scale; - - GlintRenderLayer(String name, float scale, Consumer setup) { - this.name = name; - this.scale = scale; - this.setup = setup; - } - - public RenderLayer build(CITEnchantment enchantment) { - final float speed = enchantment.speed, rotation = enchantment.rotation, r = enchantment.r, g = enchantment.g, b = enchantment.b, a = enchantment.a; - final WrappedMethodIntensity methodIntensity = enchantment.methodIntensity; - //noinspection ConstantConditions - RenderLayer.MultiPhaseParameters.Builder layer = RenderLayer.MultiPhaseParameters.builder() - .texture(new RenderPhase.Texture(enchantment.textureIdentifier, enchantment.blur, false)) - .texturing(new RenderPhase.Texturing("citresewn_glint_texturing", () -> { - float l = Util.getMeasuringTimeMs() * CITResewnConfig.INSTANCE().citenchantment_scroll_multiplier * speed; - float x = (l % 110000f) / 110000f; - float y = (l % 30000f) / 30000f; - Matrix4f matrix4f = Matrix4f.translate(-x, y, 0.0f); - matrix4f.multiply(Vec3f.POSITIVE_Z.getDegreesQuaternion(rotation + 10f)); - matrix4f.multiply(Matrix4f.scale(scale, scale, scale)); - setTextureMatrix(matrix4f); - - setShaderColor(r, g, b, a * methodIntensity.intensity); - }, () -> { - RenderSystem.resetTextureMatrix(); - - setShaderColor(1f, 1f, 1f, 1f); - })) - .transparency(enchantment.blend); - - this.setup.accept(layer); - - return RenderLayer.of("citresewn:enchantment_" + this.name + ":" + enchantment.propertiesIdentifier.toString(), - VertexFormats.POSITION_TEXTURE, - VertexFormat.DrawMode.QUADS, - 256, - layer.build(false)); - } - - public VertexConsumer tryApply(VertexConsumer base, RenderLayer baseLayer, VertexConsumerProvider provider) { - if (!shouldApply || appliedContext == null || appliedContext.size() == 0) - return null; - - VertexConsumer[] layers = new VertexConsumer[Math.min(appliedContext.size(), appliedContext.get(0).pack.cap)]; - - for (int i = 0; i < layers.length; i++) - layers[i] = provider.getBuffer(appliedContext.get(i).renderLayers.get(GlintRenderLayer.this)); - - provider.getBuffer(baseLayer); // refresh base layer for armor consumer - - return base == null ? VertexConsumers.union(layers) : VertexConsumers.union(VertexConsumers.union(layers), base); - } - } - - public static class Blend extends RenderPhase.Transparency { - private final int src, dst, srcAlpha, dstAlpha; - - private Blend(String name, int src, int dst, int srcAlpha, int dstAlpha) { - super(name + "_glint_transparency", null, null); - this.src = src; - this.dst = dst; - this.srcAlpha = srcAlpha; - this.dstAlpha = dstAlpha; - } - - private Blend(String name, int src, int dst) { - this(name, src, dst, GL_ZERO, GL_ONE); - } - - @Override - public void startDrawing() { - enableBlend(); - blendFuncSeparate(src, dst, srcAlpha, dstAlpha); - } - - @Override - public void endDrawing() { - defaultBlendFunc(); - disableBlend(); - } - - public static Blend getBlend(String blendString) throws BlendFormatException { - try { //check named blending function - return Named.valueOf(blendString.toUpperCase(Locale.ENGLISH)).blend; - } catch (IllegalArgumentException ignored) { // create custom blending function - try { - String[] split = blendString.split(" "); - int src, dst, srcAlpha, dstAlpha; - if (split.length == 2) { - src = parseGLConstant(split[0]); - dst = parseGLConstant(split[1]); - srcAlpha = GL_ZERO; - dstAlpha = GL_ONE; - } else if (split.length == 4) { - src = parseGLConstant(split[0]); - dst = parseGLConstant(split[1]); - srcAlpha = parseGLConstant(split[2]); - dstAlpha = parseGLConstant(split[3]); - } else - throw new Exception(); - - return new Blend("custom_" + src + "_" + dst + "_" + srcAlpha + "_" + dstAlpha, src, dst, srcAlpha, dstAlpha); - } catch (Exception e) { - throw new BlendFormatException(); - } - } - } - - private enum Named { - REPLACE(new Blend("replace", 0, 0) { - @Override - public void startDrawing() { - disableBlend(); - } - }), - GLINT(new Blend("glint", GL_SRC_COLOR, GL_ONE)), - ALPHA(new Blend("alpha", GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)), - ADD(new Blend("add", GL_SRC_ALPHA, GL_ONE)), - SUBTRACT(new Blend("subtract", GL_ONE_MINUS_DST_COLOR, GL_ZERO)), - MULTIPLY(new Blend("multiply", GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA)), - DODGE(new Blend("dodge", GL_ONE, GL_ONE)), - BURN(new Blend("burn", GL_ZERO, GL_ONE_MINUS_SRC_COLOR)), - SCREEN(new Blend("screen", GL_ONE, GL_ONE_MINUS_SRC_COLOR)), - OVERLAY(new Blend("overlay", GL_DST_COLOR, GL_SRC_COLOR)); - - public final Blend blend; - - Named(Blend blend) { - this.blend = blend; - } - } - - private static int parseGLConstant(String s) throws Exception { - try { - return GL11.class.getDeclaredField(s).getInt(null); - } catch (NoSuchFieldException ignored) { } - - return s.startsWith("0x") ? Integer.parseInt(s.substring(2), 16) : Integer.parseInt(s); - } - - public static class BlendFormatException extends Exception { - public BlendFormatException() { - super("Not a valid blending method"); - } - } - } - - public enum MergeMethod { - AVERAGE { - @Override - public void applyIntensity(Map stackEnchantments, CITEnchantment cit) { - Identifier enchantment = null; - for (Identifier enchantmentMatch : cit.enchantments) - if (stackEnchantments.containsKey(enchantmentMatch)) { - enchantment = enchantmentMatch; - break; - } - - if (enchantment == null) { - cit.methodIntensity.intensity = 0f; - } else { - float sum = 0f; - for (Integer value : stackEnchantments.values()) - sum += value; - - cit.methodIntensity.intensity = (float) stackEnchantments.get(enchantment) / sum; - } - } - }, - LAYERED { - @Override - public void applyIntensity(Map stackEnchantments, CITEnchantment cit) { - Identifier enchantment = null; - for (Identifier enchantmentMatch : cit.enchantments) - if (stackEnchantments.containsKey(enchantmentMatch)) { - enchantment = enchantmentMatch; - break; - } - if (enchantment == null) { - cit.methodIntensity.intensity = 0f; - return; - } - - float max = 0f; - for (Integer value : stackEnchantments.values()) - if (value > max) - max = value; - - cit.methodIntensity.intensity = (float) stackEnchantments.get(enchantment) / max; - } - }, - CYCLE { - @Override - public void applyMethod(List citEnchantments, ItemStack stack) { - List> durations = new ArrayList<>(); - for (CITEnchantment cit : citEnchantments) - durations.add(new HashMap.SimpleEntry<>(cit, cit.duration)); - - for (Map.Entry intensity : statelessFadingLoop(durations, citEnchantments.get(0).pack.fade, ticks, 20).entrySet()) - intensity.getKey().methodIntensity.intensity = intensity.getValue(); - } - }; - - public static int ticks = 0; - - public void applyIntensity(Map stackEnchantments, CITEnchantment cit) { - cit.methodIntensity.intensity = 1f; - } - - public void applyMethod(List citEnchantments, ItemStack stack) { - Map stackEnchantments = new LinkedHashMap<>(); - for (NbtElement nbtElement : stack.isOf(Items.ENCHANTED_BOOK) ? EnchantedBookItem.getEnchantmentNbt(stack) : stack.getEnchantments()) - stackEnchantments.put(EnchantmentHelper.getIdFromNbt((NbtCompound) nbtElement), EnchantmentHelper.getLevelFromNbt((NbtCompound) nbtElement)); - - for (CITEnchantment cit : citEnchantments) - if (!cit.enchantmentsAny) - applyIntensity(stackEnchantments, cit); - } - } - - private static class WrappedMethodIntensity { - public float intensity = 1f; - } - - public interface Cached { - List citresewn_getCachedCITEnchantment(Supplier> realtime); - } -} \ No newline at end of file diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITItem.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITItem.java deleted file mode 100644 index 2300f88..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cits/CITItem.java +++ /dev/null @@ -1,463 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack.cits; - -import com.google.common.collect.ImmutableMap; -import com.mojang.datafixers.util.Either; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import net.minecraft.client.render.model.BakedModel; -import net.minecraft.client.render.model.json.JsonUnbakedModel; -import net.minecraft.client.render.model.json.ModelOverride; -import net.minecraft.client.render.model.json.ModelOverrideList; -import net.minecraft.client.render.model.json.ModelTransformation; -import net.minecraft.client.texture.SpriteAtlasTexture; -import net.minecraft.client.util.SpriteIdentifier; -import net.minecraft.client.world.ClientWorld; -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.resource.Resource; -import net.minecraft.resource.ResourceManager; -import net.minecraft.resource.ResourceType; -import net.minecraft.util.Identifier; -import net.minecraft.util.registry.Registry; -import org.apache.commons.io.IOUtils; -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.ex.CITLoadException; -import shcm.shsupercm.fabric.citresewn.ex.CITParseException; -import shcm.shsupercm.fabric.citresewn.mixin.cititem.JsonUnbakedModelAccessor; -import shcm.shsupercm.fabric.citresewn.pack.CITPack; -import shcm.shsupercm.fabric.citresewn.pack.ResewnItemModelIdentifier; -import shcm.shsupercm.fabric.citresewn.pack.ResewnTextureIdentifier; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -@SuppressWarnings("deprecation") -public class CITItem extends CIT { - private static final String GENERATED_SUB_CITS_PREFIX = "sub_cititem_generated_"; - public static final Set GENERATED_SUB_CITS_SEEN = new HashSet<>(); - - public Map assetIdentifiers = new LinkedHashMap<>(); - public Map, JsonUnbakedModel> unbakedAssets = new LinkedHashMap<>(); - private Map> textureOverrideMap = new HashMap<>(); - private boolean isTexture = false; - - public BakedModel bakedModel = null; - public CITOverrideList bakedSubModels = new CITOverrideList(); - - public CITItem(CITPack pack, Identifier identifier, Properties properties) throws CITParseException { - super(pack, identifier, properties); - try { - if (this.items.size() == 0) - throw new Exception("CIT must target at least one item type"); - - Identifier assetIdentifier; - boolean containsTexture = false; - String modelProp = properties.getProperty("model"); - if (modelProp == null) - for (Object o : properties.keySet()) - if (o instanceof String property && (property.startsWith("texture") || property.startsWith("tile"))) { - containsTexture = true; - break; - } - if (!containsTexture) { - assetIdentifier = resolvePath(identifier, modelProp, ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (assetIdentifier != null) - assetIdentifiers.put(null, assetIdentifier); - else if (modelProp != null) { - assetIdentifier = resolvePath(identifier, modelProp, ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (assetIdentifier != null) - assetIdentifiers.put(null, assetIdentifier); - } - } - - for (Object o : properties.keySet()) - if (o instanceof String property && property.startsWith("model.")) { - Identifier subIdentifier = resolvePath(identifier, properties.getProperty(property), ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (subIdentifier == null) - throw new Exception("Cannot resolve path for " + property); - - String subItem = property.substring(6); - Identifier subItemIdentifier = fixDeprecatedSubItem(subItem); - assetIdentifiers.put(subItemIdentifier == null ? new Identifier("minecraft", "item/" + subItem) : subItemIdentifier, subIdentifier); - } - - if (assetIdentifiers.size() == 0) { // attempt to load texture - isTexture = true; - String textureProp = properties.getProperty("texture"); - if (textureProp == null) - textureProp = properties.getProperty("tile"); - assetIdentifier = resolvePath(identifier, textureProp, ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (assetIdentifier != null) - assetIdentifiers.put(null, assetIdentifier); - - for (Object o : properties.keySet()) - if (o instanceof String property && property.startsWith("texture.")) { - Identifier subIdentifier = resolvePath(identifier, properties.getProperty(property), ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (subIdentifier == null) - throw new Exception("Cannot resolve path for " + property); - - String subItem = property.substring(8); - Identifier subItemIdentifier = fixDeprecatedSubItem(subItem); - assetIdentifiers.put(subItemIdentifier == null ? new Identifier("minecraft", "item/" + subItem) : subItemIdentifier, subIdentifier); - } - } else { // attempt to load textureOverrideMap from textures - String textureProp = properties.getProperty("texture"); - if (textureProp == null) - textureProp = properties.getProperty("tile"); - if (textureProp != null) { - assetIdentifier = resolvePath(identifier, textureProp, ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (assetIdentifier != null) - textureOverrideMap.put(null, Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(assetIdentifier)))); - else - throw new Exception("Cannot resolve path for texture"); - } - - for (Object o : properties.keySet()) - if (o instanceof String property && property.startsWith("texture.")) { - textureProp = properties.getProperty(property); - Identifier subIdentifier = resolvePath(identifier, textureProp, ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (subIdentifier == null) - throw new Exception("Cannot resolve path for " + property); - - textureOverrideMap.put(property.substring(8), Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(subIdentifier)))); - } - } - - if (assetIdentifiers.size() == 0) - throw new Exception("Cannot resolve path for model/texture"); - } catch (Exception e) { - throw new CITParseException(pack.resourcePack, identifier, (e.getClass() == Exception.class ? "" : e.getClass().getSimpleName() + ": ") + e.getMessage()); - } - } - - public void loadUnbakedAssets(ResourceManager resourceManager) throws CITLoadException { - try { - if (isTexture) { - JsonUnbakedModel itemJson = getModelForFirstItemType(resourceManager); - if (((JsonUnbakedModelAccessor) itemJson).getTextureMap().size() > 1) { // use(some/all of) the asset identifiers to build texture override in layered models - textureOverrideMap = ((JsonUnbakedModelAccessor) itemJson).getTextureMap(); - Identifier defaultAsset = assetIdentifiers.get(null); - textureOverrideMap.replaceAll((layerName, originalTextureEither) -> { - Identifier textureIdentifier = assetIdentifiers.remove(originalTextureEither.map(SpriteIdentifier::getTextureId, Identifier::new)); - if (textureIdentifier != null) - return Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(textureIdentifier))); - if (defaultAsset != null) - return Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(defaultAsset))); - return null; - }); - - if (assetIdentifiers.size() == 0 || (assetIdentifiers.size() == 1 && assetIdentifiers.containsKey(null))) { - unbakedAssets.put(null, itemJson); - return; - } - } - - Identifier baseIdentifier = assetIdentifiers.remove(null); - - if (baseIdentifier != null) - unbakedAssets.put(null, loadUnbakedAsset(resourceManager, baseIdentifier)); - - if (!assetIdentifiers.isEmpty()) { // contains sub models - LinkedHashMap> overrideConditions = new LinkedHashMap<>(); - for (Item item : this.items) { - Identifier itemIdentifier = Registry.ITEM.getId(item); - overrideConditions.put(new Identifier(itemIdentifier.getNamespace(), "item/" + itemIdentifier.getPath()), Collections.emptyList()); - - Identifier itemModelIdentifier = new Identifier(itemIdentifier.getNamespace(), "models/item/" + itemIdentifier.getPath() + ".json"); - try (Resource itemModelResource = resourceManager.getResource(itemModelIdentifier); Reader resourceReader = new InputStreamReader(itemModelResource.getInputStream())) { - JsonUnbakedModel itemModelJson = JsonUnbakedModel.deserialize(resourceReader); - - if (itemModelJson.getOverrides() != null && !itemModelJson.getOverrides().isEmpty()) - for (ModelOverride override : itemModelJson.getOverrides()) - overrideConditions.put(override.getModelId(), override.streamConditions().toList()); - } - } - - ArrayList overrideModels = new ArrayList<>(overrideConditions.keySet()); - Collections.reverse(overrideModels); - - for (Identifier overrideModel : overrideModels) { - Identifier replacement = assetIdentifiers.remove(overrideModel); - if (replacement == null) - continue; - - List conditions = overrideConditions.get(overrideModel); - unbakedAssets.put(conditions, loadUnbakedAsset(resourceManager, replacement)); - } - } - } else { // isModel - Identifier baseIdentifier = assetIdentifiers.remove(null); - - if (baseIdentifier != null) { - if (!GENERATED_SUB_CITS_SEEN.add(baseIdentifier)) // cit generated duplicate - baseIdentifier = new Identifier(baseIdentifier.getNamespace(), GENERATED_SUB_CITS_PREFIX + GENERATED_SUB_CITS_SEEN.size() + "_" + baseIdentifier.getPath()); - GENERATED_SUB_CITS_SEEN.add(baseIdentifier); - - JsonUnbakedModel model = loadUnbakedAsset(resourceManager, baseIdentifier); - unbakedAssets.put(null, model); - - if (model.getOverrides().size() > 0 && textureOverrideMap.size() > 0) { - LinkedHashMap> overrideConditions = new LinkedHashMap<>(); - - for (ModelOverride override : model.getOverrides()) - overrideConditions.put(override.getModelId(), override.streamConditions().toList()); - - ArrayList overrideModels = new ArrayList<>(overrideConditions.keySet()); - Collections.reverse(overrideModels); - - for (Identifier overrideModel : overrideModels) { - Identifier replacement = resolvePath(baseIdentifier, overrideModel.toString(), ".json", resourceManager::containsResource); - if (replacement != null) { - String subTexturePath = replacement.toString().substring(0, replacement.toString().lastIndexOf('.')); - final String subTextureName = subTexturePath.substring(subTexturePath.lastIndexOf('/') + 1); - - replacement = baseIdentifier; - if (!GENERATED_SUB_CITS_SEEN.add(replacement)) // cit generated duplicate - replacement = new Identifier(replacement.getNamespace(), GENERATED_SUB_CITS_PREFIX + GENERATED_SUB_CITS_SEEN.size() + "_" + replacement.getPath()); - GENERATED_SUB_CITS_SEEN.add(replacement); - - JsonUnbakedModel jsonModel = loadUnbakedAsset(resourceManager, replacement); - jsonModel.getOverrides().clear(); - - ((JsonUnbakedModelAccessor) jsonModel).getTextureMap().replaceAll((layerName, texture) -> { - if (layerName != null) - try { - for (String subTexture : textureOverrideMap.keySet()) - if (subTextureName.equals(subTexture)) - return textureOverrideMap.get(subTexture); - } catch (Exception ignored) { } - return texture; - }); - - unbakedAssets.put(overrideConditions.get(overrideModel), jsonModel); - } - } - } - } - - if (!assetIdentifiers.isEmpty()) { // contains sub models - LinkedHashMap> overrideConditions = new LinkedHashMap<>(); - for (Item item : this.items) { - Identifier itemIdentifier = Registry.ITEM.getId(item); - overrideConditions.put(new Identifier(itemIdentifier.getNamespace(), "item/" + itemIdentifier.getPath()), Collections.emptyList()); - - Identifier itemModelIdentifier = new Identifier(itemIdentifier.getNamespace(), "models/item/" + itemIdentifier.getPath() + ".json"); - try (Resource itemModelResource = resourceManager.getResource(itemModelIdentifier); Reader resourceReader = new InputStreamReader(itemModelResource.getInputStream())) { - JsonUnbakedModel itemModelJson = JsonUnbakedModel.deserialize(resourceReader); - - if (itemModelJson.getOverrides() != null && !itemModelJson.getOverrides().isEmpty()) - for (ModelOverride override : itemModelJson.getOverrides()) - overrideConditions.put(override.getModelId(), override.streamConditions().toList()); - } - } - - ArrayList overrideModels = new ArrayList<>(overrideConditions.keySet()); - Collections.reverse(overrideModels); - - for (Identifier overrideModel : overrideModels) { - Identifier replacement = assetIdentifiers.remove(overrideModel); - if (replacement == null) - continue; - - if (!GENERATED_SUB_CITS_SEEN.add(replacement)) // cit generated duplicate - replacement = new Identifier(replacement.getNamespace(), GENERATED_SUB_CITS_PREFIX + GENERATED_SUB_CITS_SEEN.size() + "_" + replacement.getPath()); - GENERATED_SUB_CITS_SEEN.add(replacement); - - List conditions = overrideConditions.get(overrideModel); - unbakedAssets.put(conditions, loadUnbakedAsset(resourceManager, replacement)); - } - } - } - } catch (Exception e) { - throw new CITLoadException(pack.resourcePack, propertiesIdentifier, (e.getClass() == Exception.class ? "" : e.getClass().getSimpleName() + ": ") + e.getMessage()); - } finally { - assetIdentifiers = null; - textureOverrideMap = null; - } - } - - private JsonUnbakedModel loadUnbakedAsset(ResourceManager resourceManager, Identifier assetIdentifier) throws Exception { - final Identifier identifier; - { - Identifier possibleIdentifier = assetIdentifier; - while (possibleIdentifier.getPath().startsWith(GENERATED_SUB_CITS_PREFIX)) - possibleIdentifier = new Identifier(possibleIdentifier.getNamespace(), possibleIdentifier.getPath().substring(possibleIdentifier.getPath().substring(GENERATED_SUB_CITS_PREFIX.length()).indexOf('_') + GENERATED_SUB_CITS_PREFIX.length() + 1)); - identifier = possibleIdentifier; - } - JsonUnbakedModel json; - if (identifier.getPath().endsWith(".json")) { - InputStream is = null; - Resource resource = null; - try { - json = JsonUnbakedModel.deserialize(IOUtils.toString(is = (resource = resourceManager.getResource(identifier)).getInputStream(), StandardCharsets.UTF_8)); - json.id = assetIdentifier.toString(); - json.id = json.id.substring(0, json.id.length() - 5); - - ((JsonUnbakedModelAccessor) json).getTextureMap().replaceAll((layer, original) -> { - Optional left = original.left(); - if (left.isPresent()) { - Identifier resolvedIdentifier = resolvePath(identifier, left.get().getTextureId().getPath(), ".png", resourceManager::containsResource); - if (resolvedIdentifier != null) - return Either.left(new SpriteIdentifier(left.get().getAtlasId(), new ResewnTextureIdentifier(resolvedIdentifier))); - } - return original; - }); - - if (textureOverrideMap.size() > 0) { - Map> jsonTextureMap = ((JsonUnbakedModelAccessor) json).getTextureMap(); - if (jsonTextureMap.size() == 0) - jsonTextureMap.put("layer0", null); - - final Either defaultTextureOverride = textureOverrideMap.get(null); - if (defaultTextureOverride != null) - jsonTextureMap.replaceAll((layerName, spriteIdentifierStringEither) -> defaultTextureOverride); - - //jsonTextureMap.putAll(textureOverrideMap); - jsonTextureMap.replaceAll((layerName, texture) -> { - if (layerName != null) - try { - String[] split = texture.map(id -> id.getTextureId().getPath(), s -> s).split("/"); - String textureName = split[split.length - 1]; - if (textureName.endsWith(".png")) - textureName = textureName.substring(0, textureName.length() - 4); - return Objects.requireNonNull(textureOverrideMap.get(textureName)); - } catch (Exception ignored) { } - return texture; - }); - jsonTextureMap.values().removeIf(Objects::isNull); - } - - Identifier parentId = ((JsonUnbakedModelAccessor) json).getParentId(); - if (parentId != null) { - String[] parentIdPathSplit = parentId.getPath().split("/"); - if (parentId.getPath().startsWith("./") || (parentIdPathSplit.length > 2 && parentIdPathSplit[1].equals("cit"))) { - parentId = resolvePath(identifier, parentId.getPath(), ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (parentId != null) - ((JsonUnbakedModelAccessor) json).setParentId(new ResewnItemModelIdentifier(parentId)); - } - } - - json.getOverrides().replaceAll(override -> { - String[] modelIdPathSplit = override.getModelId().getPath().split("/"); - if (override.getModelId().getPath().startsWith("./") || (modelIdPathSplit.length > 2 && modelIdPathSplit[1].equals("cit"))) { - Identifier resolvedOverridePath = resolvePath(identifier, override.getModelId().getPath(), ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); - if (resolvedOverridePath != null) - return new ModelOverride(new ResewnItemModelIdentifier(resolvedOverridePath), override.streamConditions().collect(Collectors.toList())); - } - - return override; - }); - - return json; - } finally { - IOUtils.closeQuietly(is, resource); - } - } else if (identifier.getPath().endsWith(".png")) { - json = getModelForFirstItemType(resourceManager); - if (json == null) - json = new JsonUnbakedModel(new Identifier("minecraft", "item/generated"), new ArrayList<>(), ImmutableMap.of("layer0", Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(identifier)))), true, JsonUnbakedModel.GuiLight.ITEM, ModelTransformation.NONE, new ArrayList<>()); - json.getOverrides().clear(); - json.id = identifier.toString(); - json.id = json.id.substring(0, json.id.length() - 4); - - ((JsonUnbakedModelAccessor) json).getTextureMap().replaceAll((layerName, originalTextureEither) -> { - if (textureOverrideMap.size() > 0) { - Either textureOverride = textureOverrideMap.get(layerName); - if (textureOverride == null) - textureOverride = textureOverrideMap.get(null); - return textureOverride == null ? originalTextureEither : textureOverride; - } else - return Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(identifier))); - }); - return json; - } - - throw new Exception("Unknown asset type"); - } - - public Identifier fixDeprecatedSubItem(String subItem) { - String replacement = switch (subItem) { - case "bow_pulling_standby" -> "bow"; - case "crossbow_standby" -> "crossbow"; - case "potion_bottle_drinkable" -> "potion"; - case "potion_bottle_splash" -> "splash_potion"; - case "potion_bottle_lingering" -> "lingering_potion"; - - - default -> null; - }; - - if (replacement != null) { - CITResewn.logWarnLoading("CIT Warning: Using deprecated sub item id \"" + subItem + "\" instead of \"" + replacement + "\" in " + pack.resourcePack.getName() + " -> " + propertiesIdentifier.toString()); - - return new Identifier("minecraft", "item/" + replacement); - } - - return null; - } - - private JsonUnbakedModel getModelForFirstItemType(ResourceManager resourceManager) { - Identifier firstItemIdentifier = Registry.ITEM.getId(this.items.iterator().next()), firstItemModelIdentifier = new Identifier(firstItemIdentifier.getNamespace(), "models/item/" + firstItemIdentifier.getPath() + ".json"); - Resource itemModelResource = null; - try { - JsonUnbakedModel json = JsonUnbakedModel.deserialize(IOUtils.toString((itemModelResource = resourceManager.getResource(firstItemModelIdentifier)).getInputStream(), StandardCharsets.UTF_8)); - - if (!GENERATED_SUB_CITS_SEEN.add(firstItemModelIdentifier)) // cit generated duplicate - firstItemModelIdentifier = new Identifier(firstItemModelIdentifier.getNamespace(), GENERATED_SUB_CITS_PREFIX + GENERATED_SUB_CITS_SEEN.size() + "_" + firstItemModelIdentifier.getPath()); - GENERATED_SUB_CITS_SEEN.add(firstItemModelIdentifier); - - json.id = firstItemModelIdentifier.toString(); - json.id = json.id.substring(0, json.id.length() - 5); - return json; - } catch (Exception e) { - return null; - } finally { - IOUtils.closeQuietly(itemModelResource); - } - } - - public BakedModel getItemModel(ItemStack stack, ClientWorld world, LivingEntity entity, int seed) { - // get sub items or bakedModel if no sub item matches @Nullable - BakedModel bakedModel = bakedSubModels.apply(this.bakedModel, stack, world, entity, seed); - - // apply model overrides - if (bakedModel != null && bakedModel.getOverrides() != null) - bakedModel = bakedModel.getOverrides().apply(bakedModel, stack, world, entity, seed); - - return bakedModel; - } - - public static class CITOverrideList extends ModelOverrideList { - public void override(List key, BakedModel bakedModel) { - Set conditionTypes = new LinkedHashSet<>(Arrays.asList(this.conditionTypes)); - for (ModelOverride.Condition condition : key) - conditionTypes.add(condition.getType()); - this.conditionTypes = conditionTypes.toArray(new Identifier[0]); - - this.overrides = Arrays.copyOf(this.overrides, this.overrides.length + 1); - - Object2IntMap object2IntMap = new Object2IntOpenHashMap<>(); - for(int i = 0; i < this.conditionTypes.length; ++i) - object2IntMap.put(this.conditionTypes[i], i); - - this.overrides[this.overrides.length - 1] = new BakedOverride( - key.stream() - .map((condition) -> new InlinedCondition(object2IntMap.getInt(condition.getType()), condition.getThreshold())) - .toArray(InlinedCondition[]::new) - , bakedModel); - } - } - - public interface Cached { - CITItem citresewn_getCachedCITItem(Supplier realtime); - - boolean citresewn_isMojankCIT(); - void citresewn_setMojankCIT(boolean mojankCIT); - } -} -- cgit From c48e23a8949eaa89d06908201357b53fa7eaedbe Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 21 Jan 2022 15:50:24 +0200 Subject: Added config/screen for defaults --- .../defaults/config/CITResewnDefaultsConfig.java | 49 ++++++++++++++++++ .../CITResewnDefaultsConfigScreenFactory.java | 27 ++++++++++ .../defaults/config/CITResewnDefaultsModMenu.java | 25 +++++++++ .../main/java/shcm/shsupercm/util/logic/Loops.java | 60 ++++++++++++++++++++++ .../assets/citresewn-defaults/lang/en_us.json | 4 ++ defaults/src/main/resources/fabric.mod.json | 8 ++- .../config/CITResewnConfigScreenFactory.java | 21 +++++++- .../fabric/citresewn/config/CITResewnModMenu.java | 9 +--- src/main/java/shcm/shsupercm/util/logic/Loops.java | 60 ---------------------- .../resources/assets/citresewn/lang/en_us.json | 4 +- 10 files changed, 194 insertions(+), 73 deletions(-) create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfig.java create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsModMenu.java create mode 100644 defaults/src/main/java/shcm/shsupercm/util/logic/Loops.java create mode 100644 defaults/src/main/resources/assets/citresewn-defaults/lang/en_us.json delete mode 100644 src/main/java/shcm/shsupercm/util/logic/Loops.java (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfig.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfig.java new file mode 100644 index 0000000..0787fba --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfig.java @@ -0,0 +1,49 @@ +package shcm.shsupercm.fabric.citresewn.defaults.config; + +import com.google.gson.Gson; +import com.google.gson.stream.JsonWriter; +import org.apache.commons.io.IOUtils; +import shcm.shsupercm.fabric.citresewn.CITResewn; + +import java.io.*; + +public class CITResewnDefaultsConfig { + + + private static final File FILE = new File("config/citresewn-defaults.json"); + + public static final CITResewnDefaultsConfig INSTANCE = read(); + + public static CITResewnDefaultsConfig read() { + if (!FILE.exists()) + return new CITResewnDefaultsConfig().write(); + + Reader reader = null; + try { + return new Gson().fromJson(reader = new FileReader(FILE), CITResewnDefaultsConfig.class); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } finally { + IOUtils.closeQuietly(reader); + } + } + + public CITResewnDefaultsConfig write() { + Gson gson = new Gson(); + JsonWriter writer = null; + try { + writer = gson.newJsonWriter(new FileWriter(FILE)); + writer.setIndent(" "); + + gson.toJson(gson.toJsonTree(this, CITResewnDefaultsConfig.class), writer); + } catch (Exception e) { + CITResewn.LOG.error("Couldn't save defaults config"); + e.printStackTrace(); + throw new RuntimeException(e); + } finally { + IOUtils.closeQuietly(writer); + } + return this; + } +} diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java new file mode 100644 index 0000000..889c465 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java @@ -0,0 +1,27 @@ +package shcm.shsupercm.fabric.citresewn.defaults.config; + +import me.shedaniel.clothconfig2.api.ConfigBuilder; +import me.shedaniel.clothconfig2.api.ConfigCategory; +import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.text.LiteralText; +import net.minecraft.text.TranslatableText; + +public class CITResewnDefaultsConfigScreenFactory { + public static Screen create(Screen parent) { + CITResewnDefaultsConfig currentConfig = CITResewnDefaultsConfig.INSTANCE, defaultConfig = new CITResewnDefaultsConfig(); + + ConfigBuilder builder = ConfigBuilder.create() + .setParentScreen(parent) + .setTitle(new TranslatableText("config.citresewn.defaults.title")) + .setSavingRunnable(currentConfig::write); + + ConfigCategory category = builder.getOrCreateCategory(new LiteralText("")); + ConfigEntryBuilder entryBuilder = builder.entryBuilder(); + + + + return builder.build(); + } +} diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsModMenu.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsModMenu.java new file mode 100644 index 0000000..cba1592 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsModMenu.java @@ -0,0 +1,25 @@ +package shcm.shsupercm.fabric.citresewn.defaults.config; + +import com.terraformersmc.modmenu.api.ConfigScreenFactory; +import com.terraformersmc.modmenu.api.ModMenuApi; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.screen.NoticeScreen; +import net.minecraft.text.Text; + +public class CITResewnDefaultsModMenu implements ModMenuApi { + @Override + public ConfigScreenFactory getModConfigScreenFactory() { + if (FabricLoader.getInstance().isModLoaded("cloth-config2")) + return new ClothConfigOpenImpl().getModConfigScreenFactory(); + + return parent -> new NoticeScreen(() -> MinecraftClient.getInstance().setScreen(parent), Text.of("CIT Resewn: Defaults"), Text.of("CIT Resewn requires Cloth Config to be able to show the config.")); + } + + private static class ClothConfigOpenImpl implements ModMenuApi { + @Override + public ConfigScreenFactory getModConfigScreenFactory() { + return CITResewnDefaultsConfigScreenFactory::create; + } + } +} diff --git a/defaults/src/main/java/shcm/shsupercm/util/logic/Loops.java b/defaults/src/main/java/shcm/shsupercm/util/logic/Loops.java new file mode 100644 index 0000000..6c18244 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/util/logic/Loops.java @@ -0,0 +1,60 @@ +package shcm.shsupercm.util.logic; + +import java.util.*; + +/** + * This class(or class portion) is a part of SHCM's utilities. Feel free to use without credit. + */ +public class Loops { + /** + * Creates a loop of T with linked intensities allowing for fading between the elements. + * @param items list of items and pause durations(in time units) ordered as they are in the loop + * @param fade time in units to fade between each item + * @param ticks positive raising counter + * @param tpu the amount of ticks per time unit + * @param element type + * @return map of elements and their respective intensities(between 0.0f and 1.0f) + */ + public static Map statelessFadingLoop(List> items, float fade, int ticks, int tpu) { + Map itemValues = new HashMap<>(); + + if (items == null || items.size() == 0) + return itemValues; + + if (items.size() == 1) { + itemValues.put(items.get(0).getKey(), 1f); + return itemValues; + } + + float totalUnitsInLoop = 0f; + for (Map.Entry item : items) { + itemValues.put(item.getKey(), 0f); + totalUnitsInLoop += item.getValue() + fade; + } + + float unitInLoop = (ticks % (tpu * totalUnitsInLoop)) / tpu; + + for (int i = 0; i < items.size(); i++) { + Map.Entry item = items.get(i); + if (unitInLoop < item.getValue()) { + itemValues.put(item.getKey(), 1f); + break; + } else + unitInLoop -= item.getValue(); + + if (unitInLoop < fade) { + Map.Entry nextItem = items.get(i + 1 >= items.size() ? 0 : i + 1); + + unitInLoop /= fade; + + itemValues.put(item.getKey(), 1f - unitInLoop); + itemValues.put(nextItem.getKey(), unitInLoop); + + break; + } else + unitInLoop -= fade; + } + + return itemValues; + } +} \ No newline at end of file diff --git a/defaults/src/main/resources/assets/citresewn-defaults/lang/en_us.json b/defaults/src/main/resources/assets/citresewn-defaults/lang/en_us.json new file mode 100644 index 0000000..72784ed --- /dev/null +++ b/defaults/src/main/resources/assets/citresewn-defaults/lang/en_us.json @@ -0,0 +1,4 @@ +{ + "config.citresewn.defaults.title": "CIT Resewn: Defaults", + "config.citresewn.defaults.tooltip": "Go to the defaults' config menu" +} \ No newline at end of file diff --git a/defaults/src/main/resources/fabric.mod.json b/defaults/src/main/resources/fabric.mod.json index 004b7a8..0f8e566 100644 --- a/defaults/src/main/resources/fabric.mod.json +++ b/defaults/src/main/resources/fabric.mod.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "id": "citresewn-defaults", "version": "${version}", - "name": "CIT Resewn - Defaults", + "name": "CIT Resewn: Defaults", "description": "Default types and conditions for CIT Resewn", "authors": [ "SHsuperCM" @@ -12,6 +12,12 @@ "environment": "client", "entrypoints": { + "modmenu": [ + "shcm.shsupercm.fabric.citresewn.defaults.config.CITResewnDefaultsModMenu" + ], + "citresewn-defaults:config_screen": [ + "shcm.shsupercm.fabric.citresewn.defaults.config.CITResewnDefaultsConfigScreenFactory::create" + ] }, "accessWidener" : "citresewn-defaults.accesswidener", "mixins": [ diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java index 33f4950..57ae2c3 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java @@ -3,12 +3,16 @@ package shcm.shsupercm.fabric.citresewn.config; import me.shedaniel.clothconfig2.api.ConfigBuilder; import me.shedaniel.clothconfig2.api.ConfigCategory; import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.entrypoint.EntrypointContainer; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.text.LiteralText; import net.minecraft.text.TranslatableText; import net.minecraft.util.Formatting; +import java.util.function.Function; + public class CITResewnConfigScreenFactory { public static Screen create(Screen parent) { CITResewnConfig currentConfig = CITResewnConfig.INSTANCE, defaultConfig = new CITResewnConfig(); @@ -32,6 +36,21 @@ public class CITResewnConfigScreenFactory { .setDefaultValue(defaultConfig.enabled) .build()); + class CurrentScreen { Screen screen; boolean prevToggle = false; } final CurrentScreen currentScreen = new CurrentScreen(); + category.addEntry(entryBuilder.startBooleanToggle(new TranslatableText("config.citresewn.defaults.title"), false) + .setTooltip(new TranslatableText("config.citresewn.defaults.tooltip")) + .setYesNoTextSupplier((b) -> { + if (b != currentScreen.prevToggle) { + //noinspection unchecked + MinecraftClient.getInstance().setScreen((Screen) FabricLoader.getInstance().getEntrypoints("citresewn-defaults:config_screen", Function.class).stream().findAny().orElseThrow().apply(currentScreen.screen)); + + currentScreen.prevToggle = b; + } + + return new TranslatableText("config.citresewn.configure"); + }) + .build()); + category.addEntry(entryBuilder.startBooleanToggle(new TranslatableText("config.citresewn.mute_errors.title"), currentConfig.mute_errors) .setTooltip(new TranslatableText("config.citresewn.mute_errors.tooltip")) .setSaveConsumer(newConfig -> currentConfig.mute_errors = newConfig) @@ -70,6 +89,6 @@ public class CITResewnConfigScreenFactory { .requireRestart() .build()); - return builder.build(); + return currentScreen.screen = builder.build(); } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java index cf6d9bd..378350a 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java @@ -11,15 +11,8 @@ public class CITResewnModMenu implements ModMenuApi { @Override public ConfigScreenFactory getModConfigScreenFactory() { if (FabricLoader.getInstance().isModLoaded("cloth-config2")) - return new ClothConfigOpenImpl().getModConfigScreenFactory(); + return CITResewnConfigScreenFactory::create; return parent -> new NoticeScreen(() -> MinecraftClient.getInstance().setScreen(parent), Text.of("CIT Resewn"), Text.of("CIT Resewn requires Cloth Config to be able to show the config.")); } - - private static class ClothConfigOpenImpl implements ModMenuApi { - @Override - public ConfigScreenFactory getModConfigScreenFactory() { - return CITResewnConfigScreenFactory::create; - } - } } diff --git a/src/main/java/shcm/shsupercm/util/logic/Loops.java b/src/main/java/shcm/shsupercm/util/logic/Loops.java deleted file mode 100644 index 6c18244..0000000 --- a/src/main/java/shcm/shsupercm/util/logic/Loops.java +++ /dev/null @@ -1,60 +0,0 @@ -package shcm.shsupercm.util.logic; - -import java.util.*; - -/** - * This class(or class portion) is a part of SHCM's utilities. Feel free to use without credit. - */ -public class Loops { - /** - * Creates a loop of T with linked intensities allowing for fading between the elements. - * @param items list of items and pause durations(in time units) ordered as they are in the loop - * @param fade time in units to fade between each item - * @param ticks positive raising counter - * @param tpu the amount of ticks per time unit - * @param element type - * @return map of elements and their respective intensities(between 0.0f and 1.0f) - */ - public static Map statelessFadingLoop(List> items, float fade, int ticks, int tpu) { - Map itemValues = new HashMap<>(); - - if (items == null || items.size() == 0) - return itemValues; - - if (items.size() == 1) { - itemValues.put(items.get(0).getKey(), 1f); - return itemValues; - } - - float totalUnitsInLoop = 0f; - for (Map.Entry item : items) { - itemValues.put(item.getKey(), 0f); - totalUnitsInLoop += item.getValue() + fade; - } - - float unitInLoop = (ticks % (tpu * totalUnitsInLoop)) / tpu; - - for (int i = 0; i < items.size(); i++) { - Map.Entry item = items.get(i); - if (unitInLoop < item.getValue()) { - itemValues.put(item.getKey(), 1f); - break; - } else - unitInLoop -= item.getValue(); - - if (unitInLoop < fade) { - Map.Entry nextItem = items.get(i + 1 >= items.size() ? 0 : i + 1); - - unitInLoop /= fade; - - itemValues.put(item.getKey(), 1f - unitInLoop); - itemValues.put(nextItem.getKey(), unitInLoop); - - break; - } else - unitInLoop -= fade; - } - - return itemValues; - } -} \ No newline at end of file diff --git a/src/main/resources/assets/citresewn/lang/en_us.json b/src/main/resources/assets/citresewn/lang/en_us.json index 2f90a92..3164cb5 100644 --- a/src/main/resources/assets/citresewn/lang/en_us.json +++ b/src/main/resources/assets/citresewn/lang/en_us.json @@ -1,5 +1,6 @@ { "config.citresewn.title": "CIT Resewn Configuration", + "config.citresewn.configure": "Configure", "config.citresewn.enabled.title": "Enabled", "config.citresewn.enabled.tooltip": "Should CIT Resewn load and inject cits from resourcepacks", @@ -10,9 +11,6 @@ "config.citresewn.mute_warns.title": "Mute loading warnings", "config.citresewn.mute_warns.tooltip": "Should CIT Resewn not log cit warnings", - "config.citresewn.citenchantment_scroll_multiplier.title": "CIT Enchantment: Scroll Multiplier", - "config.citresewn.citenchantment_scroll_multiplier.tooltip": "General multiplier for the scroll speed of the glint textures added by enchantment CITs.", - "config.citresewn.broken_paths.title": "Allow broken paths in resourcepacks", "config.citresewn.broken_paths.tooltip": "Allows packs with illegal resource paths to load.\nMay cause issues!", -- cgit From ffd25dce4e101c478e13867ebb5995f07cd68039 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 22 Jan 2022 10:30:00 +0200 Subject: Implemented custom properties parser --- .../shcm/shsupercm/fabric/citresewn/CITResewn.java | 3 - .../citresewn/format/PropertiesGroupAdapter.java | 103 +++++++++++++++++++++ .../fabric/citresewn/format/PropertyGroup.java | 52 +++++++++++ .../fabric/citresewn/format/PropertyKey.java | 14 +++ .../fabric/citresewn/format/PropertyValue.java | 17 ++++ 5 files changed, 186 insertions(+), 3 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyKey.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java index 4ebfff8..0a0051f 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java @@ -1,13 +1,10 @@ package shcm.shsupercm.fabric.citresewn; import net.fabricmc.api.ClientModInitializer; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -@Environment(EnvType.CLIENT) public class CITResewn implements ClientModInitializer { public static final Logger LOG = LogManager.getLogger("CITResewn"); public static CITResewn INSTANCE; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java new file mode 100644 index 0000000..c3d91ec --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java @@ -0,0 +1,103 @@ +package shcm.shsupercm.fabric.citresewn.format; + +import net.minecraft.util.Identifier; +import net.minecraft.util.InvalidIdentifierException; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.Properties; + +public class PropertiesGroupAdapter extends PropertyGroup { + public static final String EXTENSION = ".properties"; + + protected PropertiesGroupAdapter(Identifier identifier) { + super(identifier); + } + + @Override + public String getExtension() { + return EXTENSION; + } + + @Override + public PropertyGroup load(InputStream is) throws IOException, InvalidIdentifierException { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { + String line; + int linePos = 0, multilineSkip = 0; + while ((line = reader.readLine()) != null) { + linePos++; + line = line.stripLeading(); + if (line.isEmpty() || line.startsWith("#") || line.startsWith("!")) + continue; + + while (line.endsWith("\\")) { + String nextLine = reader.readLine(); + linePos++; + multilineSkip++; + if (nextLine == null) + nextLine = ""; + nextLine = nextLine.stripLeading(); + + if (nextLine.startsWith("#") || nextLine.startsWith("!")) + continue; + + line = line.substring(0, line.length() - 1) + "\\n" + nextLine; + } + + StringBuilder builder = new StringBuilder(); + + String key = null, keyMetadata = null; + + for (int i = 0; i < line.length(); i++) { + char c = line.charAt(i); + + if (c == '\\') { // escape + c = switch (c = line.charAt(++i)) { + case 'n' -> '\n'; + case 'r' -> '\r'; + case 'f' -> '\f'; + case 't' -> '\t'; + case 'u' -> { + if (i + 4 >= line.length()) + yield c; + + //todo implement manually + java.util.Properties properties = new Properties(); + properties.load(new StringReader("k=\\u" + line.charAt(i + 1) + line.charAt(i + 2) + line.charAt(i + 3) + line.charAt(i + 4))); + String k = properties.getProperty("k"); + if (k.length() == 1) { + i += 4; + yield k.charAt(0); + } + yield c; + } + + default -> c; + }; + + } else if (key == null && c == '=') { + key = builder.toString().stripTrailing(); + int metadataIndex = key.indexOf('.'); + if (metadataIndex >= 0) { + keyMetadata = key.substring(metadataIndex + 1); + key = key.substring(0, metadataIndex); + } + + builder = new StringBuilder(); + for (i++; i < line.length() && Character.isWhitespace(line.charAt(i)); i++); + i--; + continue; + } + + + builder.append(c); + } + + int pos = linePos - multilineSkip; + multilineSkip = 0; + this.put(pos, key, keyMetadata, "=", builder.toString()); + } + } + return this; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java new file mode 100644 index 0000000..d1894c7 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java @@ -0,0 +1,52 @@ +package shcm.shsupercm.fabric.citresewn.format; + +import net.minecraft.util.Identifier; +import net.minecraft.util.InvalidIdentifierException; + +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +public abstract class PropertyGroup { + public final Map> properties = new LinkedHashMap<>(); + public final Identifier identifier; + + protected PropertyGroup(Identifier identifier) { + this.identifier = identifier; + } + + public abstract String getExtension(); + + public abstract PropertyGroup load(InputStream is) throws IOException, InvalidIdentifierException; + + protected void put(int position, String key, String keyMetadata, String delimiter, String value) throws InvalidIdentifierException { + Objects.requireNonNull(key); + Objects.requireNonNull(value); + + this.properties.computeIfAbsent(PropertyKey.of(key), id -> new LinkedHashSet<>()).add(new PropertyValue(keyMetadata, value, delimiter, position)); + } + + public Set get(String namespace, String... pathAliases) { + Set values = new LinkedHashSet<>(); + + for (String path : pathAliases) { + Set possibleValues = this.properties.get(new PropertyKey(namespace, path)); + if (possibleValues != null) + values.addAll(possibleValues); + } + + return values; + } + + public static PropertyGroup tryParseGroup(Identifier identifier, InputStream is) throws IOException { + PropertyGroup group; + if (identifier.getPath().endsWith(PropertiesGroupAdapter.EXTENSION)) + group = new PropertiesGroupAdapter(identifier); + else + return null; + + group.load(is); + + return group; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyKey.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyKey.java new file mode 100644 index 0000000..9adcca2 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyKey.java @@ -0,0 +1,14 @@ +package shcm.shsupercm.fabric.citresewn.format; + +public record PropertyKey(String namespace, String path) { + public static PropertyKey of(String key) { + String[] split = new String[] {"citresewn", key}; + int i = key.indexOf(':'); + if (i >= 0) { + split[1] = key.substring(i + 1); + if (i >= 1) + split[0] = key.substring(0, i); + } + return new PropertyKey(split[0], split[1]); + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java new file mode 100644 index 0000000..ee33cc1 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java @@ -0,0 +1,17 @@ +package shcm.shsupercm.fabric.citresewn.format; + +public class PropertyValue { + public final String keyMetadata; + public final String stringValue; + public final String delimiter; + public final int position; + + public Object value = null; + + public PropertyValue(String keyMetadata, String stringValue, String delimiter, int position) { + this.keyMetadata = keyMetadata; + this.stringValue = stringValue; + this.delimiter = delimiter; + this.position = position; + } +} -- cgit From b16f0e068ba375d0b21456811a0ae5f68a77eba0 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 22 Jan 2022 17:54:26 +0200 Subject: Implemented global properties api and started pack parsing/active cits --- .../citresewn/format/PropertiesGroupAdapter.java | 2 +- .../fabric/citresewn/format/PropertyGroup.java | 10 ++-- .../fabric/citresewn/format/PropertyValue.java | 15 +----- .../fabric/citresewn/mixin/ModelLoaderMixin.java | 22 +++++++++ .../fabric/citresewn/pack/ActiveCITs.java | 46 ++++++++++++++++++ .../fabric/citresewn/pack/GlobalProperties.java | 54 ++++++++++++++++++++++ .../fabric/citresewn/pack/PackParser.java | 12 +++++ .../registry/api/GlobalPropertiesHandler.java | 8 ++++ .../fabric/citresewn/util/Disposable.java | 6 +++ src/main/resources/citresewn.mixins.json | 1 + 10 files changed, 154 insertions(+), 22 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java index c3d91ec..51ff9d8 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java @@ -20,7 +20,7 @@ public class PropertiesGroupAdapter extends PropertyGroup { } @Override - public PropertyGroup load(InputStream is) throws IOException, InvalidIdentifierException { + public PropertyGroup load(Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { String line; int linePos = 0, multilineSkip = 0; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java index d1894c7..969800e 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java @@ -17,7 +17,7 @@ public abstract class PropertyGroup { public abstract String getExtension(); - public abstract PropertyGroup load(InputStream is) throws IOException, InvalidIdentifierException; + public abstract PropertyGroup load(Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException; protected void put(int position, String key, String keyMetadata, String delimiter, String value) throws InvalidIdentifierException { Objects.requireNonNull(key); @@ -39,14 +39,10 @@ public abstract class PropertyGroup { } public static PropertyGroup tryParseGroup(Identifier identifier, InputStream is) throws IOException { - PropertyGroup group; + PropertyGroup group = null; if (identifier.getPath().endsWith(PropertiesGroupAdapter.EXTENSION)) group = new PropertiesGroupAdapter(identifier); - else - return null; - group.load(is); - - return group; + return group == null ? null : group.load(identifier, is); } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java index ee33cc1..4998803 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java @@ -1,17 +1,4 @@ package shcm.shsupercm.fabric.citresewn.format; -public class PropertyValue { - public final String keyMetadata; - public final String stringValue; - public final String delimiter; - public final int position; - - public Object value = null; - - public PropertyValue(String keyMetadata, String stringValue, String delimiter, int position) { - this.keyMetadata = keyMetadata; - this.stringValue = stringValue; - this.delimiter = delimiter; - this.position = position; - } +public record PropertyValue(String keyMetadata, String value, String delimiter, int position) { } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java new file mode 100644 index 0000000..e37ea6d --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java @@ -0,0 +1,22 @@ +package shcm.shsupercm.fabric.citresewn.mixin; + +import net.minecraft.client.color.block.BlockColors; +import net.minecraft.client.render.model.ModelLoader; +import net.minecraft.resource.ResourceManager; +import net.minecraft.util.profiler.Profiler; +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.CallbackInfo; +import shcm.shsupercm.fabric.citresewn.pack.ActiveCITs; + +@Mixin(ModelLoader.class) +public class ModelLoaderMixin { + @Inject(method = "", at = + @At(value = "INVOKE", ordinal = 0, target = "Lnet/minecraft/util/profiler/Profiler;push(Ljava/lang/String;)V")) + private void loadCITs(ResourceManager resourceManager, BlockColors blockColors, Profiler profiler, int i, CallbackInfo ci) { + profiler.push("citresewn:reloading_cits"); + ActiveCITs.load(resourceManager, profiler); + profiler.pop(); + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java new file mode 100644 index 0000000..4d48fdc --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java @@ -0,0 +1,46 @@ +package shcm.shsupercm.fabric.citresewn.pack; + +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.resource.ResourceManager; +import net.minecraft.util.profiler.Profiler; +import shcm.shsupercm.fabric.citresewn.util.Disposable; + +public class ActiveCITs implements Disposable { private ActiveCITs() {} + private static ActiveCITs active = null; + + public static ActiveCITs getActive() { + return active; + } + + public static boolean isActive() { + return active != null; + } + + public final GlobalProperties globalProperties = new GlobalProperties(); + + public static ActiveCITs load(ResourceManager resourceManager, Profiler profiler) { + profiler.push("citresewn:disposing"); + if (active != null) { + active.dispose(); + active = null; + } + profiler.pop(); + + ActiveCITs active = new ActiveCITs(); + + profiler.push("citresewn:load_global_properties"); + PackParser.loadGlobalProperties(resourceManager, active.globalProperties); + active.globalProperties.callHandlers(); + profiler.pop(); + + return ActiveCITs.active = active; + } + + @Override + public void dispose() { + for (Disposable disposable : FabricLoader.getInstance().getEntrypoints("citresewn:dispose", Disposable.class)) + disposable.dispose(); + + + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java new file mode 100644 index 0000000..7775b66 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java @@ -0,0 +1,54 @@ +package shcm.shsupercm.fabric.citresewn.pack; + +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.entrypoint.EntrypointContainer; +import net.minecraft.util.Identifier; +import net.minecraft.util.InvalidIdentifierException; +import shcm.shsupercm.fabric.citresewn.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.format.PropertyKey; +import shcm.shsupercm.fabric.citresewn.format.PropertyValue; +import shcm.shsupercm.fabric.citresewn.registry.api.GlobalPropertiesHandler; + +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +public class GlobalProperties extends PropertyGroup { + public GlobalProperties() { + super(new Identifier("citresewn", "global_properties")); + } + + @Override + public String getExtension() { + return ""; + } + + @Override + public PropertyGroup load(Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException { + PropertyGroup group = PropertyGroup.tryParseGroup(identifier, is); + if (group != null) + for (Map.Entry> entry : group.properties.entrySet()) + this.properties.computeIfAbsent(entry.getKey(), key -> new LinkedHashSet<>()).addAll(entry.getValue()); + + return this; + } + + public void callHandlers() { + for (EntrypointContainer container : FabricLoader.getInstance().getEntrypointContainers("citresewn:cit_global_properties", GlobalPropertiesHandler.class)) { + String containerNamespace = container.getProvider().getMetadata().getId(); + if (containerNamespace.equals("citresewn-defaults")) + containerNamespace = "citresewn"; + + for (Map.Entry> entry : properties.entrySet()) + if (entry.getKey().namespace().equals(containerNamespace)) { + PropertyValue value = null; + for (PropertyValue v : entry.getValue()) + value = v; + + container.getEntrypoint().globalProperty(entry.getKey().path(), value); + } + } + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java new file mode 100644 index 0000000..79ffc70 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -0,0 +1,12 @@ +package shcm.shsupercm.fabric.citresewn.pack; + +import net.minecraft.resource.ResourceManager; + +public class PackParser { + public static void loadGlobalProperties(ResourceManager resourceManager, GlobalProperties globalProperties) { + resourceManager.streamResourcePacks().forEachOrdered(resourcePack -> { + //todo + + }); + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java b/src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java new file mode 100644 index 0000000..e5a2820 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java @@ -0,0 +1,8 @@ +package shcm.shsupercm.fabric.citresewn.registry.api; + +import shcm.shsupercm.fabric.citresewn.format.PropertyValue; + +@FunctionalInterface +public interface GlobalPropertiesHandler { + void globalProperty(String key, PropertyValue value); +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java b/src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java new file mode 100644 index 0000000..84c65b2 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java @@ -0,0 +1,6 @@ +package shcm.shsupercm.fabric.citresewn.util; + +@FunctionalInterface +public interface Disposable { + void dispose(); +} diff --git a/src/main/resources/citresewn.mixins.json b/src/main/resources/citresewn.mixins.json index 70184b7..39343fb 100644 --- a/src/main/resources/citresewn.mixins.json +++ b/src/main/resources/citresewn.mixins.json @@ -4,6 +4,7 @@ "package": "shcm.shsupercm.fabric.citresewn.mixin", "compatibilityLevel": "JAVA_17", "mixins": [ + "ModelLoaderMixin" ], "injectors": { "defaultRequire": 1 -- cgit From 315e1eee9be4981ac13b49b885e153c488b18851 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 22 Jan 2022 19:29:01 +0200 Subject: Added pack name context in various places --- .../fabric/citresewn/format/PropertiesGroupAdapter.java | 6 +++--- .../shsupercm/fabric/citresewn/format/PropertyGroup.java | 12 +++++++----- .../shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java | 3 +-- .../shsupercm/fabric/citresewn/pack/GlobalProperties.java | 6 +++--- 4 files changed, 14 insertions(+), 13 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java index 51ff9d8..7501057 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java @@ -10,8 +10,8 @@ import java.util.Properties; public class PropertiesGroupAdapter extends PropertyGroup { public static final String EXTENSION = ".properties"; - protected PropertiesGroupAdapter(Identifier identifier) { - super(identifier); + protected PropertiesGroupAdapter(String packName, Identifier identifier) { + super(packName, identifier); } @Override @@ -20,7 +20,7 @@ public class PropertiesGroupAdapter extends PropertyGroup { } @Override - public PropertyGroup load(Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException { + public PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { String line; int linePos = 0, multilineSkip = 0; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java index 969800e..d2ff2a4 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java @@ -10,14 +10,16 @@ import java.util.*; public abstract class PropertyGroup { public final Map> properties = new LinkedHashMap<>(); public final Identifier identifier; + public final String packName; - protected PropertyGroup(Identifier identifier) { + protected PropertyGroup(String packName, Identifier identifier) { + this.packName = packName; this.identifier = identifier; } public abstract String getExtension(); - public abstract PropertyGroup load(Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException; + public abstract PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException; protected void put(int position, String key, String keyMetadata, String delimiter, String value) throws InvalidIdentifierException { Objects.requireNonNull(key); @@ -38,11 +40,11 @@ public abstract class PropertyGroup { return values; } - public static PropertyGroup tryParseGroup(Identifier identifier, InputStream is) throws IOException { + public static PropertyGroup tryParseGroup(String packName, Identifier identifier, InputStream is) throws IOException { PropertyGroup group = null; if (identifier.getPath().endsWith(PropertiesGroupAdapter.EXTENSION)) - group = new PropertiesGroupAdapter(identifier); + group = new PropertiesGroupAdapter(packName, identifier); - return group == null ? null : group.load(identifier, is); + return group == null ? null : group.load(packName, identifier, is); } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java index 4d48fdc..8e5faa3 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java @@ -24,11 +24,10 @@ public class ActiveCITs implements Disposable { private ActiveCITs() {} active.dispose(); active = null; } - profiler.pop(); ActiveCITs active = new ActiveCITs(); - profiler.push("citresewn:load_global_properties"); + profiler.swap("citresewn:load_global_properties"); PackParser.loadGlobalProperties(resourceManager, active.globalProperties); active.globalProperties.callHandlers(); profiler.pop(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java index 7775b66..76f5d26 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java @@ -17,7 +17,7 @@ import java.util.Set; public class GlobalProperties extends PropertyGroup { public GlobalProperties() { - super(new Identifier("citresewn", "global_properties")); + super("global_properties", new Identifier("citresewn", "global_properties")); } @Override @@ -26,8 +26,8 @@ public class GlobalProperties extends PropertyGroup { } @Override - public PropertyGroup load(Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException { - PropertyGroup group = PropertyGroup.tryParseGroup(identifier, is); + public PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException { + PropertyGroup group = PropertyGroup.tryParseGroup(packName, identifier, is); if (group != null) for (Map.Entry> entry : group.properties.entrySet()) this.properties.computeIfAbsent(entry.getKey(), key -> new LinkedHashSet<>()).addAll(entry.getValue()); -- cgit From 1a9e72178881ca41321c730eb69ce28f0b6ad171 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 5 Feb 2022 07:46:52 +0200 Subject: Migrated to using Fletching Table --- build.gradle | 11 ++++++++++- .../defaults/config/CITResewnDefaultsConfigScreenFactory.java | 3 +++ .../citresewn/defaults/config/CITResewnDefaultsModMenu.java | 2 ++ defaults/src/main/resources/citresewn-defaults.mixins.json | 2 -- defaults/src/main/resources/fabric.mod.json | 8 -------- gradle.properties | 4 ++-- src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java | 8 ++++---- .../fabric/citresewn/config/CITResewnConfigScreenFactory.java | 4 +++- .../shsupercm/fabric/citresewn/config/CITResewnModMenu.java | 2 ++ .../java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java | 2 +- .../citresewn/registry/api/GlobalPropertiesHandler.java | 4 +++- .../java/shcm/shsupercm/fabric/citresewn/util/Disposable.java | 2 ++ src/main/resources/citresewn.mixins.json | 3 --- src/main/resources/fabric.mod.json | 8 -------- 14 files changed, 32 insertions(+), 31 deletions(-) (limited to 'src/main/java/shcm') diff --git a/build.gradle b/build.gradle index 64a0be9..5774182 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,6 @@ plugins { - id 'fabric-loom' version '0.10-SNAPSHOT' apply false + id 'fabric-loom' version '0.11-SNAPSHOT' apply false + id 'io.shcm.shsupercm.fabric.fletchingtable' version '1.4' apply false id 'maven-publish' } @@ -8,6 +9,7 @@ group = project.maven_group allprojects { apply plugin: "fabric-loom" + apply plugin: "io.shcm.shsupercm.fabric.fletchingtable" repositories { maven { url "https://maven.shedaniel.me/" } @@ -33,6 +35,13 @@ allprojects { } modCompileOnly("curse.maven:cosmeticarmor-436659:${project.cosmetic_armor}") + + + fletchingTable.shutUpDrasil18() + } + + fletchingTable { + defaultMixinEnvironment = "auto" } processResources { diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java index 889c465..6d89bc6 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java @@ -1,5 +1,6 @@ package shcm.shsupercm.fabric.citresewn.defaults.config; +import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import me.shedaniel.clothconfig2.api.ConfigBuilder; import me.shedaniel.clothconfig2.api.ConfigCategory; import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; @@ -7,8 +8,10 @@ import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.text.LiteralText; import net.minecraft.text.TranslatableText; +import shcm.shsupercm.fabric.citresewn.config.CITResewnConfigScreenFactory; public class CITResewnDefaultsConfigScreenFactory { + @Entrypoint(CITResewnConfigScreenFactory.DEFAULTS_CONFIG_ENTRYPOINT) public static Screen create(Screen parent) { CITResewnDefaultsConfig currentConfig = CITResewnDefaultsConfig.INSTANCE, defaultConfig = new CITResewnDefaultsConfig(); diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsModMenu.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsModMenu.java index cba1592..48edf33 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsModMenu.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsModMenu.java @@ -2,11 +2,13 @@ package shcm.shsupercm.fabric.citresewn.defaults.config; import com.terraformersmc.modmenu.api.ConfigScreenFactory; import com.terraformersmc.modmenu.api.ModMenuApi; +import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.NoticeScreen; import net.minecraft.text.Text; +@Entrypoint("modmenu") public class CITResewnDefaultsModMenu implements ModMenuApi { @Override public ConfigScreenFactory getModConfigScreenFactory() { diff --git a/defaults/src/main/resources/citresewn-defaults.mixins.json b/defaults/src/main/resources/citresewn-defaults.mixins.json index b5c307d..536380b 100644 --- a/defaults/src/main/resources/citresewn-defaults.mixins.json +++ b/defaults/src/main/resources/citresewn-defaults.mixins.json @@ -3,8 +3,6 @@ "minVersion": "0.8", "package": "shcm.shsupercm.fabric.citresewn.defaults.mixin", "compatibilityLevel": "JAVA_17", - "mixins": [ - ], "injectors": { "defaultRequire": 1 } diff --git a/defaults/src/main/resources/fabric.mod.json b/defaults/src/main/resources/fabric.mod.json index c140556..f35e7bb 100644 --- a/defaults/src/main/resources/fabric.mod.json +++ b/defaults/src/main/resources/fabric.mod.json @@ -16,14 +16,6 @@ }, "environment": "client", - "entrypoints": { - "modmenu": [ - "shcm.shsupercm.fabric.citresewn.defaults.config.CITResewnDefaultsModMenu" - ], - "citresewn-defaults:config_screen": [ - "shcm.shsupercm.fabric.citresewn.defaults.config.CITResewnDefaultsConfigScreenFactory::create" - ] - }, "accessWidener" : "citresewn-defaults.accesswidener", "mixins": [ "citresewn-defaults.mixins.json" diff --git a/gradle.properties b/gradle.properties index bc89793..ebfce68 100644 --- a/gradle.properties +++ b/gradle.properties @@ -5,10 +5,10 @@ org.gradle.jvmargs=-Xmx1G # check these on https://modmuss50.me/fabric.html minecraft_version=1.18.1 minecraft_version_compat=1.18.x -yarn_mappings=1.18.1+build.18 +yarn_mappings=1.18.1+build.22 loader_version=0.12.12 -fabric_api=0.45.0+1.18 +fabric_api=0.46.4+1.18 modmenu=3.0.1 cloth=6.1.48 cosmetic_armor=3544655 diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java index 0a0051f..807aa97 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java @@ -1,5 +1,6 @@ package shcm.shsupercm.fabric.citresewn; +import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import net.fabricmc.api.ClientModInitializer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -7,13 +8,12 @@ import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; public class CITResewn implements ClientModInitializer { public static final Logger LOG = LogManager.getLogger("CITResewn"); - public static CITResewn INSTANCE; - - public boolean processingBrokenPaths = false; + @Entrypoint(Entrypoint.CLIENT) + public static final CITResewn INSTANCE = new CITResewn(); @Override public void onInitializeClient() { - INSTANCE = this; + info("init"); } public static void info(String message) { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java index 57ae2c3..76576ba 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java @@ -14,6 +14,8 @@ import net.minecraft.util.Formatting; import java.util.function.Function; public class CITResewnConfigScreenFactory { + public static final String DEFAULTS_CONFIG_ENTRYPOINT = "citresewn-defaults:config_screen"; + public static Screen create(Screen parent) { CITResewnConfig currentConfig = CITResewnConfig.INSTANCE, defaultConfig = new CITResewnConfig(); @@ -42,7 +44,7 @@ public class CITResewnConfigScreenFactory { .setYesNoTextSupplier((b) -> { if (b != currentScreen.prevToggle) { //noinspection unchecked - MinecraftClient.getInstance().setScreen((Screen) FabricLoader.getInstance().getEntrypoints("citresewn-defaults:config_screen", Function.class).stream().findAny().orElseThrow().apply(currentScreen.screen)); + MinecraftClient.getInstance().setScreen((Screen) FabricLoader.getInstance().getEntrypoints(DEFAULTS_CONFIG_ENTRYPOINT, Function.class).stream().findAny().orElseThrow().apply(currentScreen.screen)); currentScreen.prevToggle = b; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java index 378350a..521c3b6 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java @@ -2,11 +2,13 @@ package shcm.shsupercm.fabric.citresewn.config; import com.terraformersmc.modmenu.api.ConfigScreenFactory; import com.terraformersmc.modmenu.api.ModMenuApi; +import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.NoticeScreen; import net.minecraft.text.Text; +@Entrypoint("modmenu") public class CITResewnModMenu implements ModMenuApi { @Override public ConfigScreenFactory getModConfigScreenFactory() { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java index 8e5faa3..5523c84 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java @@ -37,7 +37,7 @@ public class ActiveCITs implements Disposable { private ActiveCITs() {} @Override public void dispose() { - for (Disposable disposable : FabricLoader.getInstance().getEntrypoints("citresewn:dispose", Disposable.class)) + for (Disposable disposable : FabricLoader.getInstance().getEntrypoints(Disposable.ENTRYPOINT, Disposable.class)) disposable.dispose(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java b/src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java index e5a2820..9b1ad6f 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java @@ -4,5 +4,7 @@ import shcm.shsupercm.fabric.citresewn.format.PropertyValue; @FunctionalInterface public interface GlobalPropertiesHandler { - void globalProperty(String key, PropertyValue value); + String ENTRYPOINT = "citresewn:global_property"; + + boolean globalProperty(String key, PropertyValue value); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java b/src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java index 84c65b2..7878e16 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java @@ -2,5 +2,7 @@ package shcm.shsupercm.fabric.citresewn.util; @FunctionalInterface public interface Disposable { + String ENTRYPOINT = "citresewn:dispose"; + void dispose(); } diff --git a/src/main/resources/citresewn.mixins.json b/src/main/resources/citresewn.mixins.json index 39343fb..394941e 100644 --- a/src/main/resources/citresewn.mixins.json +++ b/src/main/resources/citresewn.mixins.json @@ -3,9 +3,6 @@ "minVersion": "0.8", "package": "shcm.shsupercm.fabric.citresewn.mixin", "compatibilityLevel": "JAVA_17", - "mixins": [ - "ModelLoaderMixin" - ], "injectors": { "defaultRequire": 1 } diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index b00baa4..a8e2234 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -16,14 +16,6 @@ }, "environment": "client", - "entrypoints": { - "client": [ - "shcm.shsupercm.fabric.citresewn.CITResewn" - ], - "modmenu": [ - "shcm.shsupercm.fabric.citresewn.config.CITResewnModMenu" - ] - }, "accessWidener" : "citresewn.accesswidener", "mixins": [ "citresewn.mixins.json" -- cgit From fcd73195b483075c962986994f32dc53dd2f91cd Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 5 Feb 2022 08:32:41 +0200 Subject: Moved some stuff around --- .../shsupercm/fabric/citresewn/api/Disposable.java | 8 ++ .../citresewn/api/GlobalPropertiesHandler.java | 10 ++ .../citresewn/format/PropertiesGroupAdapter.java | 103 --------------------- .../fabric/citresewn/format/PropertyGroup.java | 50 ---------- .../fabric/citresewn/format/PropertyKey.java | 14 --- .../fabric/citresewn/format/PropertyValue.java | 4 - .../fabric/citresewn/mixin/ModelLoaderMixin.java | 2 +- .../fabric/citresewn/pack/ActiveCITs.java | 2 +- .../fabric/citresewn/pack/GlobalProperties.java | 16 ++-- .../pack/format/PropertiesGroupAdapter.java | 103 +++++++++++++++++++++ .../citresewn/pack/format/PropertyGroup.java | 50 ++++++++++ .../fabric/citresewn/pack/format/PropertyKey.java | 14 +++ .../citresewn/pack/format/PropertyValue.java | 4 + .../registry/api/GlobalPropertiesHandler.java | 10 -- .../fabric/citresewn/util/Disposable.java | 8 -- 15 files changed, 199 insertions(+), 199 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/api/Disposable.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyKey.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/Disposable.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/Disposable.java new file mode 100644 index 0000000..85b8849 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/Disposable.java @@ -0,0 +1,8 @@ +package shcm.shsupercm.fabric.citresewn.api; + +@FunctionalInterface +public interface Disposable { + String ENTRYPOINT = "citresewn:dispose"; + + void dispose(); +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java new file mode 100644 index 0000000..9955823 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java @@ -0,0 +1,10 @@ +package shcm.shsupercm.fabric.citresewn.api; + +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +@FunctionalInterface +public interface GlobalPropertiesHandler { + String ENTRYPOINT = "citresewn:global_property"; + + void globalProperty(String key, PropertyValue value); +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java deleted file mode 100644 index 7501057..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertiesGroupAdapter.java +++ /dev/null @@ -1,103 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.format; - -import net.minecraft.util.Identifier; -import net.minecraft.util.InvalidIdentifierException; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.util.Properties; - -public class PropertiesGroupAdapter extends PropertyGroup { - public static final String EXTENSION = ".properties"; - - protected PropertiesGroupAdapter(String packName, Identifier identifier) { - super(packName, identifier); - } - - @Override - public String getExtension() { - return EXTENSION; - } - - @Override - public PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { - String line; - int linePos = 0, multilineSkip = 0; - while ((line = reader.readLine()) != null) { - linePos++; - line = line.stripLeading(); - if (line.isEmpty() || line.startsWith("#") || line.startsWith("!")) - continue; - - while (line.endsWith("\\")) { - String nextLine = reader.readLine(); - linePos++; - multilineSkip++; - if (nextLine == null) - nextLine = ""; - nextLine = nextLine.stripLeading(); - - if (nextLine.startsWith("#") || nextLine.startsWith("!")) - continue; - - line = line.substring(0, line.length() - 1) + "\\n" + nextLine; - } - - StringBuilder builder = new StringBuilder(); - - String key = null, keyMetadata = null; - - for (int i = 0; i < line.length(); i++) { - char c = line.charAt(i); - - if (c == '\\') { // escape - c = switch (c = line.charAt(++i)) { - case 'n' -> '\n'; - case 'r' -> '\r'; - case 'f' -> '\f'; - case 't' -> '\t'; - case 'u' -> { - if (i + 4 >= line.length()) - yield c; - - //todo implement manually - java.util.Properties properties = new Properties(); - properties.load(new StringReader("k=\\u" + line.charAt(i + 1) + line.charAt(i + 2) + line.charAt(i + 3) + line.charAt(i + 4))); - String k = properties.getProperty("k"); - if (k.length() == 1) { - i += 4; - yield k.charAt(0); - } - yield c; - } - - default -> c; - }; - - } else if (key == null && c == '=') { - key = builder.toString().stripTrailing(); - int metadataIndex = key.indexOf('.'); - if (metadataIndex >= 0) { - keyMetadata = key.substring(metadataIndex + 1); - key = key.substring(0, metadataIndex); - } - - builder = new StringBuilder(); - for (i++; i < line.length() && Character.isWhitespace(line.charAt(i)); i++); - i--; - continue; - } - - - builder.append(c); - } - - int pos = linePos - multilineSkip; - multilineSkip = 0; - this.put(pos, key, keyMetadata, "=", builder.toString()); - } - } - return this; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java deleted file mode 100644 index d2ff2a4..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyGroup.java +++ /dev/null @@ -1,50 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.format; - -import net.minecraft.util.Identifier; -import net.minecraft.util.InvalidIdentifierException; - -import java.io.IOException; -import java.io.InputStream; -import java.util.*; - -public abstract class PropertyGroup { - public final Map> properties = new LinkedHashMap<>(); - public final Identifier identifier; - public final String packName; - - protected PropertyGroup(String packName, Identifier identifier) { - this.packName = packName; - this.identifier = identifier; - } - - public abstract String getExtension(); - - public abstract PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException; - - protected void put(int position, String key, String keyMetadata, String delimiter, String value) throws InvalidIdentifierException { - Objects.requireNonNull(key); - Objects.requireNonNull(value); - - this.properties.computeIfAbsent(PropertyKey.of(key), id -> new LinkedHashSet<>()).add(new PropertyValue(keyMetadata, value, delimiter, position)); - } - - public Set get(String namespace, String... pathAliases) { - Set values = new LinkedHashSet<>(); - - for (String path : pathAliases) { - Set possibleValues = this.properties.get(new PropertyKey(namespace, path)); - if (possibleValues != null) - values.addAll(possibleValues); - } - - return values; - } - - public static PropertyGroup tryParseGroup(String packName, Identifier identifier, InputStream is) throws IOException { - PropertyGroup group = null; - if (identifier.getPath().endsWith(PropertiesGroupAdapter.EXTENSION)) - group = new PropertiesGroupAdapter(packName, identifier); - - return group == null ? null : group.load(packName, identifier, is); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyKey.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyKey.java deleted file mode 100644 index 9adcca2..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyKey.java +++ /dev/null @@ -1,14 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.format; - -public record PropertyKey(String namespace, String path) { - public static PropertyKey of(String key) { - String[] split = new String[] {"citresewn", key}; - int i = key.indexOf(':'); - if (i >= 0) { - split[1] = key.substring(i + 1); - if (i >= 1) - split[0] = key.substring(0, i); - } - return new PropertyKey(split[0], split[1]); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java b/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java deleted file mode 100644 index 4998803..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/format/PropertyValue.java +++ /dev/null @@ -1,4 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.format; - -public record PropertyValue(String keyMetadata, String value, String delimiter, int position) { -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java index e37ea6d..f8b2979 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java @@ -14,7 +14,7 @@ import shcm.shsupercm.fabric.citresewn.pack.ActiveCITs; public class ModelLoaderMixin { @Inject(method = "", at = @At(value = "INVOKE", ordinal = 0, target = "Lnet/minecraft/util/profiler/Profiler;push(Ljava/lang/String;)V")) - private void loadCITs(ResourceManager resourceManager, BlockColors blockColors, Profiler profiler, int i, CallbackInfo ci) { + private void citresewn$loadCITs(ResourceManager resourceManager, BlockColors blockColors, Profiler profiler, int i, CallbackInfo ci) { profiler.push("citresewn:reloading_cits"); ActiveCITs.load(resourceManager, profiler); profiler.pop(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java index 5523c84..642b950 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java @@ -3,7 +3,7 @@ package shcm.shsupercm.fabric.citresewn.pack; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.resource.ResourceManager; import net.minecraft.util.profiler.Profiler; -import shcm.shsupercm.fabric.citresewn.util.Disposable; +import shcm.shsupercm.fabric.citresewn.api.Disposable; public class ActiveCITs implements Disposable { private ActiveCITs() {} private static ActiveCITs active = null; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java index 76f5d26..39d551a 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java @@ -4,10 +4,10 @@ import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.entrypoint.EntrypointContainer; import net.minecraft.util.Identifier; import net.minecraft.util.InvalidIdentifierException; -import shcm.shsupercm.fabric.citresewn.format.PropertyGroup; -import shcm.shsupercm.fabric.citresewn.format.PropertyKey; -import shcm.shsupercm.fabric.citresewn.format.PropertyValue; -import shcm.shsupercm.fabric.citresewn.registry.api.GlobalPropertiesHandler; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +import shcm.shsupercm.fabric.citresewn.api.GlobalPropertiesHandler; import java.io.IOException; import java.io.InputStream; @@ -43,11 +43,11 @@ public class GlobalProperties extends PropertyGroup { for (Map.Entry> entry : properties.entrySet()) if (entry.getKey().namespace().equals(containerNamespace)) { - PropertyValue value = null; - for (PropertyValue v : entry.getValue()) - value = v; + PropertyValue lastValue = null; + for (PropertyValue value : entry.getValue()) + lastValue = value; - container.getEntrypoint().globalProperty(entry.getKey().path(), value); + container.getEntrypoint().globalProperty(entry.getKey().path(), lastValue); } } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java new file mode 100644 index 0000000..896e81e --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java @@ -0,0 +1,103 @@ +package shcm.shsupercm.fabric.citresewn.pack.format; + +import net.minecraft.util.Identifier; +import net.minecraft.util.InvalidIdentifierException; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.Properties; + +public class PropertiesGroupAdapter extends PropertyGroup { + public static final String EXTENSION = ".properties"; + + protected PropertiesGroupAdapter(String packName, Identifier identifier) { + super(packName, identifier); + } + + @Override + public String getExtension() { + return EXTENSION; + } + + @Override + public PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { + String line; + int linePos = 0, multilineSkip = 0; + while ((line = reader.readLine()) != null) { + linePos++; + line = line.stripLeading(); + if (line.isEmpty() || line.startsWith("#") || line.startsWith("!")) + continue; + + while (line.endsWith("\\")) { + String nextLine = reader.readLine(); + linePos++; + multilineSkip++; + if (nextLine == null) + nextLine = ""; + nextLine = nextLine.stripLeading(); + + if (nextLine.startsWith("#") || nextLine.startsWith("!")) + continue; + + line = line.substring(0, line.length() - 1) + "\\n" + nextLine; + } + + StringBuilder builder = new StringBuilder(); + + String key = null, keyMetadata = null; + + for (int i = 0; i < line.length(); i++) { + char c = line.charAt(i); + + if (c == '\\') { // escape + c = switch (c = line.charAt(++i)) { + case 'n' -> '\n'; + case 'r' -> '\r'; + case 'f' -> '\f'; + case 't' -> '\t'; + case 'u' -> { + if (i + 4 >= line.length()) + yield c; + + //todo implement manually + java.util.Properties properties = new Properties(); + properties.load(new StringReader("k=\\u" + line.charAt(i + 1) + line.charAt(i + 2) + line.charAt(i + 3) + line.charAt(i + 4))); + String k = properties.getProperty("k"); + if (k.length() == 1) { + i += 4; + yield k.charAt(0); + } + yield c; + } + + default -> c; + }; + + } else if (key == null && c == '=') { + key = builder.toString().stripTrailing(); + int metadataIndex = key.indexOf('.'); + if (metadataIndex >= 0) { + keyMetadata = key.substring(metadataIndex + 1); + key = key.substring(0, metadataIndex); + } + + builder = new StringBuilder(); + for (i++; i < line.length() && Character.isWhitespace(line.charAt(i)); i++); + i--; + continue; + } + + + builder.append(c); + } + + int pos = linePos - multilineSkip; + multilineSkip = 0; + this.put(pos, key, keyMetadata, "=", builder.toString()); + } + } + return this; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java new file mode 100644 index 0000000..8fcb135 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java @@ -0,0 +1,50 @@ +package shcm.shsupercm.fabric.citresewn.pack.format; + +import net.minecraft.util.Identifier; +import net.minecraft.util.InvalidIdentifierException; + +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +public abstract class PropertyGroup { + public final Map> properties = new LinkedHashMap<>(); + public final Identifier identifier; + public final String packName; + + protected PropertyGroup(String packName, Identifier identifier) { + this.packName = packName; + this.identifier = identifier; + } + + public abstract String getExtension(); + + public abstract PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException; + + protected void put(int position, String key, String keyMetadata, String delimiter, String value) throws InvalidIdentifierException { + Objects.requireNonNull(key); + Objects.requireNonNull(value); + + this.properties.computeIfAbsent(PropertyKey.of(key), id -> new LinkedHashSet<>()).add(new PropertyValue(keyMetadata, value, delimiter, position)); + } + + public Set get(String namespace, String... pathAliases) { + Set values = new LinkedHashSet<>(); + + for (String path : pathAliases) { + Set possibleValues = this.properties.get(new PropertyKey(namespace, path)); + if (possibleValues != null) + values.addAll(possibleValues); + } + + return values; + } + + public static PropertyGroup tryParseGroup(String packName, Identifier identifier, InputStream is) throws IOException { + PropertyGroup group = null; + if (identifier.getPath().endsWith(PropertiesGroupAdapter.EXTENSION)) + group = new PropertiesGroupAdapter(packName, identifier); + + return group == null ? null : group.load(packName, identifier, is); + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java new file mode 100644 index 0000000..b861a63 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java @@ -0,0 +1,14 @@ +package shcm.shsupercm.fabric.citresewn.pack.format; + +public record PropertyKey(String namespace, String path) { + public static PropertyKey of(String key) { + String[] split = new String[] {"citresewn", key}; + int i = key.indexOf(':'); + if (i >= 0) { + split[1] = key.substring(i + 1); + if (i >= 1) + split[0] = key.substring(0, i); + } + return new PropertyKey(split[0], split[1]); + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java new file mode 100644 index 0000000..9a0c4e3 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java @@ -0,0 +1,4 @@ +package shcm.shsupercm.fabric.citresewn.pack.format; + +public record PropertyValue(String keyMetadata, String value, String delimiter, int position) { +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java b/src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java deleted file mode 100644 index 9b1ad6f..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/registry/api/GlobalPropertiesHandler.java +++ /dev/null @@ -1,10 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.registry.api; - -import shcm.shsupercm.fabric.citresewn.format.PropertyValue; - -@FunctionalInterface -public interface GlobalPropertiesHandler { - String ENTRYPOINT = "citresewn:global_property"; - - boolean globalProperty(String key, PropertyValue value); -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java b/src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java deleted file mode 100644 index 7878e16..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/util/Disposable.java +++ /dev/null @@ -1,8 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.util; - -@FunctionalInterface -public interface Disposable { - String ENTRYPOINT = "citresewn:dispose"; - - void dispose(); -} -- cgit From b8572ff143d1d7f4d37472bcd1b15340aaaceea5 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 5 Feb 2022 12:17:49 +0200 Subject: Implemented internal global properties and improved property context --- .../citresewn/api/GlobalPropertiesHandler.java | 2 +- .../citresewn/mixin/GroupResourcePackAccessor.java | 14 +++++++ .../fabric/citresewn/pack/GlobalProperties.java | 9 ++++- .../fabric/citresewn/pack/PackParser.java | 44 ++++++++++++++++++++-- .../pack/format/PropertiesGroupAdapter.java | 2 +- .../citresewn/pack/format/PropertyGroup.java | 4 +- .../citresewn/pack/format/PropertyValue.java | 9 ++++- 7 files changed, 75 insertions(+), 9 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java index 9955823..ac8228a 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java @@ -6,5 +6,5 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; public interface GlobalPropertiesHandler { String ENTRYPOINT = "citresewn:global_property"; - void globalProperty(String key, PropertyValue value); + void globalProperty(String key, PropertyValue value) throws Exception; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java new file mode 100644 index 0000000..72af871 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java @@ -0,0 +1,14 @@ +package shcm.shsupercm.fabric.citresewn.mixin; + +import net.fabricmc.fabric.impl.resource.loader.GroupResourcePack; +import net.minecraft.resource.ResourcePack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +import java.util.List; + +@Mixin(GroupResourcePack.class) +public interface GroupResourcePackAccessor { + @Accessor + List getPacks(); +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java index 39d551a..d4f89f0 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java @@ -4,6 +4,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.entrypoint.EntrypointContainer; import net.minecraft.util.Identifier; import net.minecraft.util.InvalidIdentifierException; +import shcm.shsupercm.fabric.citresewn.CITResewn; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; @@ -47,7 +48,13 @@ public class GlobalProperties extends PropertyGroup { for (PropertyValue value : entry.getValue()) lastValue = value; - container.getEntrypoint().globalProperty(entry.getKey().path(), lastValue); + if (lastValue != null) + try { + container.getEntrypoint().globalProperty(entry.getKey().path(), lastValue); + } catch (Exception e) { + CITResewn.logErrorLoading("Errored while parsing global properties: Line " + lastValue.position() + " of " + lastValue.propertiesIdentifier() + " in " + lastValue.packName()); + e.printStackTrace(); + } } } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 79ffc70..463d34a 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -1,12 +1,50 @@ package shcm.shsupercm.fabric.citresewn.pack; +import net.fabricmc.fabric.impl.resource.loader.GroupResourcePack; +import net.fabricmc.loader.api.FabricLoader; import net.minecraft.resource.ResourceManager; +import net.minecraft.resource.ResourceNotFoundException; +import net.minecraft.resource.ResourcePack; +import net.minecraft.resource.ResourceType; +import net.minecraft.util.Identifier; +import shcm.shsupercm.fabric.citresewn.CITResewn; +import shcm.shsupercm.fabric.citresewn.mixin.GroupResourcePackAccessor; + +import java.io.IOException; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Function; public class PackParser { - public static void loadGlobalProperties(ResourceManager resourceManager, GlobalProperties globalProperties) { - resourceManager.streamResourcePacks().forEachOrdered(resourcePack -> { - //todo + private static final String[] ROOTS = new String[] { "mcpatcher", "optifine", "citresewn" }; + private static final Function> PARSE_FAPI_GROUPS = + FabricLoader.getInstance().isModLoaded("fabric-resource-loader-v0") ? + parentPack -> parentPack instanceof GroupResourcePack ? ((GroupResourcePackAccessor) parentPack).getPacks() : null + : parentPack -> null; + + private static void forEachPack(ResourceManager resourceManager, Consumer run) { + resourceManager.streamResourcePacks().forEachOrdered(pack -> { + List grouped = PARSE_FAPI_GROUPS.apply(pack); + if (grouped != null) + for (ResourcePack subPack : grouped) + run.accept(subPack); + else + run.accept(pack); + }); + } + public static void loadGlobalProperties(ResourceManager resourceManager, GlobalProperties globalProperties) { + forEachPack(resourceManager, pack -> { + for (String root : ROOTS) { + Identifier identifier = new Identifier("minecraft", root + "/cit.properties"); + try { + globalProperties.load(pack.getName(), identifier, pack.open(ResourceType.CLIENT_RESOURCES, identifier)); + } catch (ResourceNotFoundException ignored) { + } catch (IOException e) { + CITResewn.logErrorLoading("Errored while loading global properties: " + identifier + " in " + pack.getName()); + e.printStackTrace(); + } + } }); } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java index 896e81e..bfa4091 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java @@ -95,7 +95,7 @@ public class PropertiesGroupAdapter extends PropertyGroup { int pos = linePos - multilineSkip; multilineSkip = 0; - this.put(pos, key, keyMetadata, "=", builder.toString()); + this.put(pos, packName, identifier, key, keyMetadata, "=", builder.toString()); } } return this; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java index 8fcb135..3864569 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java @@ -21,11 +21,11 @@ public abstract class PropertyGroup { public abstract PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException; - protected void put(int position, String key, String keyMetadata, String delimiter, String value) throws InvalidIdentifierException { + protected void put(int position, String packName, Identifier propertiesIdentifier, String key, String keyMetadata, String delimiter, String value) throws InvalidIdentifierException { Objects.requireNonNull(key); Objects.requireNonNull(value); - this.properties.computeIfAbsent(PropertyKey.of(key), id -> new LinkedHashSet<>()).add(new PropertyValue(keyMetadata, value, delimiter, position)); + this.properties.computeIfAbsent(PropertyKey.of(key), id -> new LinkedHashSet<>()).add(new PropertyValue(keyMetadata, value, delimiter, position, propertiesIdentifier, packName)); } public Set get(String namespace, String... pathAliases) { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java index 9a0c4e3..0294cb2 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java @@ -1,4 +1,11 @@ package shcm.shsupercm.fabric.citresewn.pack.format; -public record PropertyValue(String keyMetadata, String value, String delimiter, int position) { +import net.minecraft.util.Identifier; + +public record PropertyValue(String keyMetadata, + String value, + String delimiter, + int position, + Identifier propertiesIdentifier, + String packName) { } -- cgit From 2a2ccd535ece8529b4c93922261d8ecbfe421b9e Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 5 Feb 2022 14:14:43 +0200 Subject: Fixed property without separator passing null key --- .../fabric/citresewn/pack/format/PropertiesGroupAdapter.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java index bfa4091..fb694ae 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java @@ -20,7 +20,7 @@ public class PropertiesGroupAdapter extends PropertyGroup { } @Override - public PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException { + public PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { String line; int linePos = 0, multilineSkip = 0; @@ -93,6 +93,9 @@ public class PropertiesGroupAdapter extends PropertyGroup { builder.append(c); } + if (key == null) + throw new IOException("Missing separator in line " + linePos); + int pos = linePos - multilineSkip; multilineSkip = 0; this.put(pos, packName, identifier, key, keyMetadata, "=", builder.toString()); -- cgit From 31a31ef5a357bbf180ef9e438771cc8623317194 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sun, 6 Feb 2022 05:36:23 +0200 Subject: Started runtime CIT structure --- .../fabric/citresewn/mixin/ModelLoaderMixin.java | 2 +- .../fabric/citresewn/pack/ActiveCITs.java | 45 --------------------- .../fabric/citresewn/pack/cit/ActiveCITs.java | 47 ++++++++++++++++++++++ .../shsupercm/fabric/citresewn/pack/cit/CIT.java | 17 ++++++++ .../fabric/citresewn/pack/cit/CITCondition.java | 9 +++++ .../fabric/citresewn/pack/cit/CITContext.java | 4 ++ .../fabric/citresewn/pack/cit/CITType.java | 4 ++ 7 files changed, 82 insertions(+), 46 deletions(-) delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java index f8b2979..e5e000d 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java @@ -8,7 +8,7 @@ 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.CallbackInfo; -import shcm.shsupercm.fabric.citresewn.pack.ActiveCITs; +import shcm.shsupercm.fabric.citresewn.pack.cit.ActiveCITs; @Mixin(ModelLoader.class) public class ModelLoaderMixin { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java deleted file mode 100644 index 642b950..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/ActiveCITs.java +++ /dev/null @@ -1,45 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack; - -import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.resource.ResourceManager; -import net.minecraft.util.profiler.Profiler; -import shcm.shsupercm.fabric.citresewn.api.Disposable; - -public class ActiveCITs implements Disposable { private ActiveCITs() {} - private static ActiveCITs active = null; - - public static ActiveCITs getActive() { - return active; - } - - public static boolean isActive() { - return active != null; - } - - public final GlobalProperties globalProperties = new GlobalProperties(); - - public static ActiveCITs load(ResourceManager resourceManager, Profiler profiler) { - profiler.push("citresewn:disposing"); - if (active != null) { - active.dispose(); - active = null; - } - - ActiveCITs active = new ActiveCITs(); - - profiler.swap("citresewn:load_global_properties"); - PackParser.loadGlobalProperties(resourceManager, active.globalProperties); - active.globalProperties.callHandlers(); - profiler.pop(); - - return ActiveCITs.active = active; - } - - @Override - public void dispose() { - for (Disposable disposable : FabricLoader.getInstance().getEntrypoints(Disposable.ENTRYPOINT, Disposable.class)) - disposable.dispose(); - - - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java new file mode 100644 index 0000000..f8df1ee --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java @@ -0,0 +1,47 @@ +package shcm.shsupercm.fabric.citresewn.pack.cit; + +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.resource.ResourceManager; +import net.minecraft.util.profiler.Profiler; +import shcm.shsupercm.fabric.citresewn.api.Disposable; +import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; +import shcm.shsupercm.fabric.citresewn.pack.PackParser; + +public class ActiveCITs implements Disposable { private ActiveCITs() {} + private static ActiveCITs active = null; + + public static ActiveCITs getActive() { + return active; + } + + public static boolean isActive() { + return active != null; + } + + public final GlobalProperties globalProperties = new GlobalProperties(); + + public static ActiveCITs load(ResourceManager resourceManager, Profiler profiler) { + profiler.push("citresewn:disposing"); + if (active != null) { + active.dispose(); + active = null; + } + + ActiveCITs active = new ActiveCITs(); + + profiler.swap("citresewn:load_global_properties"); + PackParser.loadGlobalProperties(resourceManager, active.globalProperties); + active.globalProperties.callHandlers(); + profiler.pop(); + + return ActiveCITs.active = active; + } + + @Override + public void dispose() { + for (Disposable disposable : FabricLoader.getInstance().getEntrypoints(Disposable.ENTRYPOINT, Disposable.class)) + disposable.dispose(); + + + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java new file mode 100644 index 0000000..ee293ce --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java @@ -0,0 +1,17 @@ +package shcm.shsupercm.fabric.citresewn.pack.cit; + +import net.minecraft.util.Identifier; + +public class CIT { + private final Identifier propertiesIdentifier; + private final String packName; + private final CITType type; + private final CITCondition[] conditions; + + public CIT(Identifier propertiesIdentifier, String packName, CITType type, CITCondition[] conditions) { + this.propertiesIdentifier = propertiesIdentifier; + this.packName = packName; + this.type = type; + this.conditions = conditions; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java new file mode 100644 index 0000000..736afac --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java @@ -0,0 +1,9 @@ +package shcm.shsupercm.fabric.citresewn.pack.cit; + +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +public abstract class CITCondition { + public abstract void load(String keyMetadata, PropertyValue value) throws Exception; + + public abstract boolean test(CITContext context); +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java new file mode 100644 index 0000000..a4e0d11 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java @@ -0,0 +1,4 @@ +package shcm.shsupercm.fabric.citresewn.pack.cit; + +public record CITContext() { +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java new file mode 100644 index 0000000..c10e29f --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java @@ -0,0 +1,4 @@ +package shcm.shsupercm.fabric.citresewn.pack.cit; + +public abstract class CITType { +} -- cgit From ba570a6b2e37f6f45b149515cd41d10037cbda7f Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sun, 6 Feb 2022 15:00:29 +0200 Subject: Built more runtime api --- .../fabric/citresewn/pack/cit/CITCondition.java | 15 +++++++++++ .../fabric/citresewn/pack/cit/CITContext.java | 30 +++++++++++++++++++++- .../fabric/citresewn/pack/cit/CITType.java | 5 ++++ 3 files changed, 49 insertions(+), 1 deletion(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java index 736afac..e117133 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java @@ -2,8 +2,23 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +import java.util.Collections; +import java.util.Set; + public abstract class CITCondition { public abstract void load(String keyMetadata, PropertyValue value) throws Exception; + public Set> acceptedTypes() { + return null; + } + + public Set> siblingConditions() { + return Collections.emptySet(); + } + + public T modifySibling(T sibling) { + return sibling; + } + public abstract boolean test(CITContext context); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java index a4e0d11..d8d66ad 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java @@ -1,4 +1,32 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; -public record CITContext() { +import net.minecraft.entity.LivingEntity; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +import java.util.Objects; + +public class CITContext { + public final ItemStack stack; + public final World world; + public final LivingEntity entity; + + public CITContext(ItemStack stack, World world, LivingEntity entity) { + this.stack = stack; + this.world = world; + this.entity = entity; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof CITContext that && + Objects.equals(this.stack, that.stack) && + Objects.equals(this.world, that.world) && + Objects.equals(this.entity, that.entity); + } + + @Override + public int hashCode() { + return Objects.hash(stack, world, entity); + } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java index c10e29f..557a34c 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java @@ -1,4 +1,9 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; +import java.util.List; + public abstract class CITType { + public List modifyConditions(List conditions) { + return conditions; + } } -- cgit From d51ec9fd6cde3ad393d4d0c91e30cc5d03945eaf Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 12 Feb 2022 09:21:09 +0200 Subject: More work on type registry/api --- .../shcm/shsupercm/fabric/citresewn/CITResewn.java | 3 +- .../fabric/citresewn/api/CITDisposable.java | 8 ++++ .../fabric/citresewn/api/CITGlobalProperties.java | 10 +++++ .../fabric/citresewn/api/CITTypeContainer.java | 22 ++++++++++ .../shsupercm/fabric/citresewn/api/Disposable.java | 8 ---- .../citresewn/api/GlobalPropertiesHandler.java | 10 ----- .../fabric/citresewn/ex/CITParsingException.java | 13 ++++++ .../citresewn/ex/UnknownCITTypeException.java | 9 ++++ .../fabric/citresewn/pack/GlobalProperties.java | 4 +- .../fabric/citresewn/pack/PackParser.java | 2 +- .../fabric/citresewn/pack/cit/ActiveCITs.java | 6 +-- .../shsupercm/fabric/citresewn/pack/cit/CIT.java | 16 ++++++-- .../fabric/citresewn/pack/cit/CITRegistry.java | 48 ++++++++++++++++++++++ .../citresewn/pack/format/PropertyGroup.java | 7 ++++ 14 files changed, 137 insertions(+), 29 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/api/CITDisposable.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/api/Disposable.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/ex/UnknownCITTypeException.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java index 807aa97..ce908ed 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java @@ -5,6 +5,7 @@ import net.fabricmc.api.ClientModInitializer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITRegistry; public class CITResewn implements ClientModInitializer { public static final Logger LOG = LogManager.getLogger("CITResewn"); @@ -13,7 +14,7 @@ public class CITResewn implements ClientModInitializer { @Override public void onInitializeClient() { - info("init"); + CITRegistry.registerAll(); } public static void info(String message) { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITDisposable.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITDisposable.java new file mode 100644 index 0000000..240f197 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITDisposable.java @@ -0,0 +1,8 @@ +package shcm.shsupercm.fabric.citresewn.api; + +@FunctionalInterface +public interface CITDisposable { + String ENTRYPOINT = "citresewn:dispose"; + + void dispose(); +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java new file mode 100644 index 0000000..ada5147 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java @@ -0,0 +1,10 @@ +package shcm.shsupercm.fabric.citresewn.api; + +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +@FunctionalInterface +public interface CITGlobalProperties { + String ENTRYPOINT = "citresewn:global_property"; + + void globalProperty(String key, PropertyValue value) throws Exception; +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java new file mode 100644 index 0000000..d691ab2 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java @@ -0,0 +1,22 @@ +package shcm.shsupercm.fabric.citresewn.api; + +import shcm.shsupercm.fabric.citresewn.pack.cit.CIT; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITType; + +import java.util.Collection; +import java.util.function.Supplier; + +public abstract class CITTypeContainer implements CITDisposable { + public static final String ENTRYPOINT = "citresewn:type"; + public final Class type; + public final Supplier createType; + public final String id; + + public CITTypeContainer(Class type, Supplier createType, String id) { + this.type = type; + this.createType = createType; + this.id = id; + } + + public abstract void load(Collection parsedCITs); +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/Disposable.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/Disposable.java deleted file mode 100644 index 85b8849..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/Disposable.java +++ /dev/null @@ -1,8 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.api; - -@FunctionalInterface -public interface Disposable { - String ENTRYPOINT = "citresewn:dispose"; - - void dispose(); -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java deleted file mode 100644 index ac8228a..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/GlobalPropertiesHandler.java +++ /dev/null @@ -1,10 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.api; - -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; - -@FunctionalInterface -public interface GlobalPropertiesHandler { - String ENTRYPOINT = "citresewn:global_property"; - - void globalProperty(String key, PropertyValue value) throws Exception; -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java new file mode 100644 index 0000000..964b58d --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java @@ -0,0 +1,13 @@ +package shcm.shsupercm.fabric.citresewn.ex; + +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; + +public class CITParsingException extends Exception { + public CITParsingException(String message, PropertyGroup propertyGroup, int position) { + super("Errored while parsing CIT: " + descriptionOf(message, propertyGroup, position)); + } + + public static String descriptionOf(String message, PropertyGroup propertyGroup, int position) { + return message + " at " + position + " in " + propertyGroup.identifier.toString() + " from " + propertyGroup.packName; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/UnknownCITTypeException.java b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/UnknownCITTypeException.java new file mode 100644 index 0000000..eacbc69 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/UnknownCITTypeException.java @@ -0,0 +1,9 @@ +package shcm.shsupercm.fabric.citresewn.ex; + +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; + +public class UnknownCITTypeException extends CITParsingException { + public UnknownCITTypeException(PropertyGroup propertyGroup, int position) { + super("Unknown type", propertyGroup, position); + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java index d4f89f0..c9e2cf8 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java @@ -8,7 +8,7 @@ import shcm.shsupercm.fabric.citresewn.CITResewn; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; -import shcm.shsupercm.fabric.citresewn.api.GlobalPropertiesHandler; +import shcm.shsupercm.fabric.citresewn.api.CITGlobalProperties; import java.io.IOException; import java.io.InputStream; @@ -37,7 +37,7 @@ public class GlobalProperties extends PropertyGroup { } public void callHandlers() { - for (EntrypointContainer container : FabricLoader.getInstance().getEntrypointContainers("citresewn:cit_global_properties", GlobalPropertiesHandler.class)) { + for (EntrypointContainer container : FabricLoader.getInstance().getEntrypointContainers("citresewn:cit_global_properties", CITGlobalProperties.class)) { String containerNamespace = container.getProvider().getMetadata().getId(); if (containerNamespace.equals("citresewn-defaults")) containerNamespace = "citresewn"; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 463d34a..4945120 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -41,7 +41,7 @@ public class PackParser { globalProperties.load(pack.getName(), identifier, pack.open(ResourceType.CLIENT_RESOURCES, identifier)); } catch (ResourceNotFoundException ignored) { } catch (IOException e) { - CITResewn.logErrorLoading("Errored while loading global properties: " + identifier + " in " + pack.getName()); + CITResewn.logErrorLoading("Errored while loading global properties: " + identifier + " from " + pack.getName()); e.printStackTrace(); } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java index f8df1ee..62f011e 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java @@ -3,11 +3,11 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.resource.ResourceManager; import net.minecraft.util.profiler.Profiler; -import shcm.shsupercm.fabric.citresewn.api.Disposable; +import shcm.shsupercm.fabric.citresewn.api.CITDisposable; import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.PackParser; -public class ActiveCITs implements Disposable { private ActiveCITs() {} +public class ActiveCITs implements CITDisposable { private ActiveCITs() {} private static ActiveCITs active = null; public static ActiveCITs getActive() { @@ -39,7 +39,7 @@ public class ActiveCITs implements Disposable { private ActiveCITs() {} @Override public void dispose() { - for (Disposable disposable : FabricLoader.getInstance().getEntrypoints(Disposable.ENTRYPOINT, Disposable.class)) + for (CITDisposable disposable : FabricLoader.getInstance().getEntrypoints(CITDisposable.ENTRYPOINT, CITDisposable.class)) disposable.dispose(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java index ee293ce..0eac632 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java @@ -3,10 +3,10 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; import net.minecraft.util.Identifier; public class CIT { - private final Identifier propertiesIdentifier; - private final String packName; - private final CITType type; - private final CITCondition[] conditions; + public final Identifier propertiesIdentifier; + public final String packName; + public final CITType type; + public final CITCondition[] conditions; public CIT(Identifier propertiesIdentifier, String packName, CITType type, CITCondition[] conditions) { this.propertiesIdentifier = propertiesIdentifier; @@ -14,4 +14,12 @@ public class CIT { this.type = type; this.conditions = conditions; } + + public boolean test(CITContext context) { + for (CITCondition condition : conditions) + if (!condition.test(context)) + return false; + + return true; + } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java new file mode 100644 index 0000000..9dd423b --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java @@ -0,0 +1,48 @@ +package shcm.shsupercm.fabric.citresewn.pack.cit; + +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.util.Identifier; +import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.ex.UnknownCITTypeException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +import java.util.HashMap; +import java.util.Map; + +import static shcm.shsupercm.fabric.citresewn.CITResewn.info; + +public class CITRegistry { + private static final Map> TYPES = new HashMap<>(); + + public static void registerAll() { + info("Registering CIT Types"); + for (var entrypointContainer : FabricLoader.getInstance().getEntrypointContainers(CITTypeContainer.ENTRYPOINT, CITTypeContainer.class)) { + String namespace = entrypointContainer.getProvider().getMetadata().getId(); + if (namespace.equals("citresewn-defaults")) + namespace = "citresewn"; + + TYPES.put(new Identifier(namespace, entrypointContainer.getEntrypoint().id), (CITTypeContainer) entrypointContainer.getEntrypoint()); + } + } + + public static CITTypeContainer parseType(PropertyGroup properties) throws CITParsingException { + Identifier type = new Identifier("citresewn", "item"); + + PropertyValue propertiesType = properties.getLast("citresewn", "type"); + if (propertiesType != null) { + String value = propertiesType.value(); + if (!value.contains(":")) + value = "citresewn:" + value; + type = new Identifier(value); + } + + CITTypeContainer typeContainer = TYPES.get(type); + if (typeContainer == null) + // assert (propertiesType != null) because the default citresewn:item should always be registered + throw new UnknownCITTypeException(properties, propertiesType == null ? -1 : propertiesType.position()); + + return typeContainer; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java index 3864569..6955ac1 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java @@ -40,6 +40,13 @@ public abstract class PropertyGroup { return values; } + public PropertyValue getLast(String namespace, String... pathAliases) { + PropertyValue value = null; + for (Iterator iterator = get(namespace, pathAliases).iterator(); iterator.hasNext(); value = iterator.next()); + + return value; + } + public static PropertyGroup tryParseGroup(String packName, Identifier identifier, InputStream is) throws IOException { PropertyGroup group = null; if (identifier.getPath().endsWith(PropertiesGroupAdapter.EXTENSION)) -- cgit From 3ca2dde4a8e70bd3f8f11b5d7dbad9ddbc9792af Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 12 Feb 2022 14:28:07 +0200 Subject: Created condition container api/parsing and fixed some stuff --- .../fabric/citresewn/defaults/types/TypeItem.java | 10 ++++ .../citresewn/api/CITConditionContainer.java | 18 +++++++ .../fabric/citresewn/pack/cit/CITCondition.java | 5 +- .../fabric/citresewn/pack/cit/CITRegistry.java | 61 ++++++++++++++++++++-- .../fabric/citresewn/pack/cit/CITType.java | 8 +-- 5 files changed, 93 insertions(+), 9 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java index c8ef04b..ec2491f 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java @@ -2,15 +2,25 @@ package shcm.shsupercm.fabric.citresewn.defaults.types; import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.cit.CIT; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; import shcm.shsupercm.fabric.citresewn.pack.cit.CITType; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import java.util.Collection; +import java.util.List; public class TypeItem extends CITType { @Entrypoint(CITTypeContainer.ENTRYPOINT) public static final Container CONTAINER = new Container(); + @Override + public void load(List conditions, PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException { + + } + public static class Container extends CITTypeContainer { public Container() { super(TypeItem.class, TypeItem::new, "item"); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java new file mode 100644 index 0000000..d307b1a --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java @@ -0,0 +1,18 @@ +package shcm.shsupercm.fabric.citresewn.api; + +import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; + +import java.util.function.Supplier; + +public abstract class CITConditionContainer { + public static final String ENTRYPOINT = "citresewn:condition"; + public final Class condition; + public final Supplier createCondition; + public final String[] aliases; + + protected CITConditionContainer(Class condition, Supplier createCondition, String... aliases) { + this.condition = condition; + this.createCondition = createCondition; + this.aliases = aliases; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java index e117133..f05d4d1 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java @@ -1,12 +1,13 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import java.util.Collections; import java.util.Set; public abstract class CITCondition { - public abstract void load(String keyMetadata, PropertyValue value) throws Exception; + public abstract void load(PropertyValue value) throws CITParsingException; public Set> acceptedTypes() { return null; @@ -16,7 +17,7 @@ public abstract class CITCondition { return Collections.emptySet(); } - public T modifySibling(T sibling) { + public T modifySibling(Class siblingType, T sibling) { return sibling; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java index 9dd423b..2f34de3 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java @@ -2,21 +2,35 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; +import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.ex.UnknownCITTypeException; +import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; -import java.util.HashMap; -import java.util.Map; +import java.util.*; import static shcm.shsupercm.fabric.citresewn.CITResewn.info; +import static shcm.shsupercm.fabric.citresewn.CITResewn.logWarnLoading; public class CITRegistry { private static final Map> TYPES = new HashMap<>(); + private static final Map> CONDITIONS = new HashMap<>(); public static void registerAll() { + info("Registering CIT Conditions"); + for (var entrypointContainer : FabricLoader.getInstance().getEntrypointContainers(CITConditionContainer.ENTRYPOINT, CITConditionContainer.class)) { + String namespace = entrypointContainer.getProvider().getMetadata().getId(); + if (namespace.equals("citresewn-defaults")) + namespace = "citresewn"; + + for (String alias : entrypointContainer.getEntrypoint().aliases) + CONDITIONS.put(new PropertyKey(namespace, alias), (CITConditionContainer) entrypointContainer.getEntrypoint()); + } + info("Registering CIT Types"); for (var entrypointContainer : FabricLoader.getInstance().getEntrypointContainers(CITTypeContainer.ENTRYPOINT, CITTypeContainer.class)) { String namespace = entrypointContainer.getProvider().getMetadata().getId(); @@ -27,7 +41,46 @@ public class CITRegistry { } } - public static CITTypeContainer parseType(PropertyGroup properties) throws CITParsingException { + public static CIT load(PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException { + CITType citType = parseType(properties); + + ArrayList conditions = new ArrayList<>(); + + for (Map.Entry> entry : properties.properties.entrySet()) { + if (entry.getKey().path().equals("type") && entry.getKey().namespace().equals("citresewn")) + continue; + + for (PropertyValue value : entry.getValue()) + conditions.add(parseCondition(properties, entry.getKey(), value)); + } + + for (CITCondition condition : new ArrayList<>(conditions)) + for (Class siblingConditionType : condition.siblingConditions()) + conditions.replaceAll( + siblingCondition -> siblingConditionType == siblingCondition.getClass() ? + condition.modifySibling(siblingConditionType, siblingCondition) : + siblingCondition); + + conditions.removeIf(Objects::isNull); + + citType.load(conditions, properties, globalProperties); + + return new CIT(properties.identifier, properties.packName, citType, conditions.toArray(new CITCondition[0])); + } + + public static CITCondition parseCondition(PropertyGroup properties, PropertyKey key, PropertyValue value) throws CITParsingException { + CITConditionContainer conditionContainer = CONDITIONS.get(key); + if (conditionContainer == null) { + logWarnLoading("Skipping condition: " + CITParsingException.descriptionOf("Unknown condition type", properties, value.position())); + return null; + } + + CITCondition condition = conditionContainer.createCondition.get(); + condition.load(value); + return condition; + } + + public static CITType parseType(PropertyGroup properties) throws CITParsingException { Identifier type = new Identifier("citresewn", "item"); PropertyValue propertiesType = properties.getLast("citresewn", "type"); @@ -43,6 +96,6 @@ public class CITRegistry { // assert (propertiesType != null) because the default citresewn:item should always be registered throw new UnknownCITTypeException(properties, propertiesType == null ? -1 : propertiesType.position()); - return typeContainer; + return typeContainer.createType.get(); } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java index 557a34c..bbfa0e9 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java @@ -1,9 +1,11 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; + import java.util.List; public abstract class CITType { - public List modifyConditions(List conditions) { - return conditions; - } + public abstract void load(List conditions, PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException; } -- cgit From 4d0abf10e4c8e66f06b61b52aa3dafef0d535e79 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 12 Feb 2022 16:30:28 +0200 Subject: Implemented weight condition parsing --- .../citresewn/api/CITConditionContainer.java | 4 ++-- .../fabric/citresewn/builtin/WeightCondition.java | 27 ++++++++++++++++++++++ .../shsupercm/fabric/citresewn/pack/cit/CIT.java | 4 +++- .../fabric/citresewn/pack/cit/CITCondition.java | 12 +++++++++- .../fabric/citresewn/pack/cit/CITRegistry.java | 22 +++++++++++++----- 5 files changed, 59 insertions(+), 10 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java index d307b1a..6803526 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java @@ -4,13 +4,13 @@ import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; import java.util.function.Supplier; -public abstract class CITConditionContainer { +public class CITConditionContainer { public static final String ENTRYPOINT = "citresewn:condition"; public final Class condition; public final Supplier createCondition; public final String[] aliases; - protected CITConditionContainer(Class condition, Supplier createCondition, String... aliases) { + public CITConditionContainer(Class condition, Supplier createCondition, String... aliases) { this.condition = condition; this.createCondition = createCondition; this.aliases = aliases; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java new file mode 100644 index 0000000..9882d7b --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java @@ -0,0 +1,27 @@ +package shcm.shsupercm.fabric.citresewn.builtin; + +import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; +import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +public class WeightCondition extends CITCondition { + @Entrypoint(CITConditionContainer.ENTRYPOINT) + public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(WeightCondition.class, WeightCondition::new, "weight"); + + public int weight = 0; + + @Override + public void load(PropertyValue value, PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException { + this.weight = parseInteger(value, properties); + } + + @Override + public boolean test(CITContext context) { + return true; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java index 0eac632..b4aa9fb 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java @@ -7,12 +7,14 @@ public class CIT { public final String packName; public final CITType type; public final CITCondition[] conditions; + public final int weight; - public CIT(Identifier propertiesIdentifier, String packName, CITType type, CITCondition[] conditions) { + public CIT(Identifier propertiesIdentifier, String packName, CITType type, CITCondition[] conditions, int weight) { this.propertiesIdentifier = propertiesIdentifier; this.packName = packName; this.type = type; this.conditions = conditions; + this.weight = weight; } public boolean test(CITContext context) { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java index f05d4d1..2de5be1 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java @@ -1,13 +1,15 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import java.util.Collections; import java.util.Set; public abstract class CITCondition { - public abstract void load(PropertyValue value) throws CITParsingException; + public abstract void load(PropertyValue value, PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException; public Set> acceptedTypes() { return null; @@ -22,4 +24,12 @@ public abstract class CITCondition { } public abstract boolean test(CITContext context); + + protected int parseInteger(PropertyValue value, PropertyGroup properties) throws CITParsingException { + try { + return Integer.parseInt(value.value()); + } catch (NumberFormatException e) { + throw new CITParsingException("\"" + value.value() + "\" is not a valid integer", properties, value.position()); + } + } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java index 2f34de3..fe0bcc7 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java @@ -4,6 +4,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; +import shcm.shsupercm.fabric.citresewn.builtin.WeightCondition; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.ex.UnknownCITTypeException; import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; @@ -51,7 +52,7 @@ public class CITRegistry { continue; for (PropertyValue value : entry.getValue()) - conditions.add(parseCondition(properties, entry.getKey(), value)); + conditions.add(parseCondition(entry.getKey(), value, properties, globalProperties)); } for (CITCondition condition : new ArrayList<>(conditions)) @@ -60,15 +61,24 @@ public class CITRegistry { siblingCondition -> siblingConditionType == siblingCondition.getClass() ? condition.modifySibling(siblingConditionType, siblingCondition) : siblingCondition); - - conditions.removeIf(Objects::isNull); + + WeightCondition weight = new WeightCondition(); + + conditions.removeIf(condition -> { + if (condition instanceof WeightCondition weightCondition) { + weight.weight = weightCondition.weight; + return true; + } + + return condition == null; + }); citType.load(conditions, properties, globalProperties); - return new CIT(properties.identifier, properties.packName, citType, conditions.toArray(new CITCondition[0])); + return new CIT(properties.identifier, properties.packName, citType, conditions.toArray(new CITCondition[0]), weight.weight); } - public static CITCondition parseCondition(PropertyGroup properties, PropertyKey key, PropertyValue value) throws CITParsingException { + public static CITCondition parseCondition(PropertyKey key, PropertyValue value, PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException { CITConditionContainer conditionContainer = CONDITIONS.get(key); if (conditionContainer == null) { logWarnLoading("Skipping condition: " + CITParsingException.descriptionOf("Unknown condition type", properties, value.position())); @@ -76,7 +86,7 @@ public class CITRegistry { } CITCondition condition = conditionContainer.createCondition.get(); - condition.load(value); + condition.load(value, properties, globalProperties); return condition; } -- cgit From f681f4f8811881b6a7b349f3b215c74a27a7ed4d Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 12 Feb 2022 18:26:07 +0200 Subject: Implemented CIT parsing/loading --- .../fabric/citresewn/defaults/types/TypeItem.java | 6 +- settings.gradle | 2 +- .../fabric/citresewn/api/CITTypeContainer.java | 4 +- .../fabric/citresewn/builtin/WeightCondition.java | 3 +- .../fabric/citresewn/pack/PackParser.java | 71 ++++++++++++++++++++-- .../fabric/citresewn/pack/cit/ActiveCITs.java | 13 ++++ .../fabric/citresewn/pack/cit/CITCondition.java | 7 +-- .../fabric/citresewn/pack/cit/CITRegistry.java | 44 +++----------- .../fabric/citresewn/pack/cit/CITType.java | 3 +- 9 files changed, 95 insertions(+), 58 deletions(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java index ec2491f..855b90e 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java @@ -3,13 +3,11 @@ package shcm.shsupercm.fabric.citresewn.defaults.types; import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.cit.CIT; import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; import shcm.shsupercm.fabric.citresewn.pack.cit.CITType; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; -import java.util.Collection; import java.util.List; public class TypeItem extends CITType { @@ -17,7 +15,7 @@ public class TypeItem extends CITType { public static final Container CONTAINER = new Container(); @Override - public void load(List conditions, PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException { + public void load(List conditions, PropertyGroup properties) throws CITParsingException { } @@ -27,7 +25,7 @@ public class TypeItem extends CITType { } @Override - public void load(Collection parsedCITs) { + public void load(List parsedCITs) { } @Override diff --git a/settings.gradle b/settings.gradle index 7a1d91c..4ab5170 100644 --- a/settings.gradle +++ b/settings.gradle @@ -8,4 +8,4 @@ pluginManagement { } } -include 'defaults', 'srcOld' \ No newline at end of file +include 'defaults' \ No newline at end of file diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java index d691ab2..e207d00 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java @@ -3,7 +3,7 @@ package shcm.shsupercm.fabric.citresewn.api; import shcm.shsupercm.fabric.citresewn.pack.cit.CIT; import shcm.shsupercm.fabric.citresewn.pack.cit.CITType; -import java.util.Collection; +import java.util.List; import java.util.function.Supplier; public abstract class CITTypeContainer implements CITDisposable { @@ -18,5 +18,5 @@ public abstract class CITTypeContainer implements CITDisposab this.id = id; } - public abstract void load(Collection parsedCITs); + public abstract void load(List parsedCITs); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java index 9882d7b..f258df4 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java @@ -3,7 +3,6 @@ package shcm.shsupercm.fabric.citresewn.builtin; import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; import shcm.shsupercm.fabric.citresewn.pack.cit.CITContext; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; @@ -16,7 +15,7 @@ public class WeightCondition extends CITCondition { public int weight = 0; @Override - public void load(PropertyValue value, PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException { + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { this.weight = parseInteger(value, properties); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 4945120..c82b505 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -2,16 +2,25 @@ package shcm.shsupercm.fabric.citresewn.pack; import net.fabricmc.fabric.impl.resource.loader.GroupResourcePack; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.resource.ResourceManager; -import net.minecraft.resource.ResourceNotFoundException; -import net.minecraft.resource.ResourcePack; -import net.minecraft.resource.ResourceType; +import net.minecraft.resource.*; import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.CITResewn; +import shcm.shsupercm.fabric.citresewn.builtin.WeightCondition; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.mixin.GroupResourcePackAccessor; +import shcm.shsupercm.fabric.citresewn.pack.cit.CIT; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITRegistry; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITType; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import java.io.IOException; +import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; @@ -47,4 +56,58 @@ public class PackParser { } }); } + + public static List loadCITs(ResourceManager resourceManager) { + List cits = new ArrayList<>(); + + for (String root : ROOTS) + for (Identifier identifier : resourceManager.findResources(root + "/cit", s -> s.endsWith(".properties"))) { + String packName = null; + try (Resource resource = resourceManager.getResource(identifier)) { + cits.add(parseCIT(PropertyGroup.tryParseGroup(packName = resource.getResourcePackName(), identifier, resource.getInputStream()))); + } catch (Exception e) { + CITResewn.logErrorLoading("Errored while loading cit: " + identifier + (packName == null ? "" : " from " + packName)); + e.printStackTrace(); + } + } + + return cits; + } + + + public static CIT parseCIT(PropertyGroup properties) throws CITParsingException { + CITType citType = CITRegistry.parseType(properties); + + ArrayList conditions = new ArrayList<>(); + + for (Map.Entry> entry : properties.properties.entrySet()) { + if (entry.getKey().path().equals("type") && entry.getKey().namespace().equals("citresewn")) + continue; + + for (PropertyValue value : entry.getValue()) + conditions.add(CITRegistry.parseCondition(entry.getKey(), value, properties)); + } + + for (CITCondition condition : new ArrayList<>(conditions)) + for (Class siblingConditionType : condition.siblingConditions()) + conditions.replaceAll( + siblingCondition -> siblingConditionType == siblingCondition.getClass() ? + condition.modifySibling(siblingConditionType, siblingCondition) : + siblingCondition); + + WeightCondition weight = new WeightCondition(); + + conditions.removeIf(condition -> { + if (condition instanceof WeightCondition weightCondition) { + weight.weight = weightCondition.weight; + return true; + } + + return condition == null; + }); + + citType.load(conditions, properties); + + return new CIT(properties.identifier, properties.packName, citType, conditions.toArray(new CITCondition[0]), weight.weight); + } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java index 62f011e..afc228c 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java @@ -7,6 +7,8 @@ import shcm.shsupercm.fabric.citresewn.api.CITDisposable; import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.PackParser; +import java.util.*; + public class ActiveCITs implements CITDisposable { private ActiveCITs() {} private static ActiveCITs active = null; @@ -20,6 +22,8 @@ public class ActiveCITs implements CITDisposable { private ActiveCITs() {} public final GlobalProperties globalProperties = new GlobalProperties(); + public final Map, List> cits = new IdentityHashMap<>(); + public static ActiveCITs load(ResourceManager resourceManager, Profiler profiler) { profiler.push("citresewn:disposing"); if (active != null) { @@ -32,6 +36,15 @@ public class ActiveCITs implements CITDisposable { private ActiveCITs() {} profiler.swap("citresewn:load_global_properties"); PackParser.loadGlobalProperties(resourceManager, active.globalProperties); active.globalProperties.callHandlers(); + + profiler.swap("citresewn:load_cits"); + for (CIT cit : PackParser.loadCITs(resourceManager)) + active.cits.computeIfAbsent(cit.type.getClass(), type -> new ArrayList<>()).add(cit); + for (Map.Entry, List> entry : active.cits.entrySet()) { + entry.getValue().sort(Comparator.comparingInt(cit -> cit.weight).reversed().thenComparing(cit -> cit.propertiesIdentifier.toString())); + CITRegistry.load(entry.getKey(), entry.getValue()); + } + profiler.pop(); return ActiveCITs.active = active; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java index 2de5be1..b5aa315 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java @@ -1,7 +1,6 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; @@ -9,11 +8,7 @@ import java.util.Collections; import java.util.Set; public abstract class CITCondition { - public abstract void load(PropertyValue value, PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException; - - public Set> acceptedTypes() { - return null; - } + public abstract void load(PropertyValue value, PropertyGroup properties) throws CITParsingException; public Set> siblingConditions() { return Collections.emptySet(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java index fe0bcc7..e24e598 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java @@ -4,10 +4,8 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; -import shcm.shsupercm.fabric.citresewn.builtin.WeightCondition; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.ex.UnknownCITTypeException; -import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; @@ -42,43 +40,15 @@ public class CITRegistry { } } - public static CIT load(PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException { - CITType citType = parseType(properties); - - ArrayList conditions = new ArrayList<>(); - - for (Map.Entry> entry : properties.properties.entrySet()) { - if (entry.getKey().path().equals("type") && entry.getKey().namespace().equals("citresewn")) - continue; - - for (PropertyValue value : entry.getValue()) - conditions.add(parseCondition(entry.getKey(), value, properties, globalProperties)); - } - - for (CITCondition condition : new ArrayList<>(conditions)) - for (Class siblingConditionType : condition.siblingConditions()) - conditions.replaceAll( - siblingCondition -> siblingConditionType == siblingCondition.getClass() ? - condition.modifySibling(siblingConditionType, siblingCondition) : - siblingCondition); - - WeightCondition weight = new WeightCondition(); - - conditions.removeIf(condition -> { - if (condition instanceof WeightCondition weightCondition) { - weight.weight = weightCondition.weight; - return true; + public static void load(Class type, List cits) { + for (CITTypeContainer typeContainer : TYPES.values()) + if (typeContainer.type == type) { + typeContainer.load(cits); + break; } - - return condition == null; - }); - - citType.load(conditions, properties, globalProperties); - - return new CIT(properties.identifier, properties.packName, citType, conditions.toArray(new CITCondition[0]), weight.weight); } - public static CITCondition parseCondition(PropertyKey key, PropertyValue value, PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException { + public static CITCondition parseCondition(PropertyKey key, PropertyValue value, PropertyGroup properties) throws CITParsingException { CITConditionContainer conditionContainer = CONDITIONS.get(key); if (conditionContainer == null) { logWarnLoading("Skipping condition: " + CITParsingException.descriptionOf("Unknown condition type", properties, value.position())); @@ -86,7 +56,7 @@ public class CITRegistry { } CITCondition condition = conditionContainer.createCondition.get(); - condition.load(value, properties, globalProperties); + condition.load(value, properties); return condition; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java index bbfa0e9..4504c01 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java @@ -1,11 +1,10 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import java.util.List; public abstract class CITType { - public abstract void load(List conditions, PropertyGroup properties, GlobalProperties globalProperties) throws CITParsingException; + public abstract void load(List conditions, PropertyGroup properties) throws CITParsingException; } -- cgit From 207048093b7727ff1dec581e6cb523a7a3086c59 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 12 Feb 2022 20:01:06 +0200 Subject: Fixed type container disposing --- .../shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java | 10 ++++++++-- .../shsupercm/fabric/citresewn/pack/cit/CITRegistry.java | 12 ++---------- 2 files changed, 10 insertions(+), 12 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java index afc228c..4d9377c 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java @@ -4,6 +4,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.resource.ResourceManager; import net.minecraft.util.profiler.Profiler; import shcm.shsupercm.fabric.citresewn.api.CITDisposable; +import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.PackParser; @@ -42,7 +43,11 @@ public class ActiveCITs implements CITDisposable { private ActiveCITs() {} active.cits.computeIfAbsent(cit.type.getClass(), type -> new ArrayList<>()).add(cit); for (Map.Entry, List> entry : active.cits.entrySet()) { entry.getValue().sort(Comparator.comparingInt(cit -> cit.weight).reversed().thenComparing(cit -> cit.propertiesIdentifier.toString())); - CITRegistry.load(entry.getKey(), entry.getValue()); + for (CITTypeContainer typeContainer : CITRegistry.TYPES.values()) + if (typeContainer.type == entry.getKey()) { + typeContainer.load(entry.getValue()); + break; + } } profiler.pop(); @@ -55,6 +60,7 @@ public class ActiveCITs implements CITDisposable { private ActiveCITs() {} for (CITDisposable disposable : FabricLoader.getInstance().getEntrypoints(CITDisposable.ENTRYPOINT, CITDisposable.class)) disposable.dispose(); - + for (CITTypeContainer typeContainer : CITRegistry.TYPES.values()) + typeContainer.dispose(); } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java index e24e598..ba61757 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java @@ -16,8 +16,8 @@ import static shcm.shsupercm.fabric.citresewn.CITResewn.info; import static shcm.shsupercm.fabric.citresewn.CITResewn.logWarnLoading; public class CITRegistry { - private static final Map> TYPES = new HashMap<>(); - private static final Map> CONDITIONS = new HashMap<>(); + public static final Map> TYPES = new HashMap<>(); + public static final Map> CONDITIONS = new HashMap<>(); public static void registerAll() { info("Registering CIT Conditions"); @@ -40,14 +40,6 @@ public class CITRegistry { } } - public static void load(Class type, List cits) { - for (CITTypeContainer typeContainer : TYPES.values()) - if (typeContainer.type == type) { - typeContainer.load(cits); - break; - } - } - public static CITCondition parseCondition(PropertyKey key, PropertyValue value, PropertyGroup properties) throws CITParsingException { CITConditionContainer conditionContainer = CONDITIONS.get(key); if (conditionContainer == null) { -- cgit From a48789c45fb474a953df65e342a3bad27fd89870 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sun, 13 Feb 2022 07:20:35 +0200 Subject: Implemented items condition --- .../defaults/cit/conditions/ConditionItems.java | 54 ++++++++++++++++++++++ .../citresewn/defaults/cit/types/TypeItem.java | 36 +++++++++++++++ .../fabric/citresewn/defaults/types/TypeItem.java | 36 --------------- .../fabric/citresewn/builtin/WeightCondition.java | 3 +- .../fabric/citresewn/pack/cit/CITCondition.java | 5 ++ 5 files changed, 97 insertions(+), 37 deletions(-) create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java delete mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java new file mode 100644 index 0000000..e010a58 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java @@ -0,0 +1,54 @@ +package shcm.shsupercm.fabric.citresewn.defaults.cit.conditions; + +import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; +import net.minecraft.item.Item; +import net.minecraft.util.Identifier; +import net.minecraft.util.InvalidIdentifierException; +import net.minecraft.util.registry.Registry; +import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +import java.util.LinkedHashSet; +import java.util.Set; + +public class ConditionItems extends CITCondition { + @Entrypoint(CITConditionContainer.ENTRYPOINT) + public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(ConditionItems.class, ConditionItems::new, + "items", "matchItems"); + + public Item[] items = new Item[0]; + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + Set items = new LinkedHashSet<>(); + + for (String entry : value.value().split(" ")) + if (!entry.isEmpty()) + try { + Identifier identifier = new Identifier(entry); + if (Registry.ITEM.containsId(identifier)) + items.add(Registry.ITEM.get(identifier)); + else { + items.add(null); + warn(identifier + " is not in the item registry", value, properties); + } + } catch (InvalidIdentifierException e) { + throw new CITParsingException("Invalid item identifier \"" + entry + "\"", properties, value.position()); + } + + this.items = items.toArray(new Item[0]); + } + + @Override + public boolean test(CITContext context) { + for (Item item : this.items) + if (context.stack.getItem() == item) + return true; + + return false; + } +} diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java new file mode 100644 index 0000000..58460aa --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -0,0 +1,36 @@ +package shcm.shsupercm.fabric.citresewn.defaults.cit.types; + +import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; +import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.cit.CIT; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.pack.cit.CITType; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; + +import java.util.List; + +public class TypeItem extends CITType { + @Entrypoint(CITTypeContainer.ENTRYPOINT) + public static final Container CONTAINER = new Container(); + + @Override + public void load(List conditions, PropertyGroup properties) throws CITParsingException { + + } + + public static class Container extends CITTypeContainer { + public Container() { + super(TypeItem.class, TypeItem::new, "item"); + } + + @Override + public void load(List parsedCITs) { + } + + @Override + public void dispose() { + + } + } +} \ No newline at end of file diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java deleted file mode 100644 index 855b90e..0000000 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/types/TypeItem.java +++ /dev/null @@ -1,36 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.defaults.types; - -import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; -import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; -import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.cit.CIT; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITType; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; - -import java.util.List; - -public class TypeItem extends CITType { - @Entrypoint(CITTypeContainer.ENTRYPOINT) - public static final Container CONTAINER = new Container(); - - @Override - public void load(List conditions, PropertyGroup properties) throws CITParsingException { - - } - - public static class Container extends CITTypeContainer { - public Container() { - super(TypeItem.class, TypeItem::new, "item"); - } - - @Override - public void load(List parsedCITs) { - } - - @Override - public void dispose() { - - } - } -} \ No newline at end of file diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java index f258df4..4161a55 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java @@ -10,7 +10,8 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; public class WeightCondition extends CITCondition { @Entrypoint(CITConditionContainer.ENTRYPOINT) - public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(WeightCondition.class, WeightCondition::new, "weight"); + public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(WeightCondition.class, WeightCondition::new, + "weight"); public int weight = 0; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java index b5aa315..c16d96a 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java @@ -1,5 +1,6 @@ package shcm.shsupercm.fabric.citresewn.pack.cit; +import shcm.shsupercm.fabric.citresewn.CITResewn; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; @@ -20,6 +21,10 @@ public abstract class CITCondition { public abstract boolean test(CITContext context); + protected void warn(String message, PropertyValue value, PropertyGroup properties) { + CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value.position())); + } + protected int parseInteger(PropertyValue value, PropertyGroup properties) throws CITParsingException { try { return Integer.parseInt(value.value()); -- cgit From 49318a4452f629274e96001700006e0b4a1464a5 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sun, 13 Feb 2022 07:52:10 +0200 Subject: Moved some stuff around --- .../defaults/cit/conditions/ConditionItems.java | 4 +- .../citresewn/defaults/cit/types/TypeItem.java | 6 +- .../shcm/shsupercm/fabric/citresewn/CITResewn.java | 2 +- .../citresewn/api/CITConditionContainer.java | 2 +- .../fabric/citresewn/api/CITTypeContainer.java | 4 +- .../fabric/citresewn/builtin/WeightCondition.java | 27 -------- .../shsupercm/fabric/citresewn/cit/ActiveCITs.java | 66 +++++++++++++++++++ .../shcm/shsupercm/fabric/citresewn/cit/CIT.java | 27 ++++++++ .../fabric/citresewn/cit/CITCondition.java | 35 +++++++++++ .../shsupercm/fabric/citresewn/cit/CITContext.java | 32 ++++++++++ .../fabric/citresewn/cit/CITRegistry.java | 73 ++++++++++++++++++++++ .../shsupercm/fabric/citresewn/cit/CITType.java | 10 +++ .../citresewn/cit/builtin/WeightCondition.java | 27 ++++++++ .../fabric/citresewn/mixin/ModelLoaderMixin.java | 2 +- .../fabric/citresewn/pack/PackParser.java | 10 +-- .../fabric/citresewn/pack/cit/ActiveCITs.java | 66 ------------------- .../shsupercm/fabric/citresewn/pack/cit/CIT.java | 27 -------- .../fabric/citresewn/pack/cit/CITCondition.java | 35 ----------- .../fabric/citresewn/pack/cit/CITContext.java | 32 ---------- .../fabric/citresewn/pack/cit/CITRegistry.java | 73 ---------------------- .../fabric/citresewn/pack/cit/CITType.java | 10 --- 21 files changed, 285 insertions(+), 285 deletions(-) delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/WeightCondition.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java index e010a58..ddd6220 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java @@ -7,8 +7,8 @@ import net.minecraft.util.InvalidIdentifierException; import net.minecraft.util.registry.Registry; import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java index 02c09d6..8e3bcbc 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -5,9 +5,9 @@ import net.minecraft.item.Item; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; import shcm.shsupercm.fabric.citresewn.defaults.cit.conditions.ConditionItems; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.cit.CIT; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITType; +import shcm.shsupercm.fabric.citresewn.cit.CIT; +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITType; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import java.util.*; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java index ce908ed..482d757 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java @@ -5,7 +5,7 @@ import net.fabricmc.api.ClientModInitializer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITRegistry; +import shcm.shsupercm.fabric.citresewn.cit.CITRegistry; public class CITResewn implements ClientModInitializer { public static final Logger LOG = LogManager.getLogger("CITResewn"); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java index 6803526..56ac01f 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java @@ -1,6 +1,6 @@ package shcm.shsupercm.fabric.citresewn.api; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; import java.util.function.Supplier; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java index e207d00..8c375bb 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java @@ -1,7 +1,7 @@ package shcm.shsupercm.fabric.citresewn.api; -import shcm.shsupercm.fabric.citresewn.pack.cit.CIT; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITType; +import shcm.shsupercm.fabric.citresewn.cit.CIT; +import shcm.shsupercm.fabric.citresewn.cit.CITType; import java.util.List; import java.util.function.Supplier; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java deleted file mode 100644 index 4161a55..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/builtin/WeightCondition.java +++ /dev/null @@ -1,27 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.builtin; - -import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; -import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; -import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITContext; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; - -public class WeightCondition extends CITCondition { - @Entrypoint(CITConditionContainer.ENTRYPOINT) - public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(WeightCondition.class, WeightCondition::new, - "weight"); - - public int weight = 0; - - @Override - public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { - this.weight = parseInteger(value, properties); - } - - @Override - public boolean test(CITContext context) { - return true; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java new file mode 100644 index 0000000..d24faf8 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java @@ -0,0 +1,66 @@ +package shcm.shsupercm.fabric.citresewn.cit; + +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.resource.ResourceManager; +import net.minecraft.util.profiler.Profiler; +import shcm.shsupercm.fabric.citresewn.api.CITDisposable; +import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; +import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; +import shcm.shsupercm.fabric.citresewn.pack.PackParser; + +import java.util.*; + +public class ActiveCITs implements CITDisposable { private ActiveCITs() {} + private static ActiveCITs active = null; + + public static ActiveCITs getActive() { + return active; + } + + public static boolean isActive() { + return active != null; + } + + public final GlobalProperties globalProperties = new GlobalProperties(); + + public final Map, List> cits = new IdentityHashMap<>(); + + public static ActiveCITs load(ResourceManager resourceManager, Profiler profiler) { + profiler.push("citresewn:disposing"); + if (active != null) { + active.dispose(); + active = null; + } + + ActiveCITs active = new ActiveCITs(); + + profiler.swap("citresewn:load_global_properties"); + PackParser.loadGlobalProperties(resourceManager, active.globalProperties); + active.globalProperties.callHandlers(); + + profiler.swap("citresewn:load_cits"); + for (CIT cit : PackParser.loadCITs(resourceManager)) + active.cits.computeIfAbsent(cit.type.getClass(), type -> new ArrayList<>()).add(cit); + for (Map.Entry, List> entry : active.cits.entrySet()) { + entry.getValue().sort(Comparator.comparingInt(cit -> cit.weight).reversed().thenComparing(cit -> cit.propertiesIdentifier.toString())); + for (CITTypeContainer typeContainer : CITRegistry.TYPES.values()) + if (typeContainer.type == entry.getKey()) { + typeContainer.load(entry.getValue()); + break; + } + } + + profiler.pop(); + + return ActiveCITs.active = active; + } + + @Override + public void dispose() { + for (CITDisposable disposable : FabricLoader.getInstance().getEntrypoints(CITDisposable.ENTRYPOINT, CITDisposable.class)) + disposable.dispose(); + + for (CITTypeContainer typeContainer : CITRegistry.TYPES.values()) + typeContainer.dispose(); + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java new file mode 100644 index 0000000..ea75c04 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java @@ -0,0 +1,27 @@ +package shcm.shsupercm.fabric.citresewn.cit; + +import net.minecraft.util.Identifier; + +public class CIT { + public final Identifier propertiesIdentifier; + public final String packName; + public final CITType type; + public final CITCondition[] conditions; + public final int weight; + + public CIT(Identifier propertiesIdentifier, String packName, CITType type, CITCondition[] conditions, int weight) { + this.propertiesIdentifier = propertiesIdentifier; + this.packName = packName; + this.type = type; + this.conditions = conditions; + this.weight = weight; + } + + public boolean test(CITContext context) { + for (CITCondition condition : conditions) + if (!condition.test(context)) + return false; + + return true; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java new file mode 100644 index 0000000..7640d3c --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java @@ -0,0 +1,35 @@ +package shcm.shsupercm.fabric.citresewn.cit; + +import shcm.shsupercm.fabric.citresewn.CITResewn; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +import java.util.Collections; +import java.util.Set; + +public abstract class CITCondition { + public abstract void load(PropertyValue value, PropertyGroup properties) throws CITParsingException; + + public Set> siblingConditions() { + return Collections.emptySet(); + } + + public T modifySibling(Class siblingType, T sibling) { + return sibling; + } + + public abstract boolean test(CITContext context); + + protected void warn(String message, PropertyValue value, PropertyGroup properties) { + CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value.position())); + } + + protected int parseInteger(PropertyValue value, PropertyGroup properties) throws CITParsingException { + try { + return Integer.parseInt(value.value()); + } catch (NumberFormatException e) { + throw new CITParsingException("\"" + value.value() + "\" is not a valid integer", properties, value.position()); + } + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java new file mode 100644 index 0000000..99cdbf0 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java @@ -0,0 +1,32 @@ +package shcm.shsupercm.fabric.citresewn.cit; + +import net.minecraft.entity.LivingEntity; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +import java.util.Objects; + +public class CITContext { + public final ItemStack stack; + public final World world; + public final LivingEntity entity; + + public CITContext(ItemStack stack, World world, LivingEntity entity) { + this.stack = stack; + this.world = world; + this.entity = entity; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof CITContext that && + Objects.equals(this.stack, that.stack) && + Objects.equals(this.world, that.world) && + Objects.equals(this.entity, that.entity); + } + + @Override + public int hashCode() { + return Objects.hash(stack, world, entity); + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java new file mode 100644 index 0000000..33f6367 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java @@ -0,0 +1,73 @@ +package shcm.shsupercm.fabric.citresewn.cit; + +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.util.Identifier; +import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; +import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.ex.UnknownCITTypeException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +import java.util.*; + +import static shcm.shsupercm.fabric.citresewn.CITResewn.info; +import static shcm.shsupercm.fabric.citresewn.CITResewn.logWarnLoading; + +public class CITRegistry { + public static final Map> TYPES = new HashMap<>(); + public static final Map> CONDITIONS = new HashMap<>(); + + public static void registerAll() { + info("Registering CIT Conditions"); + for (var entrypointContainer : FabricLoader.getInstance().getEntrypointContainers(CITConditionContainer.ENTRYPOINT, CITConditionContainer.class)) { + String namespace = entrypointContainer.getProvider().getMetadata().getId(); + if (namespace.equals("citresewn-defaults")) + namespace = "citresewn"; + + for (String alias : entrypointContainer.getEntrypoint().aliases) + CONDITIONS.put(new PropertyKey(namespace, alias), (CITConditionContainer) entrypointContainer.getEntrypoint()); + } + + info("Registering CIT Types"); + for (var entrypointContainer : FabricLoader.getInstance().getEntrypointContainers(CITTypeContainer.ENTRYPOINT, CITTypeContainer.class)) { + String namespace = entrypointContainer.getProvider().getMetadata().getId(); + if (namespace.equals("citresewn-defaults")) + namespace = "citresewn"; + + TYPES.put(new Identifier(namespace, entrypointContainer.getEntrypoint().id), (CITTypeContainer) entrypointContainer.getEntrypoint()); + } + } + + public static CITCondition parseCondition(PropertyKey key, PropertyValue value, PropertyGroup properties) throws CITParsingException { + CITConditionContainer conditionContainer = CONDITIONS.get(key); + if (conditionContainer == null) { + logWarnLoading("Skipping condition: " + CITParsingException.descriptionOf("Unknown condition type", properties, value.position())); + return null; + } + + CITCondition condition = conditionContainer.createCondition.get(); + condition.load(value, properties); + return condition; + } + + public static CITType parseType(PropertyGroup properties) throws CITParsingException { + Identifier type = new Identifier("citresewn", "item"); + + PropertyValue propertiesType = properties.getLast("citresewn", "type"); + if (propertiesType != null) { + String value = propertiesType.value(); + if (!value.contains(":")) + value = "citresewn:" + value; + type = new Identifier(value); + } + + CITTypeContainer typeContainer = TYPES.get(type); + if (typeContainer == null) + // assert (propertiesType != null) because the default citresewn:item should always be registered + throw new UnknownCITTypeException(properties, propertiesType == null ? -1 : propertiesType.position()); + + return typeContainer.createType.get(); + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java new file mode 100644 index 0000000..abbe755 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java @@ -0,0 +1,10 @@ +package shcm.shsupercm.fabric.citresewn.cit; + +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; + +import java.util.List; + +public abstract class CITType { + public abstract void load(List conditions, PropertyGroup properties) throws CITParsingException; +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/WeightCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/WeightCondition.java new file mode 100644 index 0000000..ec0a5d7 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/WeightCondition.java @@ -0,0 +1,27 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin; + +import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; +import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +public class WeightCondition extends CITCondition { + @Entrypoint(CITConditionContainer.ENTRYPOINT) + public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(WeightCondition.class, WeightCondition::new, + "weight"); + + public int weight = 0; + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + this.weight = parseInteger(value, properties); + } + + @Override + public boolean test(CITContext context) { + return true; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java index e5e000d..ea1d5ab 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java @@ -8,7 +8,7 @@ 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.CallbackInfo; -import shcm.shsupercm.fabric.citresewn.pack.cit.ActiveCITs; +import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; @Mixin(ModelLoader.class) public class ModelLoaderMixin { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index c82b505..35e8c87 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -5,13 +5,13 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.resource.*; import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.builtin.WeightCondition; +import shcm.shsupercm.fabric.citresewn.cit.builtin.WeightCondition; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.mixin.GroupResourcePackAccessor; -import shcm.shsupercm.fabric.citresewn.pack.cit.CIT; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITCondition; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITRegistry; -import shcm.shsupercm.fabric.citresewn.pack.cit.CITType; +import shcm.shsupercm.fabric.citresewn.cit.CIT; +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITRegistry; +import shcm.shsupercm.fabric.citresewn.cit.CITType; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java deleted file mode 100644 index 4d9377c..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/ActiveCITs.java +++ /dev/null @@ -1,66 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack.cit; - -import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.resource.ResourceManager; -import net.minecraft.util.profiler.Profiler; -import shcm.shsupercm.fabric.citresewn.api.CITDisposable; -import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; -import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; -import shcm.shsupercm.fabric.citresewn.pack.PackParser; - -import java.util.*; - -public class ActiveCITs implements CITDisposable { private ActiveCITs() {} - private static ActiveCITs active = null; - - public static ActiveCITs getActive() { - return active; - } - - public static boolean isActive() { - return active != null; - } - - public final GlobalProperties globalProperties = new GlobalProperties(); - - public final Map, List> cits = new IdentityHashMap<>(); - - public static ActiveCITs load(ResourceManager resourceManager, Profiler profiler) { - profiler.push("citresewn:disposing"); - if (active != null) { - active.dispose(); - active = null; - } - - ActiveCITs active = new ActiveCITs(); - - profiler.swap("citresewn:load_global_properties"); - PackParser.loadGlobalProperties(resourceManager, active.globalProperties); - active.globalProperties.callHandlers(); - - profiler.swap("citresewn:load_cits"); - for (CIT cit : PackParser.loadCITs(resourceManager)) - active.cits.computeIfAbsent(cit.type.getClass(), type -> new ArrayList<>()).add(cit); - for (Map.Entry, List> entry : active.cits.entrySet()) { - entry.getValue().sort(Comparator.comparingInt(cit -> cit.weight).reversed().thenComparing(cit -> cit.propertiesIdentifier.toString())); - for (CITTypeContainer typeContainer : CITRegistry.TYPES.values()) - if (typeContainer.type == entry.getKey()) { - typeContainer.load(entry.getValue()); - break; - } - } - - profiler.pop(); - - return ActiveCITs.active = active; - } - - @Override - public void dispose() { - for (CITDisposable disposable : FabricLoader.getInstance().getEntrypoints(CITDisposable.ENTRYPOINT, CITDisposable.class)) - disposable.dispose(); - - for (CITTypeContainer typeContainer : CITRegistry.TYPES.values()) - typeContainer.dispose(); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java deleted file mode 100644 index b4aa9fb..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CIT.java +++ /dev/null @@ -1,27 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack.cit; - -import net.minecraft.util.Identifier; - -public class CIT { - public final Identifier propertiesIdentifier; - public final String packName; - public final CITType type; - public final CITCondition[] conditions; - public final int weight; - - public CIT(Identifier propertiesIdentifier, String packName, CITType type, CITCondition[] conditions, int weight) { - this.propertiesIdentifier = propertiesIdentifier; - this.packName = packName; - this.type = type; - this.conditions = conditions; - this.weight = weight; - } - - public boolean test(CITContext context) { - for (CITCondition condition : conditions) - if (!condition.test(context)) - return false; - - return true; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java deleted file mode 100644 index c16d96a..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITCondition.java +++ /dev/null @@ -1,35 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack.cit; - -import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; - -import java.util.Collections; -import java.util.Set; - -public abstract class CITCondition { - public abstract void load(PropertyValue value, PropertyGroup properties) throws CITParsingException; - - public Set> siblingConditions() { - return Collections.emptySet(); - } - - public T modifySibling(Class siblingType, T sibling) { - return sibling; - } - - public abstract boolean test(CITContext context); - - protected void warn(String message, PropertyValue value, PropertyGroup properties) { - CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value.position())); - } - - protected int parseInteger(PropertyValue value, PropertyGroup properties) throws CITParsingException { - try { - return Integer.parseInt(value.value()); - } catch (NumberFormatException e) { - throw new CITParsingException("\"" + value.value() + "\" is not a valid integer", properties, value.position()); - } - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java deleted file mode 100644 index d8d66ad..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITContext.java +++ /dev/null @@ -1,32 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack.cit; - -import net.minecraft.entity.LivingEntity; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -import java.util.Objects; - -public class CITContext { - public final ItemStack stack; - public final World world; - public final LivingEntity entity; - - public CITContext(ItemStack stack, World world, LivingEntity entity) { - this.stack = stack; - this.world = world; - this.entity = entity; - } - - @Override - public boolean equals(Object obj) { - return obj instanceof CITContext that && - Objects.equals(this.stack, that.stack) && - Objects.equals(this.world, that.world) && - Objects.equals(this.entity, that.entity); - } - - @Override - public int hashCode() { - return Objects.hash(stack, world, entity); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java deleted file mode 100644 index ba61757..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITRegistry.java +++ /dev/null @@ -1,73 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack.cit; - -import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.util.Identifier; -import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; -import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; -import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.ex.UnknownCITTypeException; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; - -import java.util.*; - -import static shcm.shsupercm.fabric.citresewn.CITResewn.info; -import static shcm.shsupercm.fabric.citresewn.CITResewn.logWarnLoading; - -public class CITRegistry { - public static final Map> TYPES = new HashMap<>(); - public static final Map> CONDITIONS = new HashMap<>(); - - public static void registerAll() { - info("Registering CIT Conditions"); - for (var entrypointContainer : FabricLoader.getInstance().getEntrypointContainers(CITConditionContainer.ENTRYPOINT, CITConditionContainer.class)) { - String namespace = entrypointContainer.getProvider().getMetadata().getId(); - if (namespace.equals("citresewn-defaults")) - namespace = "citresewn"; - - for (String alias : entrypointContainer.getEntrypoint().aliases) - CONDITIONS.put(new PropertyKey(namespace, alias), (CITConditionContainer) entrypointContainer.getEntrypoint()); - } - - info("Registering CIT Types"); - for (var entrypointContainer : FabricLoader.getInstance().getEntrypointContainers(CITTypeContainer.ENTRYPOINT, CITTypeContainer.class)) { - String namespace = entrypointContainer.getProvider().getMetadata().getId(); - if (namespace.equals("citresewn-defaults")) - namespace = "citresewn"; - - TYPES.put(new Identifier(namespace, entrypointContainer.getEntrypoint().id), (CITTypeContainer) entrypointContainer.getEntrypoint()); - } - } - - public static CITCondition parseCondition(PropertyKey key, PropertyValue value, PropertyGroup properties) throws CITParsingException { - CITConditionContainer conditionContainer = CONDITIONS.get(key); - if (conditionContainer == null) { - logWarnLoading("Skipping condition: " + CITParsingException.descriptionOf("Unknown condition type", properties, value.position())); - return null; - } - - CITCondition condition = conditionContainer.createCondition.get(); - condition.load(value, properties); - return condition; - } - - public static CITType parseType(PropertyGroup properties) throws CITParsingException { - Identifier type = new Identifier("citresewn", "item"); - - PropertyValue propertiesType = properties.getLast("citresewn", "type"); - if (propertiesType != null) { - String value = propertiesType.value(); - if (!value.contains(":")) - value = "citresewn:" + value; - type = new Identifier(value); - } - - CITTypeContainer typeContainer = TYPES.get(type); - if (typeContainer == null) - // assert (propertiesType != null) because the default citresewn:item should always be registered - throw new UnknownCITTypeException(properties, propertiesType == null ? -1 : propertiesType.position()); - - return typeContainer.createType.get(); - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java deleted file mode 100644 index 4504c01..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/cit/CITType.java +++ /dev/null @@ -1,10 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.pack.cit; - -import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; - -import java.util.List; - -public abstract class CITType { - public abstract void load(List conditions, PropertyGroup properties) throws CITParsingException; -} -- cgit From fe02178b220ebf57225bd092bfdb0d8b88067c33 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sun, 13 Feb 2022 11:01:45 +0200 Subject: Generified CITs to their type --- .../fabric/citresewn/defaults/cit/types/TypeItem.java | 6 +++--- .../shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java | 7 ++++++- .../java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java | 10 +++++----- src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java | 6 +++--- .../fabric/citresewn/config/CITResewnConfigScreenFactory.java | 1 - .../java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java | 8 ++++---- 6 files changed, 21 insertions(+), 17 deletions(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java index 8e3bcbc..1b0e98e 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -26,11 +26,11 @@ public class TypeItem extends CITType { super(TypeItem.class, TypeItem::new, "item"); } - public Map> loaded = new IdentityHashMap<>(); + public Map>> loaded = new IdentityHashMap<>(); @Override - public void load(List parsedCITs) { - for (CIT cit : parsedCITs) + public void load(List> parsedCITs) { + for (CIT cit : parsedCITs) for (CITCondition condition : cit.conditions) if (condition instanceof ConditionItems items) for (Item item : items.items) diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java index 8c375bb..a9666d3 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java @@ -18,5 +18,10 @@ public abstract class CITTypeContainer implements CITDisposab this.id = id; } - public abstract void load(List parsedCITs); + public abstract void load(List> parsedCITs); + + @SuppressWarnings("unchecked") + public final void loadUntyped(List parsedCITs) { + load((List>) parsedCITs); + } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java index d24faf8..f54cc54 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java @@ -23,7 +23,7 @@ public class ActiveCITs implements CITDisposable { private ActiveCITs() {} public final GlobalProperties globalProperties = new GlobalProperties(); - public final Map, List> cits = new IdentityHashMap<>(); + public final Map, List>> cits = new IdentityHashMap<>(); public static ActiveCITs load(ResourceManager resourceManager, Profiler profiler) { profiler.push("citresewn:disposing"); @@ -39,13 +39,13 @@ public class ActiveCITs implements CITDisposable { private ActiveCITs() {} active.globalProperties.callHandlers(); profiler.swap("citresewn:load_cits"); - for (CIT cit : PackParser.loadCITs(resourceManager)) + for (CIT cit : PackParser.loadCITs(resourceManager)) active.cits.computeIfAbsent(cit.type.getClass(), type -> new ArrayList<>()).add(cit); - for (Map.Entry, List> entry : active.cits.entrySet()) { - entry.getValue().sort(Comparator.comparingInt(cit -> cit.weight).reversed().thenComparing(cit -> cit.propertiesIdentifier.toString())); + for (Map.Entry, List>> entry : active.cits.entrySet()) { + entry.getValue().sort(Comparator.>comparingInt(cit -> cit.weight).reversed().thenComparing(cit -> cit.propertiesIdentifier.toString())); for (CITTypeContainer typeContainer : CITRegistry.TYPES.values()) if (typeContainer.type == entry.getKey()) { - typeContainer.load(entry.getValue()); + typeContainer.loadUntyped(entry.getValue()); break; } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java index ea75c04..7cc5724 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java @@ -2,14 +2,14 @@ package shcm.shsupercm.fabric.citresewn.cit; import net.minecraft.util.Identifier; -public class CIT { +public class CIT { public final Identifier propertiesIdentifier; public final String packName; - public final CITType type; + public final T type; public final CITCondition[] conditions; public final int weight; - public CIT(Identifier propertiesIdentifier, String packName, CITType type, CITCondition[] conditions, int weight) { + public CIT(Identifier propertiesIdentifier, String packName, T type, CITCondition[] conditions, int weight) { this.propertiesIdentifier = propertiesIdentifier; this.packName = packName; this.type = type; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java index 76576ba..2d584aa 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java @@ -4,7 +4,6 @@ import me.shedaniel.clothconfig2.api.ConfigBuilder; import me.shedaniel.clothconfig2.api.ConfigCategory; import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; import net.fabricmc.loader.api.FabricLoader; -import net.fabricmc.loader.api.entrypoint.EntrypointContainer; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.text.LiteralText; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 35e8c87..7555866 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -57,8 +57,8 @@ public class PackParser { }); } - public static List loadCITs(ResourceManager resourceManager) { - List cits = new ArrayList<>(); + public static List> loadCITs(ResourceManager resourceManager) { + List> cits = new ArrayList<>(); for (String root : ROOTS) for (Identifier identifier : resourceManager.findResources(root + "/cit", s -> s.endsWith(".properties"))) { @@ -75,7 +75,7 @@ public class PackParser { } - public static CIT parseCIT(PropertyGroup properties) throws CITParsingException { + public static CIT parseCIT(PropertyGroup properties) throws CITParsingException { CITType citType = CITRegistry.parseType(properties); ArrayList conditions = new ArrayList<>(); @@ -108,6 +108,6 @@ public class PackParser { citType.load(conditions, properties); - return new CIT(properties.identifier, properties.packName, citType, conditions.toArray(new CITCondition[0]), weight.weight); + return new CIT<>(properties.identifier, properties.packName, citType, conditions.toArray(new CITCondition[0]), weight.weight); } } -- cgit From cf735c9f3205208801a9675e6b6217dc84b1ea3c Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sun, 13 Feb 2022 12:49:48 +0200 Subject: Implemented caching --- .../citresewn/defaults/cit/types/TypeItem.java | 22 ++++++++-- .../defaults/mixin/types/item/ItemStackMixin.java | 16 +++++++ .../shsupercm/fabric/citresewn/cit/CITCache.java | 50 ++++++++++++++++++++++ 3 files changed, 85 insertions(+), 3 deletions(-) create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemStackMixin.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCache.java (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java index 1b0e98e..730c713 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -3,11 +3,9 @@ package shcm.shsupercm.fabric.citresewn.defaults.cit.types; import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import net.minecraft.item.Item; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; +import shcm.shsupercm.fabric.citresewn.cit.*; import shcm.shsupercm.fabric.citresewn.defaults.cit.conditions.ConditionItems; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.cit.CIT; -import shcm.shsupercm.fabric.citresewn.cit.CITCondition; -import shcm.shsupercm.fabric.citresewn.cit.CITType; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import java.util.*; @@ -42,5 +40,23 @@ public class TypeItem extends CITType { public void dispose() { loaded.clear(); } + + public CIT getCIT(CITContext context) { + return ((CITCacheItem) (Object) context.stack).citresewn$getCacheTypeItem().get(context).get(); + } + + public CIT getRealTimeCIT(CITContext context) { + Set> loadedForItemType = loaded.get(context.stack.getItem()); + if (loadedForItemType != null) + for (CIT cit : loadedForItemType) + if (cit.test(context)) + return cit; + + return null; + } + } + + public interface CITCacheItem { + CITCache.Single citresewn$getCacheTypeItem(); } } \ No newline at end of file diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemStackMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemStackMixin.java new file mode 100644 index 0000000..450d8a3 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemStackMixin.java @@ -0,0 +1,16 @@ +package shcm.shsupercm.fabric.citresewn.defaults.mixin.types.item; + +import net.minecraft.item.ItemStack; +import org.spongepowered.asm.mixin.Mixin; +import shcm.shsupercm.fabric.citresewn.cit.CITCache; +import shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeItem; + +@Mixin(ItemStack.class) +public class ItemStackMixin implements TypeItem.CITCacheItem { + private final CITCache.Single citresewn$cacheTypeItem = new CITCache.Single<>(TypeItem.CONTAINER::getRealTimeCIT); + + @Override + public CITCache.Single citresewn$getCacheTypeItem() { + return this.citresewn$cacheTypeItem; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCache.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCache.java new file mode 100644 index 0000000..5fc6f5a --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCache.java @@ -0,0 +1,50 @@ +package shcm.shsupercm.fabric.citresewn.cit; + +import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +public abstract class CITCache { + public long lastCachedStamp = 0; + + public static class Single extends CITCache { + public WeakReference> cit = null; + public final Function> realtime; + + public Single(Function> realtime) { + this.realtime = realtime; + } + + public WeakReference> get(CITContext context) { + if (this.cit == null || System.currentTimeMillis() - this.lastCachedStamp >= CITResewnConfig.INSTANCE.cache_ms) { + this.cit = new WeakReference<>(this.realtime.apply(context)); + this.lastCachedStamp = System.currentTimeMillis(); + } + + return this.cit; + } + } + + public static class MultiList extends CITCache { + public List>> cit = null; + public final Function>> realtime; + + public MultiList(Function>> realtime) { + this.realtime = realtime; + } + + public List>> get(CITContext context) { + if (this.cit == null || System.currentTimeMillis() - this.lastCachedStamp >= CITResewnConfig.INSTANCE.cache_ms) { + this.cit = new ArrayList<>(); + for (CIT realtimeCIT : this.realtime.apply(context)) + this.cit.add(new WeakReference<>(realtimeCIT)); + this.lastCachedStamp = System.currentTimeMillis(); + } + + return cit; + } + } +} -- cgit From 32caf009812501e9e9a8f9d835726f12723c4a17 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Mon, 14 Feb 2022 15:36:15 +0200 Subject: Fixed some minor bugs --- .../shsupercm/fabric/citresewn/pack/PackParser.java | 17 ++++++++++------- .../citresewn/pack/format/PropertiesGroupAdapter.java | 2 +- 2 files changed, 11 insertions(+), 8 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 7555866..1dbc22d 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -16,6 +16,7 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -48,7 +49,7 @@ public class PackParser { Identifier identifier = new Identifier("minecraft", root + "/cit.properties"); try { globalProperties.load(pack.getName(), identifier, pack.open(ResourceType.CLIENT_RESOURCES, identifier)); - } catch (ResourceNotFoundException ignored) { + } catch (FileNotFoundException ignored) { } catch (IOException e) { CITResewn.logErrorLoading("Errored while loading global properties: " + identifier + " from " + pack.getName()); e.printStackTrace(); @@ -65,6 +66,8 @@ public class PackParser { String packName = null; try (Resource resource = resourceManager.getResource(identifier)) { cits.add(parseCIT(PropertyGroup.tryParseGroup(packName = resource.getResourcePackName(), identifier, resource.getInputStream()))); + } catch (CITParsingException e) { + CITResewn.logErrorLoading(e.getMessage()); } catch (Exception e) { CITResewn.logErrorLoading("Errored while loading cit: " + identifier + (packName == null ? "" : " from " + packName)); e.printStackTrace(); @@ -74,7 +77,6 @@ public class PackParser { return cits; } - public static CIT parseCIT(PropertyGroup properties) throws CITParsingException { CITType citType = CITRegistry.parseType(properties); @@ -89,11 +91,12 @@ public class PackParser { } for (CITCondition condition : new ArrayList<>(conditions)) - for (Class siblingConditionType : condition.siblingConditions()) - conditions.replaceAll( - siblingCondition -> siblingConditionType == siblingCondition.getClass() ? - condition.modifySibling(siblingConditionType, siblingCondition) : - siblingCondition); + if (condition != null) + for (Class siblingConditionType : condition.siblingConditions()) + conditions.replaceAll( + siblingCondition -> siblingConditionType == siblingCondition.getClass() ? + condition.modifySibling(siblingConditionType, siblingCondition) : + siblingCondition); WeightCondition weight = new WeightCondition(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java index fb694ae..8ad2ccf 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java @@ -93,7 +93,7 @@ public class PropertiesGroupAdapter extends PropertyGroup { builder.append(c); } - if (key == null) + if (key == null) //todo handle : separator throw new IOException("Missing separator in line " + linePos); int pos = linePos - multilineSkip; -- cgit From 972e6c330d03f205ab738ed28c4e47496f30e92d Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Tue, 15 Feb 2022 12:21:57 +0200 Subject: Ported item type (missing asset resolution) --- .../citresewn/defaults/cit/types/TypeItem.java | 440 ++++++++++++++++++++- .../defaults/common/ResewnItemModelIdentifier.java | 16 + .../defaults/common/ResewnTextureIdentifier.java | 12 + .../mixin/common/SpriteAtlasTextureMixin.java | 18 + .../mixin/types/item/ItemRendererMixin.java | 83 ++++ .../defaults/mixin/types/item/ItemStackMixin.java | 12 + .../mixin/types/item/JsonUnbakedModelAccessor.java | 22 ++ .../mixin/types/item/ModelLoaderMixin.java | 165 ++++++++ .../resources/citresewn-defaults.accesswidener | 26 ++ .../shsupercm/fabric/citresewn/cit/CITContext.java | 3 +- .../fabric/citresewn/cit/CITRegistry.java | 2 +- .../shsupercm/fabric/citresewn/cit/CITType.java | 6 + .../fabric/citresewn/ex/CITParsingException.java | 2 +- .../citresewn/pack/format/PropertyGroup.java | 6 +- src/main/resources/citresewn.accesswidener | 30 +- 15 files changed, 807 insertions(+), 36 deletions(-) create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/common/ResewnItemModelIdentifier.java create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/common/ResewnTextureIdentifier.java create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/common/SpriteAtlasTextureMixin.java create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemRendererMixin.java create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/JsonUnbakedModelAccessor.java create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java index 730c713..14b8813 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -1,22 +1,449 @@ package shcm.shsupercm.fabric.citresewn.defaults.cit.types; +import com.google.common.collect.ImmutableMap; +import com.mojang.datafixers.util.Either; import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; +import it.unimi.dsi.fastutil.objects.Object2IntMap; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import net.minecraft.client.render.model.BakedModel; +import net.minecraft.client.render.model.json.JsonUnbakedModel; +import net.minecraft.client.render.model.json.ModelOverride; +import net.minecraft.client.render.model.json.ModelOverrideList; +import net.minecraft.client.render.model.json.ModelTransformation; +import net.minecraft.client.texture.SpriteAtlasTexture; +import net.minecraft.client.util.SpriteIdentifier; +import net.minecraft.client.world.ClientWorld; import net.minecraft.item.Item; +import net.minecraft.item.Items; +import net.minecraft.resource.Resource; +import net.minecraft.resource.ResourceManager; +import net.minecraft.resource.ResourceType; +import net.minecraft.util.Identifier; +import net.minecraft.util.registry.Registry; +import org.apache.commons.io.IOUtils; +import shcm.shsupercm.fabric.citresewn.CITResewn; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; import shcm.shsupercm.fabric.citresewn.cit.*; import shcm.shsupercm.fabric.citresewn.defaults.cit.conditions.ConditionItems; +import shcm.shsupercm.fabric.citresewn.defaults.common.ResewnItemModelIdentifier; +import shcm.shsupercm.fabric.citresewn.defaults.common.ResewnTextureIdentifier; +import shcm.shsupercm.fabric.citresewn.defaults.mixin.types.item.JsonUnbakedModelAccessor; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; import java.util.*; +import java.util.stream.Collectors; public class TypeItem extends CITType { @Entrypoint(CITTypeContainer.ENTRYPOINT) public static final Container CONTAINER = new Container(); + private static final String GENERATED_SUB_CITS_PREFIX = "sub_cititem_generated_"; + public static final Set GENERATED_SUB_CITS_SEEN = new HashSet<>(); + + private final List items = new ArrayList<>(); + + public Map assetIdentifiers = new LinkedHashMap<>(); + public Map, JsonUnbakedModel> unbakedAssets = new LinkedHashMap<>(); + private Map> textureOverrideMap = new HashMap<>(); + private boolean isTexture = false; + + public BakedModel bakedModel = null; + public CITOverrideList bakedSubModels = new CITOverrideList(); + @Override public void load(List conditions, PropertyGroup properties) throws CITParsingException { + for (CITCondition condition : conditions) + if (condition instanceof ConditionItems conditionItems) + items.addAll(Arrays.asList(conditionItems.items)); + + if (this.items.size() == 0) + throw new CITParsingException("Not targeting any item type", properties, -1); + + Identifier assetIdentifier; + PropertyValue modelProp = properties.getLastWithoutMetadata("citresewn", "model"); + boolean containsTexture = modelProp == null && !properties.get("citresewn", "texture", "tile").isEmpty(); + + if (!containsTexture) { + assetIdentifier = resolvePath(identifier, modelProp, ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + if (assetIdentifier != null) + assetIdentifiers.put(null, assetIdentifier); + else if (modelProp != null) { + assetIdentifier = resolvePath(identifier, modelProp, ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + if (assetIdentifier != null) + assetIdentifiers.put(null, assetIdentifier); + } + } + + for (PropertyValue property : properties.get("citresewn", "model")) { + Identifier subIdentifier = resolvePath(identifier, properties.getProperty(property), ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + if (subIdentifier == null) + throw new CITParsingException("Cannot resolve path", properties, property.position()); + + String subItem = property.keyMetadata(); + Identifier subItemIdentifier = fixDeprecatedSubItem(subItem, properties, property.position()); + assetIdentifiers.put(subItemIdentifier == null ? new Identifier("minecraft", "item/" + subItem) : subItemIdentifier, subIdentifier); + } + if (assetIdentifiers.size() == 0) { // attempt to load texture + isTexture = true; + PropertyValue textureProp = properties.getLastWithoutMetadata("citresewn", "texture", "tile"); + assetIdentifier = resolvePath(identifier, textureProp, ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + if (assetIdentifier != null) + assetIdentifiers.put(null, assetIdentifier); + + for (PropertyValue property : properties.get("citresewn", "texture", "tile")) { + Identifier subIdentifier = resolvePath(identifier, properties.getProperty(property), ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + if (subIdentifier == null) + throw new CITParsingException("Cannot resolve path", properties, property.position()); + + String subItem = property.keyMetadata(); + Identifier subItemIdentifier = fixDeprecatedSubItem(subItem, properties, property.position()); + assetIdentifiers.put(subItemIdentifier == null ? new Identifier("minecraft", "item/" + subItem) : subItemIdentifier, subIdentifier); + } + } else { // attempt to load textureOverrideMap from textures + PropertyValue textureProp = properties.getLastWithoutMetadata("citresewn", "texture", "tile"); + if (textureProp != null) { + assetIdentifier = resolvePath(identifier, textureProp, ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + if (assetIdentifier != null) + textureOverrideMap.put(null, Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(assetIdentifier)))); + else + throw new CITParsingException("Cannot resolve path", properties, textureProp.position()); + } + + for (PropertyValue property : properties.get("citresewn", "texture", "tile")) { + textureProp = property; + Identifier subIdentifier = resolvePath(identifier, textureProp, ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + if (subIdentifier == null) + throw new CITParsingException("Cannot resolve path", properties, property.position()); + + textureOverrideMap.put(property.keyMetadata(), Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(subIdentifier)))); + } + } + + if (assetIdentifiers.size() == 0) + throw new CITParsingException("Could not resolve a replacement model/texture", properties, -1); + } + + public void loadUnbakedAssets(ResourceManager resourceManager) throws Exception { + try { + if (isTexture) { + JsonUnbakedModel itemJson = getModelForFirstItemType(resourceManager); + if (((JsonUnbakedModelAccessor) itemJson).getTextureMap().size() > 1) { // use(some/all of) the asset identifiers to build texture override in layered models + textureOverrideMap = ((JsonUnbakedModelAccessor) itemJson).getTextureMap(); + Identifier defaultAsset = assetIdentifiers.get(null); + textureOverrideMap.replaceAll((layerName, originalTextureEither) -> { + Identifier textureIdentifier = assetIdentifiers.remove(originalTextureEither.map(SpriteIdentifier::getTextureId, Identifier::new)); + if (textureIdentifier != null) + return Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(textureIdentifier))); + if (defaultAsset != null) + return Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(defaultAsset))); + return null; + }); + + if (assetIdentifiers.size() == 0 || (assetIdentifiers.size() == 1 && assetIdentifiers.containsKey(null))) { + unbakedAssets.put(null, itemJson); + return; + } + } + + Identifier baseIdentifier = assetIdentifiers.remove(null); + + if (baseIdentifier != null) + unbakedAssets.put(null, loadUnbakedAsset(resourceManager, baseIdentifier)); + + if (!assetIdentifiers.isEmpty()) { // contains sub models + LinkedHashMap> overrideConditions = new LinkedHashMap<>(); + for (Item item : this.items) { + Identifier itemIdentifier = Registry.ITEM.getId(item); + overrideConditions.put(new Identifier(itemIdentifier.getNamespace(), "item/" + itemIdentifier.getPath()), Collections.emptyList()); + + Identifier itemModelIdentifier = new Identifier(itemIdentifier.getNamespace(), "models/item/" + itemIdentifier.getPath() + ".json"); + try (Resource itemModelResource = resourceManager.getResource(itemModelIdentifier); Reader resourceReader = new InputStreamReader(itemModelResource.getInputStream())) { + JsonUnbakedModel itemModelJson = JsonUnbakedModel.deserialize(resourceReader); + + if (itemModelJson.getOverrides() != null && !itemModelJson.getOverrides().isEmpty()) + for (ModelOverride override : itemModelJson.getOverrides()) + overrideConditions.put(override.getModelId(), override.streamConditions().toList()); + } + } + + ArrayList overrideModels = new ArrayList<>(overrideConditions.keySet()); + Collections.reverse(overrideModels); + + for (Identifier overrideModel : overrideModels) { + Identifier replacement = assetIdentifiers.remove(overrideModel); + if (replacement == null) + continue; + + List conditions = overrideConditions.get(overrideModel); + unbakedAssets.put(conditions, loadUnbakedAsset(resourceManager, replacement)); + } + } + } else { // isModel + Identifier baseIdentifier = assetIdentifiers.remove(null); + + if (baseIdentifier != null) { + if (!GENERATED_SUB_CITS_SEEN.add(baseIdentifier)) // cit generated duplicate + baseIdentifier = new Identifier(baseIdentifier.getNamespace(), GENERATED_SUB_CITS_PREFIX + GENERATED_SUB_CITS_SEEN.size() + "_" + baseIdentifier.getPath()); + GENERATED_SUB_CITS_SEEN.add(baseIdentifier); + + JsonUnbakedModel model = loadUnbakedAsset(resourceManager, baseIdentifier); + unbakedAssets.put(null, model); + + if (model.getOverrides().size() > 0 && textureOverrideMap.size() > 0) { + LinkedHashMap> overrideConditions = new LinkedHashMap<>(); + + for (ModelOverride override : model.getOverrides()) + overrideConditions.put(override.getModelId(), override.streamConditions().toList()); + + ArrayList overrideModels = new ArrayList<>(overrideConditions.keySet()); + Collections.reverse(overrideModels); + + for (Identifier overrideModel : overrideModels) { + Identifier replacement = resolvePath(baseIdentifier, overrideModel.toString(), ".json", resourceManager::containsResource); + if (replacement != null) { + String subTexturePath = replacement.toString().substring(0, replacement.toString().lastIndexOf('.')); + final String subTextureName = subTexturePath.substring(subTexturePath.lastIndexOf('/') + 1); + + replacement = baseIdentifier; + if (!GENERATED_SUB_CITS_SEEN.add(replacement)) // cit generated duplicate + replacement = new Identifier(replacement.getNamespace(), GENERATED_SUB_CITS_PREFIX + GENERATED_SUB_CITS_SEEN.size() + "_" + replacement.getPath()); + GENERATED_SUB_CITS_SEEN.add(replacement); + + JsonUnbakedModel jsonModel = loadUnbakedAsset(resourceManager, replacement); + jsonModel.getOverrides().clear(); + + ((JsonUnbakedModelAccessor) jsonModel).getTextureMap().replaceAll((layerName, texture) -> { + if (layerName != null) + try { + for (String subTexture : textureOverrideMap.keySet()) + if (subTextureName.equals(subTexture)) + return textureOverrideMap.get(subTexture); + } catch (Exception ignored) { } + return texture; + }); + + unbakedAssets.put(overrideConditions.get(overrideModel), jsonModel); + } + } + } + } + + if (!assetIdentifiers.isEmpty()) { // contains sub models + LinkedHashMap> overrideConditions = new LinkedHashMap<>(); + for (Item item : this.items) { + Identifier itemIdentifier = Registry.ITEM.getId(item); + overrideConditions.put(new Identifier(itemIdentifier.getNamespace(), "item/" + itemIdentifier.getPath()), Collections.emptyList()); + + Identifier itemModelIdentifier = new Identifier(itemIdentifier.getNamespace(), "models/item/" + itemIdentifier.getPath() + ".json"); + try (Resource itemModelResource = resourceManager.getResource(itemModelIdentifier); Reader resourceReader = new InputStreamReader(itemModelResource.getInputStream())) { + JsonUnbakedModel itemModelJson = JsonUnbakedModel.deserialize(resourceReader); + + if (itemModelJson.getOverrides() != null && !itemModelJson.getOverrides().isEmpty()) + for (ModelOverride override : itemModelJson.getOverrides()) + overrideConditions.put(override.getModelId(), override.streamConditions().toList()); + } + } + + ArrayList overrideModels = new ArrayList<>(overrideConditions.keySet()); + Collections.reverse(overrideModels); + + for (Identifier overrideModel : overrideModels) { + Identifier replacement = assetIdentifiers.remove(overrideModel); + if (replacement == null) + continue; + + if (!GENERATED_SUB_CITS_SEEN.add(replacement)) // cit generated duplicate + replacement = new Identifier(replacement.getNamespace(), GENERATED_SUB_CITS_PREFIX + GENERATED_SUB_CITS_SEEN.size() + "_" + replacement.getPath()); + GENERATED_SUB_CITS_SEEN.add(replacement); + + List conditions = overrideConditions.get(overrideModel); + unbakedAssets.put(conditions, loadUnbakedAsset(resourceManager, replacement)); + } + } + } + } finally { + assetIdentifiers = null; + textureOverrideMap = null; + } + } + + private JsonUnbakedModel loadUnbakedAsset(ResourceManager resourceManager, Identifier assetIdentifier) throws Exception { + final Identifier identifier; + { + Identifier possibleIdentifier = assetIdentifier; + while (possibleIdentifier.getPath().startsWith(GENERATED_SUB_CITS_PREFIX)) + possibleIdentifier = new Identifier(possibleIdentifier.getNamespace(), possibleIdentifier.getPath().substring(possibleIdentifier.getPath().substring(GENERATED_SUB_CITS_PREFIX.length()).indexOf('_') + GENERATED_SUB_CITS_PREFIX.length() + 1)); + identifier = possibleIdentifier; + } + JsonUnbakedModel json; + if (identifier.getPath().endsWith(".json")) { + InputStream is = null; + Resource resource = null; + try { + json = JsonUnbakedModel.deserialize(IOUtils.toString(is = (resource = resourceManager.getResource(identifier)).getInputStream(), StandardCharsets.UTF_8)); + json.id = assetIdentifier.toString(); + json.id = json.id.substring(0, json.id.length() - 5); + + ((JsonUnbakedModelAccessor) json).getTextureMap().replaceAll((layer, original) -> { + Optional left = original.left(); + if (left.isPresent()) { + Identifier resolvedIdentifier = resolvePath(identifier, left.get().getTextureId().getPath(), ".png", resourceManager::containsResource); + if (resolvedIdentifier != null) + return Either.left(new SpriteIdentifier(left.get().getAtlasId(), new ResewnTextureIdentifier(resolvedIdentifier))); + } + return original; + }); + + if (textureOverrideMap.size() > 0) { + Map> jsonTextureMap = ((JsonUnbakedModelAccessor) json).getTextureMap(); + if (jsonTextureMap.size() == 0) + jsonTextureMap.put("layer0", null); + + final Either defaultTextureOverride = textureOverrideMap.get(null); + if (defaultTextureOverride != null) + jsonTextureMap.replaceAll((layerName, spriteIdentifierStringEither) -> defaultTextureOverride); + + //jsonTextureMap.putAll(textureOverrideMap); + jsonTextureMap.replaceAll((layerName, texture) -> { + if (layerName != null) + try { + String[] split = texture.map(id -> id.getTextureId().getPath(), s -> s).split("/"); + String textureName = split[split.length - 1]; + if (textureName.endsWith(".png")) + textureName = textureName.substring(0, textureName.length() - 4); + return Objects.requireNonNull(textureOverrideMap.get(textureName)); + } catch (Exception ignored) { } + return texture; + }); + jsonTextureMap.values().removeIf(Objects::isNull); + } + + Identifier parentId = ((JsonUnbakedModelAccessor) json).getParentId(); + if (parentId != null) { + String[] parentIdPathSplit = parentId.getPath().split("/"); + if (parentId.getPath().startsWith("./") || (parentIdPathSplit.length > 2 && parentIdPathSplit[1].equals("cit"))) { + parentId = resolvePath(identifier, parentId.getPath(), ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + if (parentId != null) + ((JsonUnbakedModelAccessor) json).setParentId(new ResewnItemModelIdentifier(parentId)); + } + } + + json.getOverrides().replaceAll(override -> { + String[] modelIdPathSplit = override.getModelId().getPath().split("/"); + if (override.getModelId().getPath().startsWith("./") || (modelIdPathSplit.length > 2 && modelIdPathSplit[1].equals("cit"))) { + Identifier resolvedOverridePath = resolvePath(identifier, override.getModelId().getPath(), ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + if (resolvedOverridePath != null) + return new ModelOverride(new ResewnItemModelIdentifier(resolvedOverridePath), override.streamConditions().collect(Collectors.toList())); + } + + return override; + }); + + return json; + } finally { + IOUtils.closeQuietly(is, resource); + } + } else if (identifier.getPath().endsWith(".png")) { + json = getModelForFirstItemType(resourceManager); + if (json == null) + json = new JsonUnbakedModel(new Identifier("minecraft", "item/generated"), new ArrayList<>(), ImmutableMap.of("layer0", Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(identifier)))), true, JsonUnbakedModel.GuiLight.ITEM, ModelTransformation.NONE, new ArrayList<>()); + json.getOverrides().clear(); + json.id = identifier.toString(); + json.id = json.id.substring(0, json.id.length() - 4); + + ((JsonUnbakedModelAccessor) json).getTextureMap().replaceAll((layerName, originalTextureEither) -> { + if (textureOverrideMap.size() > 0) { + Either textureOverride = textureOverrideMap.get(layerName); + if (textureOverride == null) + textureOverride = textureOverrideMap.get(null); + return textureOverride == null ? originalTextureEither : textureOverride; + } else + return Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(identifier))); + }); + return json; + } + + throw new Exception("Unknown asset type"); + } + + public Identifier fixDeprecatedSubItem(String subItem, PropertyGroup properties, int position) { + String replacement = switch (subItem) { + case "bow_pulling_standby" -> "bow"; + case "crossbow_standby" -> "crossbow"; + case "potion_bottle_drinkable" -> "potion"; + case "potion_bottle_splash" -> "splash_potion"; + case "potion_bottle_lingering" -> "lingering_potion"; + + + default -> null; + }; + + if (replacement != null) { + CITResewn.logWarnLoading(CITParsingException.descriptionOf("Warning: Using deprecated sub item id \"" + subItem + "\" instead of \"" + replacement + "\"", properties, position)); + + return new Identifier("minecraft", "item/" + replacement); + } + + return null; + } + + private JsonUnbakedModel getModelForFirstItemType(ResourceManager resourceManager) { + Identifier firstItemIdentifier = Registry.ITEM.getId(this.items.iterator().next()), firstItemModelIdentifier = new Identifier(firstItemIdentifier.getNamespace(), "models/item/" + firstItemIdentifier.getPath() + ".json"); + Resource itemModelResource = null; + try { + JsonUnbakedModel json = JsonUnbakedModel.deserialize(IOUtils.toString((itemModelResource = resourceManager.getResource(firstItemModelIdentifier)).getInputStream(), StandardCharsets.UTF_8)); + + if (!GENERATED_SUB_CITS_SEEN.add(firstItemModelIdentifier)) // cit generated duplicate + firstItemModelIdentifier = new Identifier(firstItemModelIdentifier.getNamespace(), GENERATED_SUB_CITS_PREFIX + GENERATED_SUB_CITS_SEEN.size() + "_" + firstItemModelIdentifier.getPath()); + GENERATED_SUB_CITS_SEEN.add(firstItemModelIdentifier); + + json.id = firstItemModelIdentifier.toString(); + json.id = json.id.substring(0, json.id.length() - 5); + return json; + } catch (Exception e) { + return null; + } finally { + IOUtils.closeQuietly(itemModelResource); + } + } + + public BakedModel getItemModel(CITContext context, int seed) { + // get sub items or bakedModel if no sub item matches @Nullable + BakedModel bakedModel = bakedSubModels.apply(this.bakedModel, context.stack, (ClientWorld) context.world, context.entity, seed); + + // apply model overrides + if (bakedModel != null && bakedModel.getOverrides() != null) + bakedModel = bakedModel.getOverrides().apply(bakedModel, context.stack, (ClientWorld) context.world, context.entity, seed); + + return bakedModel; + } + + public static class CITOverrideList extends ModelOverrideList { + public void override(List key, BakedModel bakedModel) { + Set conditionTypes = new LinkedHashSet<>(Arrays.asList(this.conditionTypes)); + for (ModelOverride.Condition condition : key) + conditionTypes.add(condition.getType()); + this.conditionTypes = conditionTypes.toArray(new Identifier[0]); + + this.overrides = Arrays.copyOf(this.overrides, this.overrides.length + 1); + + Object2IntMap object2IntMap = new Object2IntOpenHashMap<>(); + for(int i = 0; i < this.conditionTypes.length; ++i) + object2IntMap.put(this.conditionTypes[i], i); + + this.overrides[this.overrides.length - 1] = new BakedOverride( + key.stream() + .map((condition) -> new InlinedCondition(object2IntMap.getInt(condition.getType()), condition.getThreshold())) + .toArray(InlinedCondition[]::new) + , bakedModel); + } } public static class Container extends CITTypeContainer { @@ -41,16 +468,22 @@ public class TypeItem extends CITType { loaded.clear(); } - public CIT getCIT(CITContext context) { + public CIT getCIT(CITContext context, int seed) { return ((CITCacheItem) (Object) context.stack).citresewn$getCacheTypeItem().get(context).get(); } public CIT getRealTimeCIT(CITContext context) { + ((CITCacheItem) (Object) context.stack).citresewn$setMojankCITTypeItem(false); + Set> loadedForItemType = loaded.get(context.stack.getItem()); if (loadedForItemType != null) for (CIT cit : loadedForItemType) - if (cit.test(context)) + if (cit.test(context)) { + if (context.stack.isOf(Items.TRIDENT) || context.stack.isOf(Items.SPYGLASS)) + ((CITCacheItem) (Object) context.stack).citresewn$setMojankCITTypeItem(true); + return cit; + } return null; } @@ -58,5 +491,8 @@ public class TypeItem extends CITType { public interface CITCacheItem { CITCache.Single citresewn$getCacheTypeItem(); + + boolean citresewn$isMojankCITTypeItem(); + void citresewn$setMojankCITTypeItem(boolean mojankCIT); } } \ No newline at end of file diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/common/ResewnItemModelIdentifier.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/common/ResewnItemModelIdentifier.java new file mode 100644 index 0000000..c3f30f5 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/common/ResewnItemModelIdentifier.java @@ -0,0 +1,16 @@ +package shcm.shsupercm.fabric.citresewn.defaults.common; + +import net.minecraft.util.Identifier; + +/** + * Marks models as cit item models. + */ +public class ResewnItemModelIdentifier extends Identifier { + public ResewnItemModelIdentifier(String id) { + super(id); + } + + public ResewnItemModelIdentifier(Identifier identifier) { + super(identifier.getNamespace(), identifier.getPath()); + } +} diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/common/ResewnTextureIdentifier.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/common/ResewnTextureIdentifier.java new file mode 100644 index 0000000..a6dd2ef --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/common/ResewnTextureIdentifier.java @@ -0,0 +1,12 @@ +package shcm.shsupercm.fabric.citresewn.defaults.common; + +import net.minecraft.util.Identifier; + +/** + * Marks path identifiers as forced literal texture paths. + */ +public class ResewnTextureIdentifier extends Identifier { + public ResewnTextureIdentifier(Identifier identifier) { + super(identifier.getNamespace(), identifier.getPath()); + } +} diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/common/SpriteAtlasTextureMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/common/SpriteAtlasTextureMixin.java new file mode 100644 index 0000000..61eff5c --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/common/SpriteAtlasTextureMixin.java @@ -0,0 +1,18 @@ +package shcm.shsupercm.fabric.citresewn.defaults.mixin.common; + +import net.minecraft.client.texture.SpriteAtlasTexture; +import net.minecraft.util.Identifier; +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; +import shcm.shsupercm.fabric.citresewn.defaults.common.ResewnTextureIdentifier; + +@Mixin(SpriteAtlasTexture.class) +public class SpriteAtlasTextureMixin { + @Inject(method = "getTexturePath", cancellable = true, at = @At("HEAD")) + public void forceLiteralResewnTextureIdentifier(Identifier id, CallbackInfoReturnable cir) { + if (id instanceof ResewnTextureIdentifier) + cir.setReturnValue(id); + } +} diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemRendererMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemRendererMixin.java new file mode 100644 index 0000000..9f6063b --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemRendererMixin.java @@ -0,0 +1,83 @@ +package shcm.shsupercm.fabric.citresewn.defaults.mixin.types.item; + +import net.minecraft.client.render.VertexConsumerProvider; +import net.minecraft.client.render.item.ItemModels; +import net.minecraft.client.render.item.ItemRenderer; +import net.minecraft.client.render.model.BakedModel; +import net.minecraft.client.render.model.json.ModelTransformation; +import net.minecraft.client.util.ModelIdentifier; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.entity.LivingEntity; +import net.minecraft.item.ItemStack; +import net.minecraft.item.Items; +import net.minecraft.world.World; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; +import shcm.shsupercm.fabric.citresewn.cit.CIT; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; +import shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeItem; + +import java.lang.ref.WeakReference; + +import static shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeItem.CONTAINER; + +@Mixin(ItemRenderer.class) +public class ItemRendererMixin { + @Shadow @Final private ItemModels models; + + private static WeakReference mojankCITModel = null; + + @Inject(method = "getModel", cancellable = true, at = @At("HEAD")) + private void citresewn$getItemModel(ItemStack stack, World world, LivingEntity entity, int seed, CallbackInfoReturnable cir) { + if (!CITResewnConfig.INSTANCE.enabled || !ActiveCITs.isActive()) + return; + + CITContext context = new CITContext(stack, world, entity); + CIT cit = CONTAINER.getCIT(context, seed); + if (cit != null) { + BakedModel citModel = cit.type.getItemModel(context, seed); + + if (citModel != null) + cir.setReturnValue(citModel); + } + } + + @Inject(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;IILnet/minecraft/client/render/model/BakedModel;)V", at = @At("HEAD")) + private void citresewn$fixMojankCITsContext(ItemStack stack, ModelTransformation.Mode renderMode, boolean leftHanded, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay, BakedModel model, CallbackInfo ci) { + if (!CITResewnConfig.INSTANCE.enabled || !ActiveCITs.isActive()) + return; + + mojankCITModel = null; + if (((TypeItem.CITCacheItem) (Object) stack).citresewn$isMojankCITTypeItem()) { + boolean bl = renderMode == ModelTransformation.Mode.GUI || renderMode == ModelTransformation.Mode.GROUND || renderMode == ModelTransformation.Mode.FIXED; + if (bl) + mojankCITModel = new WeakReference<>(model); + else { // rendered in hand model of trident/spyglass + if (stack.isOf(Items.TRIDENT)) + mojankCITModel = new WeakReference<>(this.models.getModelManager().getModel(new ModelIdentifier("minecraft:trident_in_hand#inventory"))); + else if (stack.isOf(Items.SPYGLASS)) + mojankCITModel = new WeakReference<>(this.models.getModelManager().getModel(new ModelIdentifier("minecraft:spyglass_in_hand#inventory"))); + } + } else + mojankCITModel = null; + } + + @ModifyVariable(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;IILnet/minecraft/client/render/model/BakedModel;)V", at = @At(value = "LOAD", ordinal = 0, target = "Lnet/minecraft/client/render/model/BakedModel;getTransformation()Lnet/minecraft/client/render/model/json/ModelTransformation;"), argsOnly = true) + private BakedModel citresewn$fixMojankCITs(BakedModel original) { + if (!CITResewnConfig.INSTANCE.enabled || !ActiveCITs.isActive()) + return original; + + if (mojankCITModel != null) + return mojankCITModel.get(); + + return original; + } +} diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemStackMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemStackMixin.java index 450d8a3..2fb5396 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemStackMixin.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemStackMixin.java @@ -9,8 +9,20 @@ import shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeItem; public class ItemStackMixin implements TypeItem.CITCacheItem { private final CITCache.Single citresewn$cacheTypeItem = new CITCache.Single<>(TypeItem.CONTAINER::getRealTimeCIT); + private boolean citresewn$mojankCITTypeItem = false; + @Override public CITCache.Single citresewn$getCacheTypeItem() { return this.citresewn$cacheTypeItem; } + + @Override + public boolean citresewn$isMojankCITTypeItem() { + return this.citresewn$mojankCITTypeItem; + } + + @Override + public void citresewn$setMojankCITTypeItem(boolean mojankCITTypeItem) { + this.citresewn$mojankCITTypeItem = mojankCITTypeItem; + } } diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/JsonUnbakedModelAccessor.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/JsonUnbakedModelAccessor.java new file mode 100644 index 0000000..350d01a --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/JsonUnbakedModelAccessor.java @@ -0,0 +1,22 @@ +package shcm.shsupercm.fabric.citresewn.defaults.mixin.types.item; + +import com.mojang.datafixers.util.Either; +import net.minecraft.client.render.model.json.JsonUnbakedModel; +import net.minecraft.client.util.SpriteIdentifier; +import net.minecraft.util.Identifier; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +import java.util.Map; + +@Mixin(JsonUnbakedModel.class) +public interface JsonUnbakedModelAccessor { + @Accessor + Map> getTextureMap(); + + @Accessor + Identifier getParentId(); + + @Accessor + void setParentId(Identifier parentId); +} diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java new file mode 100644 index 0000000..22e9373 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java @@ -0,0 +1,165 @@ +package shcm.shsupercm.fabric.citresewn.defaults.mixin.types.item; + +import com.mojang.datafixers.util.Either; +import net.minecraft.client.render.model.BakedModel; +import net.minecraft.client.render.model.ModelLoader; +import net.minecraft.client.render.model.SpriteAtlasManager; +import net.minecraft.client.render.model.UnbakedModel; +import net.minecraft.client.render.model.json.JsonUnbakedModel; +import net.minecraft.client.render.model.json.ModelOverride; +import net.minecraft.client.texture.TextureManager; +import net.minecraft.client.util.ModelIdentifier; +import net.minecraft.client.util.SpriteIdentifier; +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 org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import shcm.shsupercm.fabric.citresewn.CITResewn; +import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; +import shcm.shsupercm.fabric.citresewn.cit.CITType; +import shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeItem; +import shcm.shsupercm.fabric.citresewn.defaults.common.ResewnItemModelIdentifier; +import shcm.shsupercm.fabric.citresewn.defaults.common.ResewnTextureIdentifier; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.stream.Collectors; + +import static shcm.shsupercm.fabric.citresewn.CITResewn.info; +import static shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeItem.CONTAINER; + +@Mixin(ModelLoader.class) +public class ModelLoaderMixin { + @Shadow @Final private ResourceManager resourceManager; + @Shadow @Final private Set modelsToLoad; + @Shadow @Final private Map modelsToBake; + @Shadow @Final private Map unbakedModels; + @Shadow @Final private Map bakedModels; + + @Inject(method = "addModel", at = @At("TAIL")) + public void citresewn$addTypeItemModels(ModelIdentifier eventModelId, CallbackInfo ci) { if (eventModelId != ModelLoader.MISSING_ID) return; + if (!ActiveCITs.isActive()) + return; + + info("Loading CITItem models..."); + CONTAINER.loaded.values().stream() // todo remove streams usage + .flatMap(Collection::stream) + .distinct().forEach(cit -> { + try { + cit.type.loadUnbakedAssets(resourceManager); + + for (JsonUnbakedModel unbakedModel : cit.type.unbakedAssets.values()) { + ResewnItemModelIdentifier id = new ResewnItemModelIdentifier(unbakedModel.id); + this.unbakedModels.put(id, unbakedModel); + this.modelsToLoad.addAll(unbakedModel.getModelDependencies()); + this.modelsToBake.put(id, unbakedModel); + } + } catch (Exception e) { + CITResewn.logErrorLoading(e.getMessage()); + } + }); + + TypeItem.GENERATED_SUB_CITS_SEEN.clear(); + } + + @Inject(method = "upload", at = @At("RETURN")) + public void citresewn$linkTypeItemModels(TextureManager textureManager, Profiler profiler, CallbackInfoReturnable cir) { + if (!ActiveCITs.isActive()) + return; + + profiler.push("citresewn:item_linking"); + info("Linking baked models to CITItems..."); + + CONTAINER.loaded.values().stream() // todo remove streams usage + .flatMap(Collection::stream) + .distinct().forEach(cit -> { + for (Map.Entry, JsonUnbakedModel> citModelEntry : cit.type.unbakedAssets.entrySet()) { + if (citModelEntry.getKey() == null) { + cit.type.bakedModel = this.bakedModels.get(new ResewnItemModelIdentifier(citModelEntry.getValue().id)); + } else { + BakedModel bakedModel = bakedModels.get(new ResewnItemModelIdentifier(citModelEntry.getValue().id)); + if (bakedModel == null) + CITResewn.logWarnLoading("Skipping sub cit: Failed loading model for \"" + citModelEntry.getValue().id + "\" in " + cit.propertiesIdentifier + " from " + cit.packName); + else + cit.type.bakedSubModels.override(citModelEntry.getKey(), bakedModel); + } + } + cit.type.unbakedAssets = null; + }); + + profiler.pop(); + } + + + @Inject(method = "loadModelFromJson", cancellable = true, at = @At("HEAD")) + public void citresewn$forceLiteralResewnModelIdentifier(Identifier id, CallbackInfoReturnable cir) { + if (id instanceof ResewnItemModelIdentifier) { + InputStream is = null; + Resource resource = null; + try { + JsonUnbakedModel json = JsonUnbakedModel.deserialize(IOUtils.toString(is = (resource = resourceManager.getResource(id)).getInputStream(), StandardCharsets.UTF_8)); + json.id = id.toString(); + json.id = json.id.substring(0, json.id.length() - 5); + + ((JsonUnbakedModelAccessor) json).getTextureMap().replaceAll((layer, original) -> { + Optional left = original.left(); + if (left.isPresent()) { + String originalPath = left.get().getTextureId().getPath(); + String[] split = originalPath.split("/"); + if (originalPath.startsWith("./") || (split.length > 2 && split[1].equals("cit"))) { + Identifier resolvedIdentifier = CITType.resolvePath(id, originalPath, ".png", identifier -> resourceManager.containsResource(identifier)); + if (resolvedIdentifier != null) + return Either.left(new SpriteIdentifier(left.get().getAtlasId(), new ResewnTextureIdentifier(resolvedIdentifier))); + } + } + return original; + }); + + Identifier parentId = ((JsonUnbakedModelAccessor) json).getParentId(); + if (parentId != null) { + String[] parentIdPathSplit = parentId.getPath().split("/"); + if (parentId.getPath().startsWith("./") || (parentIdPathSplit.length > 2 && parentIdPathSplit[1].equals("cit"))) { + parentId = CITType.resolvePath(id, parentId.getPath(), ".json", identifier -> resourceManager.containsResource(identifier)); + if (parentId != null) + ((JsonUnbakedModelAccessor) json).setParentId(new ResewnItemModelIdentifier(parentId)); + } + } + + json.getOverrides().replaceAll(override -> { + String[] modelIdPathSplit = override.getModelId().getPath().split("/"); + if (override.getModelId().getPath().startsWith("./") || (modelIdPathSplit.length > 2 && modelIdPathSplit[1].equals("cit"))) { + Identifier resolvedOverridePath = CITType.resolvePath(id, override.getModelId().getPath(), ".json", identifier -> resourceManager.containsResource(identifier)); + if (resolvedOverridePath != null) + return new ModelOverride(new ResewnItemModelIdentifier(resolvedOverridePath), override.streamConditions().collect(Collectors.toList())); + } + + return override; + }); + + cir.setReturnValue(json); + } catch (Exception ignored) { + } finally { + IOUtils.closeQuietly(is, resource); + } + } + } + + @ModifyArg(method = "loadModelFromJson", at = + @At(value = "INVOKE", target = "Lnet/minecraft/resource/ResourceManager;getResource(Lnet/minecraft/util/Identifier;)Lnet/minecraft/resource/Resource;")) + public Identifier citresewn$fixDuplicatePrefixSuffix(Identifier original) { + if (original.getPath().startsWith("models/models/") && original.getPath().endsWith(".json.json") && original.getPath().contains("cit")) + return new Identifier(original.getNamespace(), original.getPath().substring(7, original.getPath().length() - 5)); + + return original; + } +} diff --git a/defaults/src/main/resources/citresewn-defaults.accesswidener b/defaults/src/main/resources/citresewn-defaults.accesswidener index 3fde517..22b4947 100644 --- a/defaults/src/main/resources/citresewn-defaults.accesswidener +++ b/defaults/src/main/resources/citresewn-defaults.accesswidener @@ -1 +1,27 @@ accessWidener v1 named + +# TypeItem +accessible class net/minecraft/client/render/model/json/ModelOverrideList$BakedOverride +accessible class net/minecraft/client/render/model/json/ModelOverrideList$InlinedCondition +accessible method net/minecraft/client/render/model/json/ModelOverrideList ()V +accessible method net/minecraft/client/render/model/json/ModelOverrideList$BakedOverride ([Lnet/minecraft/client/render/model/json/ModelOverrideList$InlinedCondition;Lnet/minecraft/client/render/model/BakedModel;)V +accessible method net/minecraft/client/render/model/json/ModelOverrideList$InlinedCondition (IF)V +accessible field net/minecraft/client/render/model/json/ModelOverrideList overrides [Lnet/minecraft/client/render/model/json/ModelOverrideList$BakedOverride; +mutable field net/minecraft/client/render/model/json/ModelOverrideList overrides [Lnet/minecraft/client/render/model/json/ModelOverrideList$BakedOverride; +accessible field net/minecraft/client/render/model/json/ModelOverrideList conditionTypes [Lnet/minecraft/util/Identifier; +mutable field net/minecraft/client/render/model/json/ModelOverrideList conditionTypes [Lnet/minecraft/util/Identifier; + +# TypeEnchantment +accessible class net/minecraft/client/render/RenderLayer$MultiPhaseParameters +accessible method net/minecraft/client/render/RenderLayer of (Ljava/lang/String;Lnet/minecraft/client/render/VertexFormat;Lnet/minecraft/client/render/VertexFormat$DrawMode;ILnet/minecraft/client/render/RenderLayer$MultiPhaseParameters;)Lnet/minecraft/client/render/RenderLayer$MultiPhase; +accessible class net/minecraft/client/render/RenderPhase$Shader +accessible class net/minecraft/client/render/RenderPhase$Texturing +accessible class net/minecraft/client/render/RenderPhase$Transparency +accessible class net/minecraft/client/render/RenderPhase$Texture +accessible class net/minecraft/client/render/RenderPhase$Lightmap +accessible class net/minecraft/client/render/RenderPhase$Overlay +accessible class net/minecraft/client/render/RenderPhase$Cull +accessible class net/minecraft/client/render/RenderPhase$DepthTest +accessible class net/minecraft/client/render/RenderPhase$WriteMaskState +accessible class net/minecraft/client/render/RenderPhase$Layering +accessible class net/minecraft/client/render/RenderPhase$Target \ No newline at end of file diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java index 99cdbf0..b2dd2cd 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java @@ -1,5 +1,6 @@ package shcm.shsupercm.fabric.citresewn.cit; +import net.minecraft.client.MinecraftClient; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.world.World; @@ -13,7 +14,7 @@ public class CITContext { public CITContext(ItemStack stack, World world, LivingEntity entity) { this.stack = stack; - this.world = world; + this.world = world == null ? MinecraftClient.getInstance().world : world; this.entity = entity; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java index 33f6367..fb0f793 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java @@ -55,7 +55,7 @@ public class CITRegistry { public static CITType parseType(PropertyGroup properties) throws CITParsingException { Identifier type = new Identifier("citresewn", "item"); - PropertyValue propertiesType = properties.getLast("citresewn", "type"); + PropertyValue propertiesType = properties.getLastWithoutMetadata("citresewn", "type"); if (propertiesType != null) { String value = propertiesType.value(); if (!value.contains(":")) diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java index abbe755..b618dde 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java @@ -1,10 +1,16 @@ package shcm.shsupercm.fabric.citresewn.cit; +import shcm.shsupercm.fabric.citresewn.CITResewn; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import java.util.List; public abstract class CITType { public abstract void load(List conditions, PropertyGroup properties) throws CITParsingException; + + protected void warn(String message, PropertyValue value, PropertyGroup properties) { + CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value.position())); + } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java index 964b58d..384014b 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java @@ -8,6 +8,6 @@ public class CITParsingException extends Exception { } public static String descriptionOf(String message, PropertyGroup propertyGroup, int position) { - return message + " at " + position + " in " + propertyGroup.identifier.toString() + " from " + propertyGroup.packName; + return message + (position != -1 ? " line " + position : "") + " in " + propertyGroup.identifier.toString() + " from " + propertyGroup.packName; } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java index 6955ac1..b2806a2 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java @@ -40,9 +40,11 @@ public abstract class PropertyGroup { return values; } - public PropertyValue getLast(String namespace, String... pathAliases) { + public PropertyValue getLastWithoutMetadata(String namespace, String... pathAliases) { PropertyValue value = null; - for (Iterator iterator = get(namespace, pathAliases).iterator(); iterator.hasNext(); value = iterator.next()); + for (PropertyValue next : get(namespace, pathAliases)) + if (next.keyMetadata() == null) + value = next; return value; } diff --git a/src/main/resources/citresewn.accesswidener b/src/main/resources/citresewn.accesswidener index 33ad46d..dfde67a 100644 --- a/src/main/resources/citresewn.accesswidener +++ b/src/main/resources/citresewn.accesswidener @@ -1,29 +1 @@ -accessWidener v1 named - -# net.minecraft.client.render.model.json.ModelOverrideList -accessible class net/minecraft/client/render/model/json/ModelOverrideList$BakedOverride -accessible class net/minecraft/client/render/model/json/ModelOverrideList$InlinedCondition -accessible method net/minecraft/client/render/model/json/ModelOverrideList ()V -accessible method net/minecraft/client/render/model/json/ModelOverrideList$BakedOverride ([Lnet/minecraft/client/render/model/json/ModelOverrideList$InlinedCondition;Lnet/minecraft/client/render/model/BakedModel;)V -accessible method net/minecraft/client/render/model/json/ModelOverrideList$InlinedCondition (IF)V -accessible field net/minecraft/client/render/model/json/ModelOverrideList overrides [Lnet/minecraft/client/render/model/json/ModelOverrideList$BakedOverride; -mutable field net/minecraft/client/render/model/json/ModelOverrideList overrides [Lnet/minecraft/client/render/model/json/ModelOverrideList$BakedOverride; -accessible field net/minecraft/client/render/model/json/ModelOverrideList conditionTypes [Lnet/minecraft/util/Identifier; -mutable field net/minecraft/client/render/model/json/ModelOverrideList conditionTypes [Lnet/minecraft/util/Identifier; - -# net.minecraft.client.render.RenderLayer -accessible class net/minecraft/client/render/RenderLayer$MultiPhaseParameters -accessible method net/minecraft/client/render/RenderLayer of (Ljava/lang/String;Lnet/minecraft/client/render/VertexFormat;Lnet/minecraft/client/render/VertexFormat$DrawMode;ILnet/minecraft/client/render/RenderLayer$MultiPhaseParameters;)Lnet/minecraft/client/render/RenderLayer$MultiPhase; - -# net.minecraft.client.render.RenderPhase -accessible class net/minecraft/client/render/RenderPhase$Shader -accessible class net/minecraft/client/render/RenderPhase$Texturing -accessible class net/minecraft/client/render/RenderPhase$Transparency -accessible class net/minecraft/client/render/RenderPhase$Texture -accessible class net/minecraft/client/render/RenderPhase$Lightmap -accessible class net/minecraft/client/render/RenderPhase$Overlay -accessible class net/minecraft/client/render/RenderPhase$Cull -accessible class net/minecraft/client/render/RenderPhase$DepthTest -accessible class net/minecraft/client/render/RenderPhase$WriteMaskState -accessible class net/minecraft/client/render/RenderPhase$Layering -accessible class net/minecraft/client/render/RenderPhase$Target \ No newline at end of file +accessWidener v1 named \ No newline at end of file -- cgit From 4d8c7ea53d5f4af351ec9355c55931ad4dad6715 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Tue, 15 Feb 2022 12:31:42 +0200 Subject: Pass resource manager to type loading --- .../shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java | 2 +- src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java | 3 ++- src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java | 6 +++--- 3 files changed, 6 insertions(+), 5 deletions(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java index 14b8813..aa3562b 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -57,7 +57,7 @@ public class TypeItem extends CITType { public CITOverrideList bakedSubModels = new CITOverrideList(); @Override - public void load(List conditions, PropertyGroup properties) throws CITParsingException { + public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { for (CITCondition condition : conditions) if (condition instanceof ConditionItems conditionItems) items.addAll(Arrays.asList(conditionItems.items)); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java index b618dde..7ee1e03 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java @@ -1,5 +1,6 @@ package shcm.shsupercm.fabric.citresewn.cit; +import net.minecraft.resource.ResourceManager; import shcm.shsupercm.fabric.citresewn.CITResewn; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; @@ -8,7 +9,7 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import java.util.List; public abstract class CITType { - public abstract void load(List conditions, PropertyGroup properties) throws CITParsingException; + public abstract void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException; protected void warn(String message, PropertyValue value, PropertyGroup properties) { CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value.position())); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 1dbc22d..38ca718 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -65,7 +65,7 @@ public class PackParser { for (Identifier identifier : resourceManager.findResources(root + "/cit", s -> s.endsWith(".properties"))) { String packName = null; try (Resource resource = resourceManager.getResource(identifier)) { - cits.add(parseCIT(PropertyGroup.tryParseGroup(packName = resource.getResourcePackName(), identifier, resource.getInputStream()))); + cits.add(parseCIT(PropertyGroup.tryParseGroup(packName = resource.getResourcePackName(), identifier, resource.getInputStream()), resourceManager)); } catch (CITParsingException e) { CITResewn.logErrorLoading(e.getMessage()); } catch (Exception e) { @@ -77,7 +77,7 @@ public class PackParser { return cits; } - public static CIT parseCIT(PropertyGroup properties) throws CITParsingException { + public static CIT parseCIT(PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { CITType citType = CITRegistry.parseType(properties); ArrayList conditions = new ArrayList<>(); @@ -109,7 +109,7 @@ public class PackParser { return condition == null; }); - citType.load(conditions, properties); + citType.load(conditions, properties, resourceManager); return new CIT<>(properties.identifier, properties.packName, citType, conditions.toArray(new CITCondition[0]), weight.weight); } -- cgit From 55e32286cb149e4c20aa8466d51b4d40dae58d48 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Tue, 15 Feb 2022 12:49:37 +0200 Subject: Implemented asset resolution --- .../citresewn/defaults/cit/types/TypeItem.java | 22 +++---- .../mixin/types/item/ModelLoaderMixin.java | 6 +- .../shsupercm/fabric/citresewn/cit/CITType.java | 68 ++++++++++++++++++++++ 3 files changed, 82 insertions(+), 14 deletions(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java index aa3562b..b08f0c9 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -70,18 +70,18 @@ public class TypeItem extends CITType { boolean containsTexture = modelProp == null && !properties.get("citresewn", "texture", "tile").isEmpty(); if (!containsTexture) { - assetIdentifier = resolvePath(identifier, modelProp, ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + assetIdentifier = resolveAsset(properties.identifier, modelProp, "models", ".json", resourceManager); if (assetIdentifier != null) assetIdentifiers.put(null, assetIdentifier); else if (modelProp != null) { - assetIdentifier = resolvePath(identifier, modelProp, ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + assetIdentifier = resolveAsset(properties.identifier, modelProp, "models", ".json", resourceManager); if (assetIdentifier != null) assetIdentifiers.put(null, assetIdentifier); } } for (PropertyValue property : properties.get("citresewn", "model")) { - Identifier subIdentifier = resolvePath(identifier, properties.getProperty(property), ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + Identifier subIdentifier = resolveAsset(properties.identifier, property, "models", ".json", resourceManager); if (subIdentifier == null) throw new CITParsingException("Cannot resolve path", properties, property.position()); @@ -93,12 +93,12 @@ public class TypeItem extends CITType { if (assetIdentifiers.size() == 0) { // attempt to load texture isTexture = true; PropertyValue textureProp = properties.getLastWithoutMetadata("citresewn", "texture", "tile"); - assetIdentifier = resolvePath(identifier, textureProp, ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + assetIdentifier = resolveAsset(properties.identifier, textureProp, "textures", ".png", resourceManager); if (assetIdentifier != null) assetIdentifiers.put(null, assetIdentifier); for (PropertyValue property : properties.get("citresewn", "texture", "tile")) { - Identifier subIdentifier = resolvePath(identifier, properties.getProperty(property), ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + Identifier subIdentifier = resolveAsset(properties.identifier, property, "textures", ".png", resourceManager); if (subIdentifier == null) throw new CITParsingException("Cannot resolve path", properties, property.position()); @@ -109,7 +109,7 @@ public class TypeItem extends CITType { } else { // attempt to load textureOverrideMap from textures PropertyValue textureProp = properties.getLastWithoutMetadata("citresewn", "texture", "tile"); if (textureProp != null) { - assetIdentifier = resolvePath(identifier, textureProp, ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + assetIdentifier = resolveAsset(properties.identifier, textureProp, "textures", ".png", resourceManager); if (assetIdentifier != null) textureOverrideMap.put(null, Either.left(new SpriteIdentifier(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE, new ResewnTextureIdentifier(assetIdentifier)))); else @@ -118,7 +118,7 @@ public class TypeItem extends CITType { for (PropertyValue property : properties.get("citresewn", "texture", "tile")) { textureProp = property; - Identifier subIdentifier = resolvePath(identifier, textureProp, ".png", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + Identifier subIdentifier = resolveAsset(properties.identifier, textureProp, "textures", ".png", resourceManager); if (subIdentifier == null) throw new CITParsingException("Cannot resolve path", properties, property.position()); @@ -206,7 +206,7 @@ public class TypeItem extends CITType { Collections.reverse(overrideModels); for (Identifier overrideModel : overrideModels) { - Identifier replacement = resolvePath(baseIdentifier, overrideModel.toString(), ".json", resourceManager::containsResource); + Identifier replacement = resolveAsset(baseIdentifier, overrideModel.toString(), "models", ".json", resourceManager); if (replacement != null) { String subTexturePath = replacement.toString().substring(0, replacement.toString().lastIndexOf('.')); final String subTextureName = subTexturePath.substring(subTexturePath.lastIndexOf('/') + 1); @@ -294,7 +294,7 @@ public class TypeItem extends CITType { ((JsonUnbakedModelAccessor) json).getTextureMap().replaceAll((layer, original) -> { Optional left = original.left(); if (left.isPresent()) { - Identifier resolvedIdentifier = resolvePath(identifier, left.get().getTextureId().getPath(), ".png", resourceManager::containsResource); + Identifier resolvedIdentifier = resolveAsset(identifier, left.get().getTextureId().getPath(), "textures", ".png", resourceManager); if (resolvedIdentifier != null) return Either.left(new SpriteIdentifier(left.get().getAtlasId(), new ResewnTextureIdentifier(resolvedIdentifier))); } @@ -329,7 +329,7 @@ public class TypeItem extends CITType { if (parentId != null) { String[] parentIdPathSplit = parentId.getPath().split("/"); if (parentId.getPath().startsWith("./") || (parentIdPathSplit.length > 2 && parentIdPathSplit[1].equals("cit"))) { - parentId = resolvePath(identifier, parentId.getPath(), ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + parentId = resolveAsset(identifier, parentId.getPath(), "models", ".json", resourceManager); if (parentId != null) ((JsonUnbakedModelAccessor) json).setParentId(new ResewnItemModelIdentifier(parentId)); } @@ -338,7 +338,7 @@ public class TypeItem extends CITType { json.getOverrides().replaceAll(override -> { String[] modelIdPathSplit = override.getModelId().getPath().split("/"); if (override.getModelId().getPath().startsWith("./") || (modelIdPathSplit.length > 2 && modelIdPathSplit[1].equals("cit"))) { - Identifier resolvedOverridePath = resolvePath(identifier, override.getModelId().getPath(), ".json", id -> pack.resourcePack.contains(ResourceType.CLIENT_RESOURCES, id)); + Identifier resolvedOverridePath = resolveAsset(identifier, override.getModelId().getPath(), "models", ".json", resourceManager); if (resolvedOverridePath != null) return new ModelOverride(new ResewnItemModelIdentifier(resolvedOverridePath), override.streamConditions().collect(Collectors.toList())); } diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java index 22e9373..c95e08a 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java @@ -117,7 +117,7 @@ public class ModelLoaderMixin { String originalPath = left.get().getTextureId().getPath(); String[] split = originalPath.split("/"); if (originalPath.startsWith("./") || (split.length > 2 && split[1].equals("cit"))) { - Identifier resolvedIdentifier = CITType.resolvePath(id, originalPath, ".png", identifier -> resourceManager.containsResource(identifier)); + Identifier resolvedIdentifier = CITType.resolveAsset(id, originalPath, "textures", ".png", resourceManager); if (resolvedIdentifier != null) return Either.left(new SpriteIdentifier(left.get().getAtlasId(), new ResewnTextureIdentifier(resolvedIdentifier))); } @@ -129,7 +129,7 @@ public class ModelLoaderMixin { if (parentId != null) { String[] parentIdPathSplit = parentId.getPath().split("/"); if (parentId.getPath().startsWith("./") || (parentIdPathSplit.length > 2 && parentIdPathSplit[1].equals("cit"))) { - parentId = CITType.resolvePath(id, parentId.getPath(), ".json", identifier -> resourceManager.containsResource(identifier)); + parentId = CITType.resolveAsset(id, parentId.getPath(), "models", ".json", resourceManager); if (parentId != null) ((JsonUnbakedModelAccessor) json).setParentId(new ResewnItemModelIdentifier(parentId)); } @@ -138,7 +138,7 @@ public class ModelLoaderMixin { json.getOverrides().replaceAll(override -> { String[] modelIdPathSplit = override.getModelId().getPath().split("/"); if (override.getModelId().getPath().startsWith("./") || (modelIdPathSplit.length > 2 && modelIdPathSplit[1].equals("cit"))) { - Identifier resolvedOverridePath = CITType.resolvePath(id, override.getModelId().getPath(), ".json", identifier -> resourceManager.containsResource(identifier)); + Identifier resolvedOverridePath = CITType.resolveAsset(id, override.getModelId().getPath(), "models", ".json", resourceManager); if (resolvedOverridePath != null) return new ModelOverride(new ResewnItemModelIdentifier(resolvedOverridePath), override.streamConditions().collect(Collectors.toList())); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java index 7ee1e03..3618dfd 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java @@ -1,11 +1,14 @@ package shcm.shsupercm.fabric.citresewn.cit; import net.minecraft.resource.ResourceManager; +import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.CITResewn; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +import java.util.Arrays; +import java.util.LinkedList; import java.util.List; public abstract class CITType { @@ -14,4 +17,69 @@ public abstract class CITType { protected void warn(String message, PropertyValue value, PropertyGroup properties) { CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value.position())); } + + /** + * Takes a defined path and resolves it to an identifier pointing to the resourcepack's path of the specified extension(returns null if no path can be resolved).
+ * If definedPath is null, will try to resolve a relative file with the same name as the rootIdentifier with the extension, otherwise:
+ * definedPath will be formatted to replace "\\" with "/" the extension will be appended if not there already.
+ * It will first try using definedPath as an absolute path, if it cant resolve(or definedPath starts with ./), definedPath will be considered relative.
+ * Relative paths support going to parent directories using "..". + */ + public static Identifier resolveAsset(Identifier rootIdentifier, String path, String defaultedTypeDirectory, String extension, ResourceManager resourceManager) { + if (path == null) { + path = rootIdentifier.getPath().substring(0, rootIdentifier.getPath().length() - 11); + if (!path.endsWith(extension)) + path = path + extension; + Identifier pathIdentifier = new Identifier(rootIdentifier.getNamespace(), path); + return resourceManager.containsResource(pathIdentifier) ? pathIdentifier : null; + } + + Identifier pathIdentifier = new Identifier(path); + + path = pathIdentifier.getPath().replace('\\', '/'); + if (!path.endsWith(extension)) + path = path + extension; + + if (path.startsWith("./")) + path = path.substring(2); + else if (!path.contains("..")) { + pathIdentifier = new Identifier(pathIdentifier.getNamespace(), path); + if (resourceManager.containsResource(pathIdentifier)) + return pathIdentifier; + else if (path.startsWith("assets/")) { + path = path.substring(7); + int sep = path.indexOf('/'); + pathIdentifier = new Identifier(path.substring(0, sep), path.substring(sep + 1)); + if (resourceManager.containsResource(pathIdentifier)) + return pathIdentifier; + } + pathIdentifier = new Identifier(pathIdentifier.getNamespace(), defaultedTypeDirectory + "/" + path); + if (resourceManager.containsResource(pathIdentifier)) + return pathIdentifier; + } + + LinkedList pathParts = new LinkedList<>(Arrays.asList(rootIdentifier.getPath().split("/"))); + pathParts.removeLast(); + + if (path.contains("/")) { + for (String part : path.split("/")) { + if (part.equals("..")) { + if (pathParts.size() == 0) + return null; + pathParts.removeLast(); + } else + pathParts.addLast(part); + } + } else + pathParts.addLast(path); + path = String.join("/", pathParts); + + pathIdentifier = new Identifier(rootIdentifier.getNamespace(), path); + + return resourceManager.containsResource(pathIdentifier) ? pathIdentifier : null; + } + + public static Identifier resolveAsset(Identifier rootIdentifier, PropertyValue path, String defaultedTypeDirectory, String extension, ResourceManager resourceManager) { + return resolveAsset(rootIdentifier, path == null ? null : path.value(), defaultedTypeDirectory, extension, resourceManager); + } } -- cgit From 185dd9defbd5e0a511a6551e7857b01c5353dd5b Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Wed, 16 Feb 2022 14:42:15 +0200 Subject: Implemented type-specific property acknowledgement --- .../shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java | 7 ++++++- .../citresewn/defaults/mixin/types/item/ModelLoaderMixin.java | 6 +++--- src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java | 7 ++++--- src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java | 4 ++++ 4 files changed, 17 insertions(+), 7 deletions(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java index d9f9ba6..9cb623e 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -17,7 +17,6 @@ import net.minecraft.item.Item; import net.minecraft.item.Items; import net.minecraft.resource.Resource; import net.minecraft.resource.ResourceManager; -import net.minecraft.resource.ResourceType; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; import org.apache.commons.io.IOUtils; @@ -30,6 +29,7 @@ import shcm.shsupercm.fabric.citresewn.defaults.common.ResewnTextureIdentifier; import shcm.shsupercm.fabric.citresewn.defaults.mixin.types.item.JsonUnbakedModelAccessor; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import java.io.InputStream; @@ -56,6 +56,11 @@ public class TypeItem extends CITType { public BakedModel bakedModel = null; public CITOverrideList bakedSubModels = new CITOverrideList(); + @Override + public Set typeProperties() { + return Set.of(PropertyKey.of("model"), PropertyKey.of("texture"), PropertyKey.of("tile")); + } + @Override public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { for (CITCondition condition : conditions) diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java index adb4963..0c5f4f1 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java @@ -54,7 +54,7 @@ public class ModelLoaderMixin { if (!ActiveCITs.isActive()) return; - info("Loading CITItem models..."); + info("Loading item CIT models..."); CONTAINER.loaded.values().stream() // todo remove streams usage .flatMap(Collection::stream) .distinct().forEach(cit -> { @@ -80,8 +80,8 @@ public class ModelLoaderMixin { if (!ActiveCITs.isActive()) return; - profiler.push("citresewn:item_linking"); - info("Linking baked models to CITItems..."); + profiler.push("citresewn:type_item_linking"); + info("Linking baked models to item CITs..."); CONTAINER.loaded.values().stream() // todo remove streams usage .flatMap(Collection::stream) diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java index 3618dfd..aed784a 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java @@ -5,13 +5,14 @@ import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.CITResewn; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; +import java.util.*; public abstract class CITType { + public abstract Set typeProperties(); + public abstract void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException; protected void warn(String message, PropertyValue value, PropertyGroup properties) { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 38ca718..70e3f75 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -82,9 +82,13 @@ public class PackParser { ArrayList conditions = new ArrayList<>(); + Set ignoredProperties = citType.typeProperties(); + for (Map.Entry> entry : properties.properties.entrySet()) { if (entry.getKey().path().equals("type") && entry.getKey().namespace().equals("citresewn")) continue; + if (ignoredProperties.contains(entry.getKey())) + continue; for (PropertyValue value : entry.getValue()) conditions.add(CITRegistry.parseCondition(entry.getKey(), value, properties)); -- cgit From 9b04862bfb974a2b6728d1ddcf8a0c93b7bae1fc Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Wed, 16 Feb 2022 14:46:44 +0200 Subject: Unknown conditions will now fail CITs by default --- .../shsupercm/fabric/citresewn/cit/CITRegistry.java | 5 +++-- .../citresewn/cit/builtin/AlwaysFailCondition.java | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/AlwaysFailCondition.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java index fb0f793..af8f430 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java @@ -4,6 +4,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; +import shcm.shsupercm.fabric.citresewn.cit.builtin.AlwaysFailCondition; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.ex.UnknownCITTypeException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; @@ -43,8 +44,8 @@ public class CITRegistry { public static CITCondition parseCondition(PropertyKey key, PropertyValue value, PropertyGroup properties) throws CITParsingException { CITConditionContainer conditionContainer = CONDITIONS.get(key); if (conditionContainer == null) { - logWarnLoading("Skipping condition: " + CITParsingException.descriptionOf("Unknown condition type", properties, value.position())); - return null; + logWarnLoading(CITParsingException.descriptionOf("Unknown condition type", properties, value.position())); + return new AlwaysFailCondition(); } CITCondition condition = conditionContainer.createCondition.get(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/AlwaysFailCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/AlwaysFailCondition.java new file mode 100644 index 0000000..f385ae9 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/AlwaysFailCondition.java @@ -0,0 +1,19 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin; + +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +public class AlwaysFailCondition extends CITCondition { + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + + } + + @Override + public boolean test(CITContext context) { + return false; + } +} -- cgit From dd0b7b4b6af463ee0b8e794300a05a10d46a75e4 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Wed, 16 Feb 2022 15:19:07 +0200 Subject: Added partial support for colon separator --- .../shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java | 2 +- .../fabric/citresewn/pack/format/PropertiesGroupAdapter.java | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java index 384014b..b3e126f 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java @@ -8,6 +8,6 @@ public class CITParsingException extends Exception { } public static String descriptionOf(String message, PropertyGroup propertyGroup, int position) { - return message + (position != -1 ? " line " + position : "") + " in " + propertyGroup.identifier.toString() + " from " + propertyGroup.packName; + return message + (position != -1 ? " @L" + position : "") + " in " + propertyGroup.identifier.toString() + " from " + propertyGroup.packName; } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java index 8ad2ccf..c0b3da6 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java @@ -47,6 +47,7 @@ public class PropertiesGroupAdapter extends PropertyGroup { StringBuilder builder = new StringBuilder(); String key = null, keyMetadata = null; + final boolean checkColonSeparator = !line.contains("="); for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); @@ -75,7 +76,7 @@ public class PropertiesGroupAdapter extends PropertyGroup { default -> c; }; - } else if (key == null && c == '=') { + } else if (key == null && (c == '=' || (checkColonSeparator && c == ':'))) { key = builder.toString().stripTrailing(); int metadataIndex = key.indexOf('.'); if (metadataIndex >= 0) { @@ -89,11 +90,10 @@ public class PropertiesGroupAdapter extends PropertyGroup { continue; } - builder.append(c); } - if (key == null) //todo handle : separator + if (key == null) throw new IOException("Missing separator in line " + linePos); int pos = linePos - multilineSkip; -- cgit From 77bcaf1b48fd94d90755eb9a9360601ba5414904 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Wed, 16 Feb 2022 15:31:18 +0200 Subject: Moved some stuff around --- .../fabric/citresewn/cit/CITRegistry.java | 2 +- .../citresewn/cit/builtin/AlwaysFailCondition.java | 19 --------------- .../citresewn/cit/builtin/WeightCondition.java | 27 ---------------------- .../builtin/conditions/AlwaysFailCondition.java | 19 +++++++++++++++ .../cit/builtin/conditions/WeightCondition.java | 27 ++++++++++++++++++++++ .../fabric/citresewn/pack/PackParser.java | 2 +- 6 files changed, 48 insertions(+), 48 deletions(-) delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/AlwaysFailCondition.java delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/WeightCondition.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/AlwaysFailCondition.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java index af8f430..53a5226 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java @@ -4,7 +4,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; -import shcm.shsupercm.fabric.citresewn.cit.builtin.AlwaysFailCondition; +import shcm.shsupercm.fabric.citresewn.cit.builtin.conditions.AlwaysFailCondition; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.ex.UnknownCITTypeException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/AlwaysFailCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/AlwaysFailCondition.java deleted file mode 100644 index f385ae9..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/AlwaysFailCondition.java +++ /dev/null @@ -1,19 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.cit.builtin; - -import shcm.shsupercm.fabric.citresewn.cit.CITCondition; -import shcm.shsupercm.fabric.citresewn.cit.CITContext; -import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; - -public class AlwaysFailCondition extends CITCondition { - @Override - public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { - - } - - @Override - public boolean test(CITContext context) { - return false; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/WeightCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/WeightCondition.java deleted file mode 100644 index ec0a5d7..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/WeightCondition.java +++ /dev/null @@ -1,27 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.cit.builtin; - -import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; -import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; -import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.cit.CITCondition; -import shcm.shsupercm.fabric.citresewn.cit.CITContext; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; - -public class WeightCondition extends CITCondition { - @Entrypoint(CITConditionContainer.ENTRYPOINT) - public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(WeightCondition.class, WeightCondition::new, - "weight"); - - public int weight = 0; - - @Override - public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { - this.weight = parseInteger(value, properties); - } - - @Override - public boolean test(CITContext context) { - return true; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/AlwaysFailCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/AlwaysFailCondition.java new file mode 100644 index 0000000..5c32d97 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/AlwaysFailCondition.java @@ -0,0 +1,19 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; + +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +public class AlwaysFailCondition extends CITCondition { + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + + } + + @Override + public boolean test(CITContext context) { + return false; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java new file mode 100644 index 0000000..54f26ff --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java @@ -0,0 +1,27 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; + +import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; +import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +public class WeightCondition extends CITCondition { + @Entrypoint(CITConditionContainer.ENTRYPOINT) + public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(WeightCondition.class, WeightCondition::new, + "weight"); + + public int weight = 0; + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + this.weight = parseInteger(value, properties); + } + + @Override + public boolean test(CITContext context) { + return true; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 70e3f75..5096543 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -5,7 +5,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.resource.*; import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.cit.builtin.WeightCondition; +import shcm.shsupercm.fabric.citresewn.cit.builtin.conditions.WeightCondition; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.mixin.GroupResourcePackAccessor; import shcm.shsupercm.fabric.citresewn.cit.CIT; -- cgit From 8e96b0fbba042e63f956b017cc3215d9880d597c Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Thu, 17 Feb 2022 12:30:58 +0200 Subject: Implemented some common condition types --- .../fabric/citresewn/cit/CITCondition.java | 8 -- .../cit/builtin/conditions/DoubleCondition.java | 132 +++++++++++++++++++++ .../cit/builtin/conditions/FloatCondition.java | 132 +++++++++++++++++++++ .../cit/builtin/conditions/IntegerCondition.java | 132 +++++++++++++++++++++ .../cit/builtin/conditions/ListCondition.java | 79 ++++++++++++ .../cit/builtin/conditions/WeightCondition.java | 19 +-- .../fabric/citresewn/ex/CITParsingException.java | 4 + .../fabric/citresewn/pack/PackParser.java | 4 +- 8 files changed, 493 insertions(+), 17 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java index 7640d3c..03f118f 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java @@ -24,12 +24,4 @@ public abstract class CITCondition { protected void warn(String message, PropertyValue value, PropertyGroup properties) { CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value.position())); } - - protected int parseInteger(PropertyValue value, PropertyGroup properties) throws CITParsingException { - try { - return Integer.parseInt(value.value()); - } catch (NumberFormatException e) { - throw new CITParsingException("\"" + value.value() + "\" is not a valid integer", properties, value.position()); - } - } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java new file mode 100644 index 0000000..60b6e1a --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java @@ -0,0 +1,132 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; + +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +import static java.lang.Double.*; + +public abstract class DoubleCondition extends CITCondition { + protected final boolean supportsRanges, supportsNegatives, supportsPercentages; + + protected double min, max; + protected boolean range = false, percentage = false; + + protected DoubleCondition(boolean supportsRanges, boolean supportsNegatives, boolean supportsPercentages) { + this.supportsRanges = supportsRanges; + this.supportsNegatives = supportsNegatives; + this.supportsPercentages = supportsPercentages; + } + + protected abstract double getValue(CITContext context); + + protected double getPercentageTotalValue(CITContext context) { + return 0; + } + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + String strValue = value.value(); + if (supportsPercentages && (percentage = strValue.contains("%"))) + strValue = strValue.replace("%", ""); + + try { + if (range = supportsRanges) { + if (supportsNegatives) { + switch (strValue.length() - strValue.replace("-", "").length()) { // dashesCount + case 0 -> { + range = false; + min = parseDouble(strValue); + } + case 1 -> { + if (strValue.startsWith("-")) { + range = false; + min = parseDouble(strValue); + } else if (strValue.endsWith("-")) { + min = parseDouble(strValue.substring(0, strValue.length() - 1)); + max = MAX_VALUE; + } else { + String[] split = strValue.split("-"); + min = parseDouble(split[0]); + max = parseDouble(split[1]); + } + } + case 2 -> { + if (strValue.startsWith("--")) { + min = MIN_VALUE; + max = parseDouble(strValue.substring(1)); + } else if (strValue.startsWith("-") && strValue.endsWith("-")) { + min = parseDouble(strValue.substring(0, strValue.length() - 1)); + max = MAX_VALUE; + } else if (strValue.startsWith("-") && !strValue.endsWith("-") && !strValue.contains("--")) { + int lastDash = strValue.lastIndexOf('-'); + min = parseDouble(strValue.substring(0, lastDash)); + max = parseDouble(strValue.substring(lastDash + 1)); + } else + throw new CITParsingException("Could not parse range", properties, value.position()); + } + case 3 -> { + if (!strValue.contains("---") && strValue.startsWith("-")) { + String[] split = strValue.split("--"); + if (split.length != 2 || split[0].isEmpty() || split[1].isEmpty()) + throw new CITParsingException("Could not parse range", properties, value.position()); + + min = parseDouble(split[0]); + max = -parseDouble(split[1]); + } else + throw new CITParsingException("Could not parse range", properties, value.position()); + } + + default -> throw new CITParsingException("Could not parse range", properties, value.position()); + } + } else { + if (range = strValue.contains("-")) { + if (strValue.contains("--")) + throw new CITParsingException("Could not parse range", properties, value.position()); + String[] split = strValue.split("-"); + switch (split.length) { + case 1 -> { + min = parseDouble(split[0]); + max = MAX_VALUE; + } + case 2 -> { + if (strValue.endsWith("-")) + throw new CITParsingException("Could not parse range", properties, value.position()); + min = split[0].isEmpty() ? MIN_VALUE : parseDouble(split[0]); + max = split[1].isEmpty() ? MAX_VALUE : parseDouble(split[1]); + } + default -> throw new CITParsingException("Could not parse range", properties, value.position()); + } + } else + min = parseDouble(strValue); + } + } else { + min = parseDouble(strValue); + if (!supportsNegatives && min < 0) + throw new CITParsingException("Negatives are not allowed", properties, value.position()); + } + + if (range) { + if (min == max) + range = false; + else if (min > max) + throw new CITParsingException("Could not parse range", properties, value.position()); + } + } catch (Exception e) { + throw e instanceof CITParsingException citE ? citE : new CITParsingException("Could not parse double", properties, value.position(), e); + } + } + + @Override + public boolean test(CITContext context) { + double value = getValue(context); + + if (percentage) { + double percentValue = 100d * value / getPercentageTotalValue(context); + return range ? min <= percentValue && percentValue <= max : percentValue == min; + } else + return range ? min <= value && value <= max : value == min; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java new file mode 100644 index 0000000..24de921 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java @@ -0,0 +1,132 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; + +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +import static java.lang.Float.*; + +public abstract class FloatCondition extends CITCondition { + protected final boolean supportsRanges, supportsNegatives, supportsPercentages; + + protected float min, max; + protected boolean range = false, percentage = false; + + protected FloatCondition(boolean supportsRanges, boolean supportsNegatives, boolean supportsPercentages) { + this.supportsRanges = supportsRanges; + this.supportsNegatives = supportsNegatives; + this.supportsPercentages = supportsPercentages; + } + + protected abstract float getValue(CITContext context); + + protected float getPercentageTotalValue(CITContext context) { + return 0; + } + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + String strValue = value.value(); + if (supportsPercentages && (percentage = strValue.contains("%"))) + strValue = strValue.replace("%", ""); + + try { + if (range = supportsRanges) { + if (supportsNegatives) { + switch (strValue.length() - strValue.replace("-", "").length()) { // dashesCount + case 0 -> { + range = false; + min = parseFloat(strValue); + } + case 1 -> { + if (strValue.startsWith("-")) { + range = false; + min = parseFloat(strValue); + } else if (strValue.endsWith("-")) { + min = parseFloat(strValue.substring(0, strValue.length() - 1)); + max = MAX_VALUE; + } else { + String[] split = strValue.split("-"); + min = parseFloat(split[0]); + max = parseFloat(split[1]); + } + } + case 2 -> { + if (strValue.startsWith("--")) { + min = MIN_VALUE; + max = parseFloat(strValue.substring(1)); + } else if (strValue.startsWith("-") && strValue.endsWith("-")) { + min = parseFloat(strValue.substring(0, strValue.length() - 1)); + max = MAX_VALUE; + } else if (strValue.startsWith("-") && !strValue.endsWith("-") && !strValue.contains("--")) { + int lastDash = strValue.lastIndexOf('-'); + min = parseFloat(strValue.substring(0, lastDash)); + max = parseFloat(strValue.substring(lastDash + 1)); + } else + throw new CITParsingException("Could not parse range", properties, value.position()); + } + case 3 -> { + if (!strValue.contains("---") && strValue.startsWith("-")) { + String[] split = strValue.split("--"); + if (split.length != 2 || split[0].isEmpty() || split[1].isEmpty()) + throw new CITParsingException("Could not parse range", properties, value.position()); + + min = parseFloat(split[0]); + max = -parseFloat(split[1]); + } else + throw new CITParsingException("Could not parse range", properties, value.position()); + } + + default -> throw new CITParsingException("Could not parse range", properties, value.position()); + } + } else { + if (range = strValue.contains("-")) { + if (strValue.contains("--")) + throw new CITParsingException("Could not parse range", properties, value.position()); + String[] split = strValue.split("-"); + switch (split.length) { + case 1 -> { + min = parseFloat(split[0]); + max = MAX_VALUE; + } + case 2 -> { + if (strValue.endsWith("-")) + throw new CITParsingException("Could not parse range", properties, value.position()); + min = split[0].isEmpty() ? MIN_VALUE : parseFloat(split[0]); + max = split[1].isEmpty() ? MAX_VALUE : parseFloat(split[1]); + } + default -> throw new CITParsingException("Could not parse range", properties, value.position()); + } + } else + min = parseFloat(strValue); + } + } else { + min = parseFloat(strValue); + if (!supportsNegatives && min < 0) + throw new CITParsingException("Negatives are not allowed", properties, value.position()); + } + + if (range) { + if (min == max) + range = false; + else if (min > max) + throw new CITParsingException("Could not parse range", properties, value.position()); + } + } catch (Exception e) { + throw e instanceof CITParsingException citE ? citE : new CITParsingException("Could not parse float", properties, value.position(), e); + } + } + + @Override + public boolean test(CITContext context) { + float value = getValue(context); + + if (percentage) { + float percentValue = 100f * value / getPercentageTotalValue(context); + return range ? min <= percentValue && percentValue <= max : percentValue == min; + } else + return range ? min <= value && value <= max : value == min; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java new file mode 100644 index 0000000..6701338 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java @@ -0,0 +1,132 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; + +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +import static java.lang.Integer.*; + +public abstract class IntegerCondition extends CITCondition { + protected final boolean supportsRanges, supportsNegatives, supportsPercentages; + + protected int min, max; + protected boolean range = false, percentage = false; + + protected IntegerCondition(boolean supportsRanges, boolean supportsNegatives, boolean supportsPercentages) { + this.supportsRanges = supportsRanges; + this.supportsNegatives = supportsNegatives; + this.supportsPercentages = supportsPercentages; + } + + protected abstract int getValue(CITContext context); + + protected int getPercentageTotalValue(CITContext context) { + return 0; + } + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + String strValue = value.value(); + if (supportsPercentages && (percentage = strValue.contains("%"))) + strValue = strValue.replace("%", ""); + + try { + if (range = supportsRanges) { + if (supportsNegatives) { + switch (strValue.length() - strValue.replace("-", "").length()) { // dashesCount + case 0 -> { + range = false; + min = parseInt(strValue); + } + case 1 -> { + if (strValue.startsWith("-")) { + range = false; + min = parseInt(strValue); + } else if (strValue.endsWith("-")) { + min = parseInt(strValue.substring(0, strValue.length() - 1)); + max = MAX_VALUE; + } else { + String[] split = strValue.split("-"); + min = parseInt(split[0]); + max = parseInt(split[1]); + } + } + case 2 -> { + if (strValue.startsWith("--")) { + min = MIN_VALUE; + max = parseInt(strValue.substring(1)); + } else if (strValue.startsWith("-") && strValue.endsWith("-")) { + min = parseInt(strValue.substring(0, strValue.length() - 1)); + max = MAX_VALUE; + } else if (strValue.startsWith("-") && !strValue.endsWith("-") && !strValue.contains("--")) { + int lastDash = strValue.lastIndexOf('-'); + min = parseInt(strValue.substring(0, lastDash)); + max = parseInt(strValue.substring(lastDash + 1)); + } else + throw new CITParsingException("Could not parse range", properties, value.position()); + } + case 3 -> { + if (!strValue.contains("---") && strValue.startsWith("-")) { + String[] split = strValue.split("--"); + if (split.length != 2 || split[0].isEmpty() || split[1].isEmpty()) + throw new CITParsingException("Could not parse range", properties, value.position()); + + min = parseInt(split[0]); + max = -parseInt(split[1]); + } else + throw new CITParsingException("Could not parse range", properties, value.position()); + } + + default -> throw new CITParsingException("Could not parse range", properties, value.position()); + } + } else { + if (range = strValue.contains("-")) { + if (strValue.contains("--")) + throw new CITParsingException("Could not parse range", properties, value.position()); + String[] split = strValue.split("-"); + switch (split.length) { + case 1 -> { + min = parseInt(split[0]); + max = MAX_VALUE; + } + case 2 -> { + if (strValue.endsWith("-")) + throw new CITParsingException("Could not parse range", properties, value.position()); + min = split[0].isEmpty() ? MIN_VALUE : parseInt(split[0]); + max = split[1].isEmpty() ? MAX_VALUE : parseInt(split[1]); + } + default -> throw new CITParsingException("Could not parse range", properties, value.position()); + } + } else + min = parseInt(strValue); + } + } else { + min = parseInt(strValue); + if (!supportsNegatives && min < 0) + throw new CITParsingException("Negatives are not allowed", properties, value.position()); + } + + if (range) { + if (min == max) + range = false; + else if (min > max) + throw new CITParsingException("Could not parse range", properties, value.position()); + } + } catch (Exception e) { + throw e instanceof CITParsingException citE ? citE : new CITParsingException("Could not parse integer", properties, value.position(), e); + } + } + + @Override + public boolean test(CITContext context) { + int value = getValue(context); + + if (percentage) { + double percentValue = 100d * (double) value / (double) getPercentageTotalValue(context); + return range ? min <= percentValue && percentValue <= max : percentValue == (double) min; + } else + return range ? min <= value && value <= max : value == (double) min; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java new file mode 100644 index 0000000..151119b --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java @@ -0,0 +1,79 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; + +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; +import java.util.regex.Pattern; + +public abstract class ListCondition extends CITCondition { + private static final Pattern PATTERN_WHITESPACE = Pattern.compile("\\p{Zs}+"); + + private final Class conditionType; + protected final Type listType; + protected final Pattern delimiter; + protected final Supplier conditionSupplier; + + protected T[] conditions; + + protected ListCondition(Class conditionType, Type listType, Pattern delimiter, Supplier conditionSupplier) { + this.conditionType = conditionType; + this.listType = listType; + this.delimiter = delimiter; + this.conditionSupplier = conditionSupplier; + } + + protected ListCondition(Class conditionType, Supplier conditionSupplier) { + this(conditionType, Type.OR, PATTERN_WHITESPACE, conditionSupplier); + } + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + List conditions = new ArrayList<>(); + + for (String conditionValue : delimiter.split(value.value())) { + T condition = conditionSupplier.get(); + condition.load(new PropertyValue(value.keyMetadata(), conditionValue, value.delimiter(), value.position(), value.propertiesIdentifier(), value.packName()), properties); + conditions.add(condition); + } + + //noinspection unchecked + this.conditions = conditions.toArray((T[]) Array.newInstance(conditionType, 0)); + } + + @Override + public boolean test(CITContext context) { + return listType.test(conditions, context); + } + + public enum Type { + OR { + @Override + public boolean test(CITCondition[] conditions, CITContext context) { + for (CITCondition condition : conditions) + if (condition.test(context)) + return true; + + return false; + } + }, + AND { + @Override + public boolean test(CITCondition[] conditions, CITContext context) { + for (CITCondition condition : conditions) + if (!condition.test(context)) + return false; + + return true; + } + }; + + public abstract boolean test(CITCondition[] conditions, CITContext context); + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java index 54f26ff..6ad3783 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java @@ -8,20 +8,25 @@ import shcm.shsupercm.fabric.citresewn.cit.CITContext; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; -public class WeightCondition extends CITCondition { +public class WeightCondition extends IntegerCondition { @Entrypoint(CITConditionContainer.ENTRYPOINT) public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(WeightCondition.class, WeightCondition::new, "weight"); - public int weight = 0; + public WeightCondition() { + super(false, true, false); + } - @Override - public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { - this.weight = parseInteger(value, properties); + public int getWeight() { + return this.min; + } + + public void setWeight(int weight) { + this.min = weight; } @Override - public boolean test(CITContext context) { - return true; + protected int getValue(CITContext context) { + return 0; } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java index b3e126f..811d16b 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java @@ -3,6 +3,10 @@ package shcm.shsupercm.fabric.citresewn.ex; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; public class CITParsingException extends Exception { + public CITParsingException(String message, PropertyGroup propertyGroup, int position, Throwable throwable) { + super("Errored while parsing CIT: " + descriptionOf(message, propertyGroup, position), throwable); + } + public CITParsingException(String message, PropertyGroup propertyGroup, int position) { super("Errored while parsing CIT: " + descriptionOf(message, propertyGroup, position)); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 5096543..5f5a5c9 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -106,7 +106,7 @@ public class PackParser { conditions.removeIf(condition -> { if (condition instanceof WeightCondition weightCondition) { - weight.weight = weightCondition.weight; + weight.setWeight(weightCondition.getWeight()); return true; } @@ -115,6 +115,6 @@ public class PackParser { citType.load(conditions, properties, resourceManager); - return new CIT<>(properties.identifier, properties.packName, citType, conditions.toArray(new CITCondition[0]), weight.weight); + return new CIT<>(properties.identifier, properties.packName, citType, conditions.toArray(new CITCondition[0]), weight.getWeight()); } } -- cgit From 4615af9f467be065426d217375c3b3bd4203afe7 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Thu, 17 Feb 2022 12:54:13 +0200 Subject: Removed redundant arg from CITCondition#modifySibling --- src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java | 2 +- src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java index 03f118f..b5c1996 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java @@ -15,7 +15,7 @@ public abstract class CITCondition { return Collections.emptySet(); } - public T modifySibling(Class siblingType, T sibling) { + public T modifySibling(T sibling) { return sibling; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 5f5a5c9..303217c 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -99,7 +99,7 @@ public class PackParser { for (Class siblingConditionType : condition.siblingConditions()) conditions.replaceAll( siblingCondition -> siblingConditionType == siblingCondition.getClass() ? - condition.modifySibling(siblingConditionType, siblingCondition) : + condition.modifySibling(siblingCondition) : siblingCondition); WeightCondition weight = new WeightCondition(); -- cgit From a5e1db0be61f978693e922a5f867ed787016b564 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Thu, 17 Feb 2022 13:12:42 +0200 Subject: Improved exceptions --- src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java | 2 +- .../shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java index 53a5226..326ec76 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java @@ -44,7 +44,7 @@ public class CITRegistry { public static CITCondition parseCondition(PropertyKey key, PropertyValue value, PropertyGroup properties) throws CITParsingException { CITConditionContainer conditionContainer = CONDITIONS.get(key); if (conditionContainer == null) { - logWarnLoading(CITParsingException.descriptionOf("Unknown condition type", properties, value.position())); + logWarnLoading(CITParsingException.descriptionOf("Unknown condition type \"" + key.toString() + "\"", properties, value.position())); return new AlwaysFailCondition(); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java index b861a63..37a698d 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java @@ -11,4 +11,9 @@ public record PropertyKey(String namespace, String path) { } return new PropertyKey(split[0], split[1]); } + + @Override + public String toString() { + return namespace + ":" + path; + } } -- cgit From 1527eeccd5608ce1bee91336ef3b1185529ba67f Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Thu, 17 Feb 2022 13:33:43 +0200 Subject: Re-added Broken Paths Will now notify in the logs when encountering a broken path. --- .../fabric/citresewn/config/BrokenPaths.java | 5 +++ .../config/CITResewnMixinConfiguration.java | 2 +- .../AbstractFileResourcePackMixin.java | 49 ++++++++++++++++++++++ .../mixin/broken_paths/IdentifierMixin.java | 24 +++++++++++ .../ReloadableResourceManagerImplMixin.java | 33 +++++++++++++++ .../ResourcePackCompatibilityMixin.java | 26 ++++++++++++ src/main/resources/citresewn.mixins.json | 1 + 7 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/config/BrokenPaths.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/BrokenPaths.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/BrokenPaths.java new file mode 100644 index 0000000..c89e3cb --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/BrokenPaths.java @@ -0,0 +1,5 @@ +package shcm.shsupercm.fabric.citresewn.config; + +public class BrokenPaths { + public static boolean processingBrokenPaths = false; +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java index 4247494..29f64e9 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java @@ -29,7 +29,7 @@ public class CITResewnMixinConfiguration implements IMixinConfigPlugin { if (mixinClassName.startsWith("broken_paths")) return broken_paths; - if (mixinClassName.equals("core.GroupResourcePackAccessor")) + if (mixinClassName.equals("GroupResourcePackAccessor")) return FabricLoader.getInstance().isModLoaded("fabric-resource-loader-v0"); return true; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java new file mode 100644 index 0000000..9ad7992 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java @@ -0,0 +1,49 @@ +package shcm.shsupercm.fabric.citresewn.mixin.broken_paths; + +import net.minecraft.resource.AbstractFileResourcePack; +import net.minecraft.resource.DirectoryResourcePack; +import net.minecraft.resource.ResourcePack; +import net.minecraft.resource.ZipResourcePack; +import net.minecraft.resource.metadata.PackResourceMetadata; +import net.minecraft.resource.metadata.ResourceMetadataReader; +import net.minecraft.util.Identifier; +import net.minecraft.util.InvalidIdentifierException; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.zip.ZipFile; + +@Mixin(AbstractFileResourcePack.class) +public abstract class AbstractFileResourcePackMixin implements ResourcePack { + @Shadow @Final protected File base; + + @SuppressWarnings({"unchecked", "ConstantConditions", "EqualsBetweenInconvertibleTypes"}) + @Inject(method = "parseMetadata(Lnet/minecraft/resource/metadata/ResourceMetadataReader;)Ljava/lang/Object;", cancellable = true, at = @At("RETURN")) + public void parseMetadata(ResourceMetadataReader metaReader, CallbackInfoReturnable cir) { + if (cir.getReturnValue() != null) + try { + if (this.getClass().equals(ZipResourcePack.class)) { + try (ZipFile zipFile = new ZipFile(base)) { + zipFile.stream() + .forEach(entry -> { + if (entry.getName().startsWith("assets")) + new Identifier("minecraft", entry.getName()); + }); + } + } else if (this.getClass().equals(DirectoryResourcePack.class)) { + final Path assets = new File(base, "assets").toPath(); + Files.walk(assets) + .forEach(path -> new Identifier("minecraft", assets.relativize(path).toString().replace('\\', '/'))); + } + } catch (InvalidIdentifierException e) { + cir.setReturnValue((T) new PackResourceMetadata(cir.getReturnValue().getDescription(), Integer.MAX_VALUE - 53)); + } catch (Exception ignored) {} + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java new file mode 100644 index 0000000..0be08f9 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java @@ -0,0 +1,24 @@ +package shcm.shsupercm.fabric.citresewn.mixin.broken_paths; + +import net.minecraft.util.Identifier; +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; +import shcm.shsupercm.fabric.citresewn.CITResewn; + +import static shcm.shsupercm.fabric.citresewn.config.BrokenPaths.processingBrokenPaths; + +@Mixin(Identifier.class) +public class IdentifierMixin { + @Inject(method = "isPathValid", cancellable = true, at = @At("RETURN")) + private static void processBrokenPaths(String path, CallbackInfoReturnable cir) { + if (!processingBrokenPaths) + return; + + if (!cir.getReturnValue()) { + CITResewn.logWarnLoading("Warning: Encountered broken path: \"" + path + "\""); + cir.setReturnValue(true); + } + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java new file mode 100644 index 0000000..3f54be3 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java @@ -0,0 +1,33 @@ +package shcm.shsupercm.fabric.citresewn.mixin.broken_paths; + +import net.minecraft.resource.ReloadableResourceManagerImpl; +import net.minecraft.resource.ResourcePack; +import net.minecraft.resource.ResourceReload; +import net.minecraft.resource.ResourceType; +import net.minecraft.util.Unit; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import shcm.shsupercm.fabric.citresewn.CITResewn; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; + +import static shcm.shsupercm.fabric.citresewn.config.BrokenPaths.processingBrokenPaths; + +@Mixin(ReloadableResourceManagerImpl.class) +public class ReloadableResourceManagerImplMixin { + @Shadow @Final private ResourceType type; + + @Inject(method = "reload", at = @At("RETURN")) + public void onReload(Executor prepareExecutor, Executor applyExecutor, CompletableFuture initialStage, List packs, CallbackInfoReturnable cir) { + if (processingBrokenPaths = this.type == ResourceType.CLIENT_RESOURCES) { + CITResewn.LOG.error("[citresewn] Caution! Broken paths is enabled!"); + cir.getReturnValue().whenComplete().thenRun(() -> processingBrokenPaths = false); + } + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java new file mode 100644 index 0000000..f187a56 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java @@ -0,0 +1,26 @@ +package shcm.shsupercm.fabric.citresewn.mixin.broken_paths; + +import net.minecraft.resource.ResourcePackCompatibility; +import net.minecraft.resource.ResourceType; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(ResourcePackCompatibility.class) +public abstract class ResourcePackCompatibilityMixin { + private static final ResourcePackCompatibility BROKEN_PATHS = ResourcePackCompatibility("BROKEN_PATHS", -1, "broken_paths"); + + @SuppressWarnings("InvokerTarget") + @Invoker("") + public static ResourcePackCompatibility ResourcePackCompatibility(String internalName, int internalId, String translationSuffix) { + throw new AssertionError(); + } + + @Inject(method = "from(ILnet/minecraft/resource/ResourceType;)Lnet/minecraft/resource/ResourcePackCompatibility;", cancellable = true, at = @At("HEAD")) + private static void redirectBrokenPathsCompatibility(int packVersion, ResourceType type, CallbackInfoReturnable cir) { + if (packVersion == Integer.MAX_VALUE - 53) + cir.setReturnValue(BROKEN_PATHS); + } +} diff --git a/src/main/resources/citresewn.mixins.json b/src/main/resources/citresewn.mixins.json index 394941e..31b8216 100644 --- a/src/main/resources/citresewn.mixins.json +++ b/src/main/resources/citresewn.mixins.json @@ -2,6 +2,7 @@ "required": true, "minVersion": "0.8", "package": "shcm.shsupercm.fabric.citresewn.mixin", + "plugin": "shcm.shsupercm.fabric.citresewn.config.CITResewnMixinConfiguration", "compatibilityLevel": "JAVA_17", "injectors": { "defaultRequire": 1 -- cgit From a50fd46a00b56a15161ae3288cf2ad55d9badc17 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Thu, 17 Feb 2022 15:04:18 +0200 Subject: Added more common condition types --- .../cit/conditions/ConditionDamageMask.java | 8 ++++ .../cit/builtin/conditions/BooleanCondition.java | 28 ++++++++++++ .../cit/builtin/conditions/EnumCondition.java | 50 ++++++++++++++++++++++ .../builtin/conditions/IdentifierCondition.java | 29 +++++++++++++ 4 files changed, 115 insertions(+) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionDamageMask.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionDamageMask.java index 6c8e9e0..01d33fe 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionDamageMask.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionDamageMask.java @@ -2,9 +2,12 @@ package shcm.shsupercm.fabric.citresewn.defaults.cit.conditions; import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; import shcm.shsupercm.fabric.citresewn.cit.CITContext; import shcm.shsupercm.fabric.citresewn.cit.builtin.conditions.IntegerCondition; +import java.util.Set; + public class ConditionDamageMask extends IntegerCondition { @Entrypoint(CITConditionContainer.ENTRYPOINT) public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(ConditionDamageMask.class, ConditionDamageMask::new, @@ -27,4 +30,9 @@ public class ConditionDamageMask extends IntegerCondition { public int getMask() { return this.min; } + + @Override + public Set> siblingConditions() { + return Set.of(ConditionDamage.class); + } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java new file mode 100644 index 0000000..fcf976c --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java @@ -0,0 +1,28 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; + +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +public abstract class BooleanCondition extends CITCondition { + protected boolean value; + + protected abstract boolean getValue(CITContext context); + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + if (value.value().equalsIgnoreCase("true")) + this.value = true; + else if (value.value().equalsIgnoreCase("false")) + this.value = false; + else + throw new CITParsingException("Not a boolean", properties, value.position()); + } + + @Override + public boolean test(CITContext context) { + return getValue(context) == this.value; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java new file mode 100644 index 0000000..cdfd65d --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java @@ -0,0 +1,50 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; + +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +import java.util.function.Supplier; + +public abstract class EnumCondition> extends CITCondition { + protected final Supplier values; + protected final boolean ignoreCase; + + protected T value; + + protected abstract T getValue(CITContext context); + + protected EnumCondition(Supplier values, boolean ignoreCase) { + this.values = values; + this.ignoreCase = ignoreCase; + } + + protected EnumCondition(Supplier values) { + this(values, true); + } + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + for (T enumConstant : values.get()) + for (String alias : ((Aliased) enumConstant).getAliases()) + if (ignoreCase ? alias.equalsIgnoreCase(value.value()) : alias.equals(value.value())) { + this.value = enumConstant; + return; + } + + throw new CITParsingException("Unrecognized value", properties, value.position()); + } + + @Override + public boolean test(CITContext context) { + return getValue(context) == this.value; + } + + public interface Aliased { + default String[] getAliases() { + return new String[] { ((Enum) this).name() }; + } + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java new file mode 100644 index 0000000..2f45f2f --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java @@ -0,0 +1,29 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; + +import net.minecraft.util.Identifier; +import net.minecraft.util.InvalidIdentifierException; +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +public abstract class IdentifierCondition extends CITCondition { + protected Identifier value; + + protected abstract Identifier getValue(CITContext context); + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + try { + this.value = new Identifier(value.value()); + } catch (InvalidIdentifierException e) { + throw new CITParsingException(e.getMessage(), properties, value.position()); + } + } + + @Override + public boolean test(CITContext context) { + return this.value.equals(getValue(context)); + } +} -- cgit From da0213efc8313c0ae4589f6f8e748d518f96b757 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Thu, 17 Feb 2022 16:24:24 +0200 Subject: Cleaned common condition types api a bit Added long common condition type --- .../cit/builtin/conditions/BooleanCondition.java | 4 +- .../cit/builtin/conditions/DoubleCondition.java | 6 +- .../cit/builtin/conditions/EnumCondition.java | 4 +- .../cit/builtin/conditions/FloatCondition.java | 6 +- .../builtin/conditions/IdentifierCondition.java | 4 +- .../cit/builtin/conditions/IntegerCondition.java | 8 +- .../cit/builtin/conditions/LongCondition.java | 134 +++++++++++++++++++++ 7 files changed, 156 insertions(+), 10 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/LongCondition.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java index fcf976c..62f1da1 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java @@ -9,7 +9,9 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; public abstract class BooleanCondition extends CITCondition { protected boolean value; - protected abstract boolean getValue(CITContext context); + protected boolean getValue(CITContext context) { + throw new AssertionError(); + } @Override public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java index 60b6e1a..0f392d4 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java @@ -20,10 +20,12 @@ public abstract class DoubleCondition extends CITCondition { this.supportsPercentages = supportsPercentages; } - protected abstract double getValue(CITContext context); + protected double getValue(CITContext context) { + throw new AssertionError(); + } protected double getPercentageTotalValue(CITContext context) { - return 0; + throw new AssertionError(); } @Override diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java index cdfd65d..56f5fb7 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java @@ -14,7 +14,9 @@ public abstract class EnumCondition values, boolean ignoreCase) { this.values = values; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java index 24de921..afc3954 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java @@ -20,10 +20,12 @@ public abstract class FloatCondition extends CITCondition { this.supportsPercentages = supportsPercentages; } - protected abstract float getValue(CITContext context); + protected float getValue(CITContext context) { + throw new AssertionError(); + } protected float getPercentageTotalValue(CITContext context) { - return 0; + throw new AssertionError(); } @Override diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java index 2f45f2f..0df5330 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java @@ -11,7 +11,9 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; public abstract class IdentifierCondition extends CITCondition { protected Identifier value; - protected abstract Identifier getValue(CITContext context); + protected Identifier getValue(CITContext context) { + throw new AssertionError(); + } @Override public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java index 6701338..13c87c6 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java @@ -20,10 +20,12 @@ public abstract class IntegerCondition extends CITCondition { this.supportsPercentages = supportsPercentages; } - protected abstract int getValue(CITContext context); + protected int getValue(CITContext context) { + throw new AssertionError(); + } protected int getPercentageTotalValue(CITContext context) { - return 0; + throw new AssertionError(); } @Override @@ -127,6 +129,6 @@ public abstract class IntegerCondition extends CITCondition { double percentValue = 100d * (double) value / (double) getPercentageTotalValue(context); return range ? min <= percentValue && percentValue <= max : percentValue == (double) min; } else - return range ? min <= value && value <= max : value == (double) min; + return range ? min <= value && value <= max : value == min; } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/LongCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/LongCondition.java new file mode 100644 index 0000000..97f58b5 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/LongCondition.java @@ -0,0 +1,134 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; + +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +import static java.lang.Long.*; + +public abstract class LongCondition extends CITCondition { + protected final boolean supportsRanges, supportsNegatives, supportsPercentages; + + protected long min, max; + protected boolean range = false, percentage = false; + + protected LongCondition(boolean supportsRanges, boolean supportsNegatives, boolean supportsPercentages) { + this.supportsRanges = supportsRanges; + this.supportsNegatives = supportsNegatives; + this.supportsPercentages = supportsPercentages; + } + + protected long getValue(CITContext context) { + throw new AssertionError(); + } + + protected long getPercentageTotalValue(CITContext context) { + throw new AssertionError(); + } + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + String strValue = value.value(); + if (supportsPercentages && (percentage = strValue.contains("%"))) + strValue = strValue.replace("%", ""); + + try { + if (range = supportsRanges) { + if (supportsNegatives) { + switch (strValue.length() - strValue.replace("-", "").length()) { // dashesCount + case 0 -> { + range = false; + min = parseLong(strValue); + } + case 1 -> { + if (strValue.startsWith("-")) { + range = false; + min = parseLong(strValue); + } else if (strValue.endsWith("-")) { + min = parseLong(strValue.substring(0, strValue.length() - 1)); + max = MAX_VALUE; + } else { + String[] split = strValue.split("-"); + min = parseLong(split[0]); + max = parseLong(split[1]); + } + } + case 2 -> { + if (strValue.startsWith("--")) { + min = MIN_VALUE; + max = parseLong(strValue.substring(1)); + } else if (strValue.startsWith("-") && strValue.endsWith("-")) { + min = parseLong(strValue.substring(0, strValue.length() - 1)); + max = MAX_VALUE; + } else if (strValue.startsWith("-") && !strValue.endsWith("-") && !strValue.contains("--")) { + int lastDash = strValue.lastIndexOf('-'); + min = parseLong(strValue.substring(0, lastDash)); + max = parseLong(strValue.substring(lastDash + 1)); + } else + throw new CITParsingException("Could not parse range", properties, value.position()); + } + case 3 -> { + if (!strValue.contains("---") && strValue.startsWith("-")) { + String[] split = strValue.split("--"); + if (split.length != 2 || split[0].isEmpty() || split[1].isEmpty()) + throw new CITParsingException("Could not parse range", properties, value.position()); + + min = parseLong(split[0]); + max = -parseLong(split[1]); + } else + throw new CITParsingException("Could not parse range", properties, value.position()); + } + + default -> throw new CITParsingException("Could not parse range", properties, value.position()); + } + } else { + if (range = strValue.contains("-")) { + if (strValue.contains("--")) + throw new CITParsingException("Could not parse range", properties, value.position()); + String[] split = strValue.split("-"); + switch (split.length) { + case 1 -> { + min = parseLong(split[0]); + max = MAX_VALUE; + } + case 2 -> { + if (strValue.endsWith("-")) + throw new CITParsingException("Could not parse range", properties, value.position()); + min = split[0].isEmpty() ? MIN_VALUE : parseLong(split[0]); + max = split[1].isEmpty() ? MAX_VALUE : parseLong(split[1]); + } + default -> throw new CITParsingException("Could not parse range", properties, value.position()); + } + } else + min = parseLong(strValue); + } + } else { + min = parseLong(strValue); + if (!supportsNegatives && min < 0) + throw new CITParsingException("Negatives are not allowed", properties, value.position()); + } + + if (range) { + if (min == max) + range = false; + else if (min > max) + throw new CITParsingException("Could not parse range", properties, value.position()); + } + } catch (Exception e) { + throw e instanceof CITParsingException citE ? citE : new CITParsingException("Could not parse long", properties, value.position(), e); + } + } + + @Override + public boolean test(CITContext context) { + long value = getValue(context); + + if (percentage) { + double percentValue = 100d * (double) value / (double) getPercentageTotalValue(context); + return range ? min <= percentValue && percentValue <= max : percentValue == (double) min; + } else + return range ? min <= value && value <= max : value == min; + } +} -- cgit From 9db8d1eafb861f6512e7ae0d8584b5ace676cc3c Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Thu, 17 Feb 2022 17:15:26 +0200 Subject: Implemented enchantments and enchantmentLevels conditions --- .../cit/conditions/ConditionEnchantmentLevels.java | 62 ++++++++++++++++++++++ .../cit/conditions/ConditionEnchantments.java | 59 ++++++++++++++++++++ .../shsupercm/fabric/citresewn/cit/CITContext.java | 19 +++++++ 3 files changed, 140 insertions(+) create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionEnchantmentLevels.java create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionEnchantments.java (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionEnchantmentLevels.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionEnchantmentLevels.java new file mode 100644 index 0000000..da6b4f4 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionEnchantmentLevels.java @@ -0,0 +1,62 @@ +package shcm.shsupercm.fabric.citresewn.defaults.cit.conditions; + +import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; +import net.minecraft.util.Identifier; +import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.cit.builtin.conditions.IntegerCondition; +import shcm.shsupercm.fabric.citresewn.cit.builtin.conditions.ListCondition; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class ConditionEnchantmentLevels extends ListCondition { + @Entrypoint(CITConditionContainer.ENTRYPOINT) + public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(ConditionEnchantmentLevels.class, ConditionEnchantmentLevels::new, + "enchantment_levels", "enchantmentLevels"); + + protected Set enchantments = null; + + public ConditionEnchantmentLevels() { + super(EnchantmentLevelCondition.class, EnchantmentLevelCondition::new); + } + + @Override + public Set> siblingConditions() { + return Set.of(ConditionEnchantments.class); + } + + @Override + public T modifySibling(T sibling) { + if (sibling instanceof ConditionEnchantments conditionEnchantments) { + if (enchantments == null) { + enchantments = new HashSet<>(); + for (EnchantmentLevelCondition subCondition : this.conditions) + subCondition.enchantments = enchantments; + } + enchantments.addAll(Arrays.asList(conditionEnchantments.getEnchantments())); + } + + return sibling; + } + + protected static class EnchantmentLevelCondition extends IntegerCondition { + protected Set enchantments = null; + + protected EnchantmentLevelCondition() { + super(true, false, false); + } + + @Override + public boolean test(CITContext context) { + for (Map.Entry entry : context.enchantments().entrySet()) + if ((enchantments == null || enchantments.contains(entry.getKey())) && entry.getValue() != null && (range ? min <= entry.getValue() && entry.getValue() <= max : entry.getValue() == min)) + return true; + + return false; + } + } +} diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionEnchantments.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionEnchantments.java new file mode 100644 index 0000000..301f9c1 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionEnchantments.java @@ -0,0 +1,59 @@ +package shcm.shsupercm.fabric.citresewn.defaults.cit.conditions; + +import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; +import net.minecraft.util.Identifier; +import net.minecraft.util.registry.Registry; +import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.cit.builtin.conditions.IdentifierCondition; +import shcm.shsupercm.fabric.citresewn.cit.builtin.conditions.ListCondition; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +import java.util.Set; + +public class ConditionEnchantments extends ListCondition { + @Entrypoint(CITConditionContainer.ENTRYPOINT) + public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(ConditionEnchantments.class, ConditionEnchantments::new, + "enchantments", "enchantmentIDs"); + + public ConditionEnchantments() { + super(EnchantmentCondition.class, EnchantmentCondition::new); + } + + public Identifier[] getEnchantments() { + Identifier[] enchantments = new Identifier[this.conditions.length]; + + for (int i = 0; i < this.conditions.length; i++) + enchantments[i] = this.conditions[i].getValue(null); + + return enchantments; + } + + @Override + public Set> siblingConditions() { + return Set.of(ConditionEnchantmentLevels.class); + } + + protected static class EnchantmentCondition extends IdentifierCondition { + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + super.load(value, properties); + + if (!Registry.ENCHANTMENT.containsId(this.value)) + warn(this.value + " is not in the enchantment registry", value, properties); + } + + @Override + public boolean test(CITContext context) { + return context.enchantments().containsKey(this.value); + } + + @Override + protected Identifier getValue(CITContext context) { + return this.value; + } + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java index b2dd2cd..c5f1922 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java @@ -1,10 +1,18 @@ package shcm.shsupercm.fabric.citresewn.cit; import net.minecraft.client.MinecraftClient; +import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.LivingEntity; +import net.minecraft.item.EnchantedBookItem; import net.minecraft.item.ItemStack; +import net.minecraft.item.Items; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtElement; +import net.minecraft.util.Identifier; import net.minecraft.world.World; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.Objects; public class CITContext { @@ -12,12 +20,23 @@ public class CITContext { public final World world; public final LivingEntity entity; + private Map enchantments = null; + public CITContext(ItemStack stack, World world, LivingEntity entity) { this.stack = stack; this.world = world == null ? MinecraftClient.getInstance().world : world; this.entity = entity; } + public Map enchantments() { + if (this.enchantments == null) { + this.enchantments = new LinkedHashMap<>(); + for (NbtElement nbtElement : stack.isOf(Items.ENCHANTED_BOOK) ? EnchantedBookItem.getEnchantmentNbt(stack) : stack.getEnchantments()) + this.enchantments.put(EnchantmentHelper.getIdFromNbt((NbtCompound) nbtElement), EnchantmentHelper.getLevelFromNbt((NbtCompound) nbtElement)); + } + return this.enchantments; + } + @Override public boolean equals(Object obj) { return obj instanceof CITContext that && -- cgit From 75e42832339cc0cfb4584ff45a5d57c335d4618d Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 18 Feb 2022 08:16:08 +0200 Subject: Fixed sibling condition npe --- src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 303217c..4c5b116 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -98,7 +98,7 @@ public class PackParser { if (condition != null) for (Class siblingConditionType : condition.siblingConditions()) conditions.replaceAll( - siblingCondition -> siblingConditionType == siblingCondition.getClass() ? + siblingCondition -> siblingCondition != null && siblingConditionType == siblingCondition.getClass() ? condition.modifySibling(siblingCondition) : siblingCondition); -- cgit From 9a3952f2a17a94ff98494856b1ed9754d7b6ead6 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 18 Feb 2022 08:31:18 +0200 Subject: Fixed ambiguous conditions list for type loading --- .../shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeArmor.java | 2 +- .../shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeElytra.java | 2 +- .../shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java | 2 +- .../shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java | 2 +- src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java | 2 +- src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeArmor.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeArmor.java index 2b857fa..9f0beed 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeArmor.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeArmor.java @@ -23,7 +23,7 @@ public class TypeArmor extends CITType { } @Override - public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { + public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { } diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeElytra.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeElytra.java index f0f7540..1b5367b 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeElytra.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeElytra.java @@ -23,7 +23,7 @@ public class TypeElytra extends CITType { } @Override - public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { + public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { } diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java index 3a340b1..566273a 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java @@ -35,7 +35,7 @@ public class TypeEnchantment extends CITType { } @Override - public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { + public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { } diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java index 9cb623e..02a2bf1 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -62,7 +62,7 @@ public class TypeItem extends CITType { } @Override - public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { + public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { for (CITCondition condition : conditions) if (condition instanceof ConditionItems conditionItems) items.addAll(Arrays.asList(conditionItems.items)); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java index aed784a..468c1cb 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java @@ -13,7 +13,7 @@ import java.util.*; public abstract class CITType { public abstract Set typeProperties(); - public abstract void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException; + public abstract void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException; protected void warn(String message, PropertyValue value, PropertyGroup properties) { CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value.position())); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 4c5b116..163435b 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -80,7 +80,7 @@ public class PackParser { public static CIT parseCIT(PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { CITType citType = CITRegistry.parseType(properties); - ArrayList conditions = new ArrayList<>(); + List conditions = new ArrayList<>(); Set ignoredProperties = citType.typeProperties(); -- cgit From 429b299266e9633e325e4d57e2a582fde1666e7a Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 18 Feb 2022 08:52:52 +0200 Subject: Fixed item name from properties file name --- .../citresewn/defaults/cit/conditions/ConditionItems.java | 5 +++++ .../fabric/citresewn/defaults/cit/types/TypeItem.java | 11 ++++++++++- .../shsupercm/fabric/citresewn/pack/format/PropertyGroup.java | 4 ++++ 3 files changed, 19 insertions(+), 1 deletion(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java index 73b79e0..117aa47 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/conditions/ConditionItems.java @@ -26,6 +26,11 @@ public class ConditionItems extends ListCondition super(ItemCondition.class, ItemCondition::new); } + public ConditionItems(Item... items) { + this(); + this.items = items; + } + @Override public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { super.load(value, properties); diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java index 02a2bf1..aaca882 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -68,7 +68,16 @@ public class TypeItem extends CITType { items.addAll(Arrays.asList(conditionItems.items)); if (this.items.size() == 0) - throw new CITParsingException("Not targeting any item type", properties, -1); + try { + Identifier propertiesName = new Identifier(properties.stripName()); + if (!Registry.ITEM.containsId(propertiesName)) + throw new Exception(); + Item item = Registry.ITEM.get(propertiesName); + conditions.add(new ConditionItems(item)); + this.items.add(item); + } catch (Exception ignored) { + throw new CITParsingException("Not targeting any item type", properties, -1); + } Identifier assetIdentifier; PropertyValue modelProp = properties.getLastWithoutMetadata("citresewn", "model"); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java index b2806a2..5252330 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java @@ -49,6 +49,10 @@ public abstract class PropertyGroup { return value; } + public String stripName() { + return identifier.getPath().substring(identifier.getPath().lastIndexOf('/') + 1, identifier.getPath().length() - getExtension().length()); + } + public static PropertyGroup tryParseGroup(String packName, Identifier identifier, InputStream is) throws IOException { PropertyGroup group = null; if (identifier.getPath().endsWith(PropertiesGroupAdapter.EXTENSION)) -- cgit From 93efe2624458a66da06d7edc572924be1c8c7168 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sun, 20 Feb 2022 10:52:50 +0200 Subject: Ported elytra type --- .../citresewn/defaults/cit/types/TypeElytra.java | 34 +++++++++++++++--- .../types/elytra/ElytraFeatureRendererMixin.java | 41 ++++++++++++++++++++++ .../mixin/types/elytra/ItemStackMixin.java | 16 +++++++++ .../shsupercm/fabric/citresewn/cit/CITType.java | 2 +- 4 files changed, 88 insertions(+), 5 deletions(-) create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/elytra/ElytraFeatureRendererMixin.java create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/elytra/ItemStackMixin.java (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeElytra.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeElytra.java index 1b5367b..d50d084 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeElytra.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeElytra.java @@ -2,14 +2,15 @@ package shcm.shsupercm.fabric.citresewn.defaults.cit.types; import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import net.minecraft.resource.ResourceManager; +import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; -import shcm.shsupercm.fabric.citresewn.cit.CIT; -import shcm.shsupercm.fabric.citresewn.cit.CITCondition; -import shcm.shsupercm.fabric.citresewn.cit.CITType; +import shcm.shsupercm.fabric.citresewn.cit.*; +import shcm.shsupercm.fabric.citresewn.defaults.cit.conditions.ConditionItems; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; +import java.util.HashSet; import java.util.List; import java.util.Set; @@ -17,6 +18,8 @@ public class TypeElytra extends CITType { @Entrypoint(CITTypeContainer.ENTRYPOINT) public static final Container CONTAINER = new Container(); + public Identifier texture; + @Override public Set typeProperties() { return Set.of(PropertyKey.of("texture")); @@ -24,7 +27,12 @@ public class TypeElytra extends CITType { @Override public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { + if (conditions.removeIf(condition -> condition instanceof ConditionItems)) + warn("Type elytra does not support the items condition", null, properties); + texture = resolveAsset(properties.identifier, properties.getLastWithoutMetadata("citresewn", "texture"), "textures", ".png", resourceManager); + if (texture == null) + throw new CITParsingException("Texture not specified", properties, -1); } public static class Container extends CITTypeContainer { @@ -32,14 +40,32 @@ public class TypeElytra extends CITType { super(TypeElytra.class, TypeElytra::new, "elytra"); } + public Set> loaded = new HashSet<>(); + @Override public void load(List> parsedCITs) { - + loaded.addAll(parsedCITs); } @Override public void dispose() { + loaded.clear(); + } + public CIT getCIT(CITContext context) { + return ((CITCacheElytra) (Object) context.stack).citresewn$getCacheTypeElytra().get(context).get(); } + + public CIT getRealTimeCIT(CITContext context) { + for (CIT cit : loaded) + if (cit.test(context)) + return cit; + + return null; + } + } + + public interface CITCacheElytra { + CITCache.Single citresewn$getCacheTypeElytra(); } } diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/elytra/ElytraFeatureRendererMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/elytra/ElytraFeatureRendererMixin.java new file mode 100644 index 0000000..ab4d420 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/elytra/ElytraFeatureRendererMixin.java @@ -0,0 +1,41 @@ +package shcm.shsupercm.fabric.citresewn.defaults.mixin.types.elytra; + +import net.minecraft.client.render.VertexConsumerProvider; +import net.minecraft.client.render.entity.feature.ElytraFeatureRenderer; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.entity.EquipmentSlot; +import net.minecraft.entity.LivingEntity; +import net.minecraft.item.ItemStack; +import net.minecraft.item.Items; +import net.minecraft.util.Identifier; +import org.spongepowered.asm.mixin.*; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; +import shcm.shsupercm.fabric.citresewn.cit.CIT; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; +import shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeElytra; + +import static shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeElytra.CONTAINER; + +@Mixin(ElytraFeatureRenderer.class) +public class ElytraFeatureRendererMixin { + @Shadow @Mutable @Final private static Identifier SKIN; + + private final static Identifier citresewn$ORIGINAL_SKIN = SKIN; + + @Inject(method = "render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;ILnet/minecraft/entity/LivingEntity;FFFFFF)V", at = @At("HEAD")) + public void citresewn$render(MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int i, LivingEntity livingEntity, float f, float g, float h, float j, float k, float l, CallbackInfo ci) { + if (!CITResewnConfig.INSTANCE.enabled || !ActiveCITs.isActive()) + return; + + ItemStack equippedStack = livingEntity.getEquippedStack(EquipmentSlot.CHEST); + if (!equippedStack.isOf(Items.ELYTRA)) + return; + + CIT cit = CONTAINER.getCIT(new CITContext(equippedStack, livingEntity.getWorld(), livingEntity)); + SKIN = cit == null ? citresewn$ORIGINAL_SKIN : cit.type.texture; + } +} \ No newline at end of file diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/elytra/ItemStackMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/elytra/ItemStackMixin.java new file mode 100644 index 0000000..a751fb9 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/elytra/ItemStackMixin.java @@ -0,0 +1,16 @@ +package shcm.shsupercm.fabric.citresewn.defaults.mixin.types.elytra; + +import net.minecraft.item.ItemStack; +import org.spongepowered.asm.mixin.Mixin; +import shcm.shsupercm.fabric.citresewn.cit.CITCache; +import shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeElytra; + +@Mixin(ItemStack.class) +public class ItemStackMixin implements TypeElytra.CITCacheElytra { + private final CITCache.Single citresewn$cacheTypeElytra = new CITCache.Single<>(TypeElytra.CONTAINER::getRealTimeCIT); + + @Override + public CITCache.Single citresewn$getCacheTypeElytra() { + return this.citresewn$cacheTypeElytra; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java index 468c1cb..c3bb134 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java @@ -16,7 +16,7 @@ public abstract class CITType { public abstract void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException; protected void warn(String message, PropertyValue value, PropertyGroup properties) { - CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value.position())); + CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value == null ? -1 : value.position())); } /** -- cgit From 2d99c1b5773eb4067bb873e21c409a9a2399ab3d Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Tue, 22 Feb 2022 17:11:14 +0200 Subject: Cleaned/fixed some stuff up --- .../shcm/shsupercm/fabric/citresewn/cit/CIT.java | 12 +++++++---- .../fabric/citresewn/cit/CITRegistry.java | 4 ++-- .../builtin/conditions/AlwaysFailCondition.java | 19 ---------------- .../cit/builtin/conditions/ConstantCondition.java | 25 ++++++++++++++++++++++ .../cit/builtin/conditions/WeightCondition.java | 5 ----- 5 files changed, 35 insertions(+), 30 deletions(-) delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/AlwaysFailCondition.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ConstantCondition.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java index 7cc5724..3bc708f 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java @@ -18,10 +18,14 @@ public class CIT { } public boolean test(CITContext context) { - for (CITCondition condition : conditions) - if (!condition.test(context)) - return false; + try { + for (CITCondition condition : conditions) + if (!condition.test(context)) + return false; - return true; + return true; + } catch (Exception ignored) { + return false; + } } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java index 326ec76..ff38ef8 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java @@ -4,7 +4,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; -import shcm.shsupercm.fabric.citresewn.cit.builtin.conditions.AlwaysFailCondition; +import shcm.shsupercm.fabric.citresewn.cit.builtin.conditions.ConstantCondition; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.ex.UnknownCITTypeException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; @@ -45,7 +45,7 @@ public class CITRegistry { CITConditionContainer conditionContainer = CONDITIONS.get(key); if (conditionContainer == null) { logWarnLoading(CITParsingException.descriptionOf("Unknown condition type \"" + key.toString() + "\"", properties, value.position())); - return new AlwaysFailCondition(); + return new ConstantCondition(false); } CITCondition condition = conditionContainer.createCondition.get(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/AlwaysFailCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/AlwaysFailCondition.java deleted file mode 100644 index 5c32d97..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/AlwaysFailCondition.java +++ /dev/null @@ -1,19 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; - -import shcm.shsupercm.fabric.citresewn.cit.CITCondition; -import shcm.shsupercm.fabric.citresewn.cit.CITContext; -import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; -import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; - -public class AlwaysFailCondition extends CITCondition { - @Override - public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { - - } - - @Override - public boolean test(CITContext context) { - return false; - } -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ConstantCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ConstantCondition.java new file mode 100644 index 0000000..081c2d8 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ConstantCondition.java @@ -0,0 +1,25 @@ +package shcm.shsupercm.fabric.citresewn.cit.builtin.conditions; + +import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITContext; +import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; + +public class ConstantCondition extends CITCondition { + public final boolean value; + + public ConstantCondition(boolean value) { + this.value = value; + } + + @Override + public void load(PropertyValue value, PropertyGroup properties) throws CITParsingException { + + } + + @Override + public boolean test(CITContext context) { + return value; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java index 6ad3783..2e887d6 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java @@ -24,9 +24,4 @@ public class WeightCondition extends IntegerCondition { public void setWeight(int weight) { this.min = weight; } - - @Override - protected int getValue(CITContext context) { - return 0; - } } -- cgit From 70b04c19b5c6da9d63a095fb7a2e17fd722c9cb1 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Wed, 23 Feb 2022 11:13:12 +0200 Subject: Ported more of the enchantment type --- .../defaults/cit/types/TypeEnchantment.java | 244 ++++++++++++++++++--- .../defaults/config/CITResewnDefaultsConfig.java | 2 +- .../enchantment/BufferBuilderStorageAccessor.java | 15 ++ .../types/enchantment/RenderPhaseAccessor.java | 21 ++ .../citresewn/pack/format/PropertyGroup.java | 8 + 5 files changed, 253 insertions(+), 37 deletions(-) create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/BufferBuilderStorageAccessor.java create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/RenderPhaseAccessor.java (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java index 760cc83..5fd6e3c 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java @@ -1,18 +1,28 @@ package shcm.shsupercm.fabric.citresewn.defaults.cit.types; +import com.mojang.blaze3d.systems.RenderSystem; import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; -import net.minecraft.client.render.RenderPhase; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.render.*; import net.minecraft.resource.ResourceManager; import net.minecraft.util.Identifier; +import net.minecraft.util.Util; +import net.minecraft.util.math.Matrix4f; +import net.minecraft.util.math.Vec3f; import org.lwjgl.opengl.GL11; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; import shcm.shsupercm.fabric.citresewn.cit.*; +import shcm.shsupercm.fabric.citresewn.defaults.config.CITResewnDefaultsConfig; +import shcm.shsupercm.fabric.citresewn.defaults.mixin.types.enchantment.BufferBuilderStorageAccessor; +import shcm.shsupercm.fabric.citresewn.defaults.mixin.types.enchantment.RenderPhaseAccessor; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import java.lang.ref.WeakReference; import java.util.*; +import java.util.function.Consumer; import static com.mojang.blaze3d.systems.RenderSystem.*; import static org.lwjgl.opengl.GL11.*; @@ -29,24 +39,68 @@ public class TypeEnchantment extends CITType { PropertyKey.of("speed"), PropertyKey.of("rotation"), PropertyKey.of("duration"), - PropertyKey.of("blend"), - PropertyKey.of("useGlint"), - PropertyKey.of("blur"), PropertyKey.of("r"), PropertyKey.of("g"), PropertyKey.of("b"), - PropertyKey.of("a")); + PropertyKey.of("a"), + PropertyKey.of("useGlint"), + PropertyKey.of("blur"), + PropertyKey.of("blend")); } public Identifier texture; - public float speed, rotation, duration, r, g, b, a; public int layer; + public float speed, rotation, duration, r, g, b, a; public boolean useGlint, blur; public Blend blend; + public final Map renderLayers = new EnumMap<>(GlintRenderLayer.class); + private final WrappedMethodIntensity methodIntensity = new WrappedMethodIntensity(); + @Override public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { + PropertyValue textureProp = properties.getLastWithoutMetadata("citresewn", "texture"); + if (textureProp == null) + throw new CITParsingException("No texture specified", properties, -1); + this.texture = resolveAsset(properties.identifier, textureProp, "textures", ".png", resourceManager); + if (this.texture == null) + throw new CITParsingException("Could not resolve texture", properties, textureProp.position()); + + PropertyValue layerProp = properties.getLastWithoutMetadataOrDefault("0", "citresewn", "layer"); + try { + this.layer = Integer.parseInt(layerProp.value()); + } catch (Exception e) { + throw new CITParsingException("Could not parse integer", properties, layerProp.position(), e); + } + this.speed = parseFloatOrZero("speed", properties); + this.rotation = parseFloatOrZero("rotation", properties); + this.duration = parseFloatOrZero("duration", properties); + this.r = parseFloatOrZero("r", properties); + this.g = parseFloatOrZero("g", properties); + this.b = parseFloatOrZero("b", properties); + this.a = parseFloatOrZero("a", properties); + + this.useGlint = Boolean.parseBoolean(properties.getLastWithoutMetadataOrDefault("false", "citresewn", "useGlint").value()); + this.blur = Boolean.parseBoolean(properties.getLastWithoutMetadataOrDefault("true", "citresewn", "blur").value()); + + PropertyValue blendProp = properties.getLastWithoutMetadataOrDefault("add", "citresewn", "blend"); + try { + this.blend = Blend.getBlend(blendProp.value()); + } catch (Exception e) { + throw new CITParsingException("Could not parse blending method", properties, blendProp.position(), e); + } + } + + private float parseFloatOrZero(String propertyName, PropertyGroup properties) throws CITParsingException { + PropertyValue property = properties.getLastWithoutMetadata("citresewn", propertyName); + if (property == null) + return 0f; + try { + return Float.parseFloat(property.value()); + } catch (Exception e) { + throw new CITParsingException("Could not parse float", properties, property.position(), e); + } } public static class Container extends CITTypeContainer { @@ -57,6 +111,9 @@ public class TypeEnchantment extends CITType { public List> loaded = new ArrayList<>(); public List>> loadedLayered = new ArrayList<>(); + private List> appliedContext = null; + public boolean shouldApply = false; + @Override public void load(List> parsedCITs) { loaded.addAll(parsedCITs); @@ -68,23 +125,47 @@ public class TypeEnchantment extends CITType { layers.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .forEachOrdered(layer -> loadedLayered.add(layer.getValue())); + + for (CIT cit : loaded) + for (GlintRenderLayer glintLayer : GlintRenderLayer.values()) { + RenderLayer renderLayer = glintLayer.build(cit.type, cit.propertiesIdentifier); + + cit.type.renderLayers.put(glintLayer, renderLayer); + ((BufferBuilderStorageAccessor) MinecraftClient.getInstance().getBufferBuilders()).getEntityBuilders().put(renderLayer, new BufferBuilder(renderLayer.getExpectedBufferSize())); + } } @Override public void dispose() { + appliedContext = null; + + for (CIT cit : loaded) + for (RenderLayer renderLayer : cit.type.renderLayers.values()) + ((BufferBuilderStorageAccessor) MinecraftClient.getInstance().getBufferBuilders()).getEntityBuilders().remove(renderLayer); + loaded.clear(); loadedLayered.clear(); } - public void apply(CITContext context) { + public void setContext(CITContext context) { if (context == null) { - //todo clear + appliedContext = null; return; } List>> cits = ((CITCacheEnchantment) (Object) context.stack).citresewn$getCacheTypeEnchantment().get(context); - //todo apply + appliedContext = new ArrayList<>(); + if (cits != null) + for (WeakReference> citRef : cits) + if (citRef != null) { + CIT cit = citRef.get(); + if (cit != null) + appliedContext.add(cit); + } + + if (appliedContext.isEmpty()) + appliedContext = null; } public List> getRealTimeCIT(CITContext context) { @@ -99,6 +180,107 @@ public class TypeEnchantment extends CITType { return cits; } } + + public enum GlintRenderLayer { + ARMOR_GLINT("armor_glint", 8f, layer -> layer + .shader(RenderPhaseAccessor.ARMOR_GLINT_SHADER()) + .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) + .cull(RenderPhaseAccessor.DISABLE_CULLING()) + .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST()) + .layering(RenderPhaseAccessor.VIEW_OFFSET_Z_LAYERING())), + ARMOR_ENTITY_GLINT("armor_entity_glint", 0.16f, layer -> layer + .shader(RenderPhaseAccessor.ARMOR_ENTITY_GLINT_SHADER()) + .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) + .cull(RenderPhaseAccessor.DISABLE_CULLING()) + .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST()) + .layering(RenderPhaseAccessor.VIEW_OFFSET_Z_LAYERING())), + GLINT_TRANSLUCENT("glint_translucent", 8f, layer -> layer + .shader(RenderPhaseAccessor.TRANSLUCENT_GLINT_SHADER()) + .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) + .cull(RenderPhaseAccessor.DISABLE_CULLING()) + .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST()) + .target(RenderPhaseAccessor.ITEM_TARGET())), + GLINT("glint", 8f, layer -> layer + .shader(RenderPhaseAccessor.GLINT_SHADER()) + .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) + .cull(RenderPhaseAccessor.DISABLE_CULLING()) + .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST())), + DIRECT_GLINT("glint_direct", 8f, layer -> layer + .shader(RenderPhaseAccessor.DIRECT_GLINT_SHADER()) + .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) + .cull(RenderPhaseAccessor.DISABLE_CULLING()) + .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST())), + ENTITY_GLINT("entity_glint", 0.16f, layer -> layer + .shader(RenderPhaseAccessor.ENTITY_GLINT_SHADER()) + .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) + .cull(RenderPhaseAccessor.DISABLE_CULLING()) + .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST()) + .target(RenderPhaseAccessor.ITEM_TARGET())), + DIRECT_ENTITY_GLINT("entity_glint_direct", 0.16f, layer -> layer + .shader(RenderPhaseAccessor.DIRECT_ENTITY_GLINT_SHADER()) + .writeMaskState(RenderPhaseAccessor.COLOR_MASK()) + .cull(RenderPhaseAccessor.DISABLE_CULLING()) + .depthTest(RenderPhaseAccessor.EQUAL_DEPTH_TEST())); + + public final String name; + private final Consumer setup; + private final float scale; + + GlintRenderLayer(String name, float scale, Consumer setup) { + this.name = name; + this.scale = scale; + this.setup = setup; + } + + public RenderLayer build(TypeEnchantment enchantment, Identifier propertiesIdentifier) { + final float speed = enchantment.speed, rotation = enchantment.rotation, r = enchantment.r, g = enchantment.g, b = enchantment.b, a = enchantment.a; + final WrappedMethodIntensity methodIntensity = enchantment.methodIntensity; + RenderLayer.MultiPhaseParameters.Builder layer = RenderLayer.MultiPhaseParameters.builder() + .texture(new RenderPhase.Texture(enchantment.texture, enchantment.blur, false)) + .texturing(new RenderPhase.Texturing("citresewn_glint_texturing", () -> { + float l = Util.getMeasuringTimeMs() * CITResewnDefaultsConfig.INSTANCE.type_enchantment_scroll_multiplier * speed; + float x = (l % 110000f) / 110000f; + float y = (l % 30000f) / 30000f; + Matrix4f matrix4f = Matrix4f.translate(-x, y, 0.0f); + matrix4f.multiply(Vec3f.POSITIVE_Z.getDegreesQuaternion(rotation + 10f)); + matrix4f.multiply(Matrix4f.scale(scale, scale, scale)); + setTextureMatrix(matrix4f); + + setShaderColor(r, g, b, a * methodIntensity.intensity); + }, () -> { + RenderSystem.resetTextureMatrix(); + + setShaderColor(1f, 1f, 1f, 1f); + })) + .transparency(enchantment.blend); + + this.setup.accept(layer); + + return RenderLayer.of("citresewn:enchantment_" + this.name + ":" + propertiesIdentifier.toString(), + VertexFormats.POSITION_TEXTURE, + VertexFormat.DrawMode.QUADS, + 256, + layer.build(false)); + } + + public VertexConsumer tryApply(VertexConsumer base, RenderLayer baseLayer, VertexConsumerProvider provider) { + if (!CONTAINER.shouldApply || CONTAINER.appliedContext == null || CONTAINER.appliedContext.size() == 0) + return null; + + VertexConsumer[] layers = new VertexConsumer[Math.min(CONTAINER.appliedContext.size(), Integer.MAX_VALUE /*todo cap global property*/)]; + + for (int i = 0; i < layers.length; i++) + layers[i] = provider.getBuffer(CONTAINER.appliedContext.get(i).type.renderLayers.get(GlintRenderLayer.this)); + + provider.getBuffer(baseLayer); // refresh base layer for armor consumer + + return base == null ? VertexConsumers.union(layers) : VertexConsumers.union(VertexConsumers.union(layers), base); + } + } + + private static class WrappedMethodIntensity { + public float intensity = 1f; + } public static class Blend extends RenderPhase.Transparency { private final int src, dst, srcAlpha, dstAlpha; @@ -127,30 +309,26 @@ public class TypeEnchantment extends CITType { disableBlend(); } - public static Blend getBlend(String blendString) throws BlendFormatException { + public static Blend getBlend(String blendString) throws Exception { try { //check named blending function return Named.valueOf(blendString.toUpperCase(Locale.ENGLISH)).blend; } catch (IllegalArgumentException ignored) { // create custom blending function - try { - String[] split = blendString.split(" "); - int src, dst, srcAlpha, dstAlpha; - if (split.length == 2) { - src = parseGLConstant(split[0]); - dst = parseGLConstant(split[1]); - srcAlpha = GL_ZERO; - dstAlpha = GL_ONE; - } else if (split.length == 4) { - src = parseGLConstant(split[0]); - dst = parseGLConstant(split[1]); - srcAlpha = parseGLConstant(split[2]); - dstAlpha = parseGLConstant(split[3]); - } else - throw new Exception(); - - return new Blend("custom_" + src + "_" + dst + "_" + srcAlpha + "_" + dstAlpha, src, dst, srcAlpha, dstAlpha); - } catch (Exception e) { - throw new BlendFormatException(); - } + String[] split = blendString.split("\\p{Zs}+"); + int src, dst, srcAlpha, dstAlpha; + if (split.length == 2) { + src = parseGLConstant(split[0]); + dst = parseGLConstant(split[1]); + srcAlpha = GL_ZERO; + dstAlpha = GL_ONE; + } else if (split.length == 4) { + src = parseGLConstant(split[0]); + dst = parseGLConstant(split[1]); + srcAlpha = parseGLConstant(split[2]); + dstAlpha = parseGLConstant(split[3]); + } else + throw new Exception(); + + return new Blend("custom_" + src + "_" + dst + "_" + srcAlpha + "_" + dstAlpha, src, dst, srcAlpha, dstAlpha); } } @@ -185,12 +363,6 @@ public class TypeEnchantment extends CITType { return s.startsWith("0x") ? Integer.parseInt(s.substring(2), 16) : Integer.parseInt(s); } - - public static class BlendFormatException extends Exception { - public BlendFormatException() { - super("Not a valid blending method"); - } - } } public interface CITCacheEnchantment { diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfig.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfig.java index 0787fba..791205b 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfig.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfig.java @@ -8,7 +8,7 @@ import shcm.shsupercm.fabric.citresewn.CITResewn; import java.io.*; public class CITResewnDefaultsConfig { - + public float type_enchantment_scroll_multiplier = 1f; private static final File FILE = new File("config/citresewn-defaults.json"); diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/BufferBuilderStorageAccessor.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/BufferBuilderStorageAccessor.java new file mode 100644 index 0000000..e23e091 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/BufferBuilderStorageAccessor.java @@ -0,0 +1,15 @@ +package shcm.shsupercm.fabric.citresewn.defaults.mixin.types.enchantment; + +import net.minecraft.client.render.BufferBuilder; +import net.minecraft.client.render.BufferBuilderStorage; +import net.minecraft.client.render.RenderLayer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +import java.util.SortedMap; + +@Mixin(BufferBuilderStorage.class) +public interface BufferBuilderStorageAccessor { + @Accessor + SortedMap getEntityBuilders(); +} diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/RenderPhaseAccessor.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/RenderPhaseAccessor.java new file mode 100644 index 0000000..b2a59b4 --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/RenderPhaseAccessor.java @@ -0,0 +1,21 @@ +package shcm.shsupercm.fabric.citresewn.defaults.mixin.types.enchantment; + +import net.minecraft.client.render.RenderPhase; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(RenderPhase.class) +public interface RenderPhaseAccessor { + @Accessor("ARMOR_GLINT_SHADER") static RenderPhase.Shader ARMOR_GLINT_SHADER() { throw new RuntimeException(); } + @Accessor("ARMOR_ENTITY_GLINT_SHADER") static RenderPhase.Shader ARMOR_ENTITY_GLINT_SHADER() { throw new RuntimeException(); } + @Accessor("TRANSLUCENT_GLINT_SHADER") static RenderPhase.Shader TRANSLUCENT_GLINT_SHADER() { throw new RuntimeException(); } + @Accessor("GLINT_SHADER") static RenderPhase.Shader GLINT_SHADER() { throw new RuntimeException(); } + @Accessor("DIRECT_GLINT_SHADER") static RenderPhase.Shader DIRECT_GLINT_SHADER() { throw new RuntimeException(); } + @Accessor("ENTITY_GLINT_SHADER") static RenderPhase.Shader ENTITY_GLINT_SHADER() { throw new RuntimeException(); } + @Accessor("DIRECT_ENTITY_GLINT_SHADER") static RenderPhase.Shader DIRECT_ENTITY_GLINT_SHADER() { throw new RuntimeException(); } + @Accessor("DISABLE_CULLING") static RenderPhase.Cull DISABLE_CULLING() { throw new RuntimeException(); } + @Accessor("EQUAL_DEPTH_TEST") static RenderPhase.DepthTest EQUAL_DEPTH_TEST() { throw new RuntimeException(); } + @Accessor("COLOR_MASK") static RenderPhase.WriteMaskState COLOR_MASK() { throw new RuntimeException(); } + @Accessor("VIEW_OFFSET_Z_LAYERING") static RenderPhase.Layering VIEW_OFFSET_Z_LAYERING() { throw new RuntimeException(); } + @Accessor("ITEM_TARGET") static RenderPhase.Target ITEM_TARGET() { throw new RuntimeException(); } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java index 5252330..75949db 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java @@ -49,6 +49,14 @@ public abstract class PropertyGroup { return value; } + public PropertyValue getLastWithoutMetadataOrDefault(String defaultValue, String namespace, String... pathAliases) { + PropertyValue property = getLastWithoutMetadata(namespace, pathAliases); + if (property == null) + property = new PropertyValue(null, defaultValue, "=", -1, this.identifier, this.packName); + + return property; + } + public String stripName() { return identifier.getPath().substring(identifier.getPath().lastIndexOf('/') + 1, identifier.getPath().length() - getExtension().length()); } -- cgit From 5a08a70cf1d1c21992b21e484330fff54b744051 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 25 Feb 2022 13:21:43 +0200 Subject: Implemented the rest of the global properties --- .../defaults/cit/types/TypeEnchantment.java | 148 ++++++++++++++++++++- .../types/enchantment/MinecraftClientMixin.java | 16 +++ .../fabric/citresewn/pack/GlobalProperties.java | 2 +- 3 files changed, 158 insertions(+), 8 deletions(-) create mode 100644 defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/MinecraftClientMixin.java (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java index d28f441..6f9481e 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java @@ -4,14 +4,23 @@ import com.mojang.blaze3d.systems.RenderSystem; import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import net.minecraft.client.MinecraftClient; import net.minecraft.client.render.*; +import net.minecraft.enchantment.EnchantmentHelper; +import net.minecraft.item.EnchantedBookItem; +import net.minecraft.item.ItemStack; +import net.minecraft.item.Items; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtElement; import net.minecraft.resource.ResourceManager; +import net.minecraft.text.Text; import net.minecraft.util.Identifier; import net.minecraft.util.Util; import net.minecraft.util.math.Matrix4f; import net.minecraft.util.math.Vec3f; import org.lwjgl.opengl.GL11; +import shcm.shsupercm.fabric.citresewn.api.CITGlobalProperties; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; import shcm.shsupercm.fabric.citresewn.cit.*; +import shcm.shsupercm.fabric.citresewn.defaults.cit.conditions.ConditionEnchantments; import shcm.shsupercm.fabric.citresewn.defaults.config.CITResewnDefaultsConfig; import shcm.shsupercm.fabric.citresewn.defaults.mixin.types.enchantment.BufferBuilderStorageAccessor; import shcm.shsupercm.fabric.citresewn.defaults.mixin.types.enchantment.RenderPhaseAccessor; @@ -19,6 +28,7 @@ import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +import shcm.shsupercm.util.logic.Loops; import java.lang.ref.WeakReference; import java.util.*; @@ -28,6 +38,7 @@ import static com.mojang.blaze3d.systems.RenderSystem.*; import static org.lwjgl.opengl.GL11.*; public class TypeEnchantment extends CITType { + @Entrypoint(CITGlobalProperties.ENTRYPOINT) @Entrypoint(CITTypeContainer.ENTRYPOINT) public static final Container CONTAINER = new Container(); @@ -55,7 +66,8 @@ public class TypeEnchantment extends CITType { public Blend blend; public final Map renderLayers = new EnumMap<>(GlintRenderLayer.class); - private final WrappedMethodIntensity methodIntensity = new WrappedMethodIntensity(); + private final MergeMethodIntensity methodIntensity = new MergeMethodIntensity(); + private Set enchantmentChecks = null; @Override public void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { @@ -88,6 +100,14 @@ public class TypeEnchantment extends CITType { } catch (Exception e) { throw new CITParsingException("Could not parse blending method", properties, blendProp.position(), e); } + + for (CITCondition condition : conditions) + if (condition instanceof ConditionEnchantments enchantments) { + if (enchantmentChecks == null && enchantments.getEnchantments().length > 0) + enchantmentChecks = new HashSet<>(); + + enchantmentChecks.addAll(Arrays.asList(enchantments.getEnchantments())); + } } private float parseFloatOrDefault(float defaultValue, String propertyName, PropertyGroup properties) throws CITParsingException { @@ -101,11 +121,16 @@ public class TypeEnchantment extends CITType { } } - public static class Container extends CITTypeContainer { + public static class Container extends CITTypeContainer implements CITGlobalProperties { public Container() { super(TypeEnchantment.class, TypeEnchantment::new, "enchantment"); } + public boolean globalUseGlint = true; + public int globalCap = Integer.MAX_VALUE; + public MergeMethodIntensity.MergeMethod globalMergeMethod = MergeMethodIntensity.MergeMethod.AVERAGE; + public float globalFade = 0.5f; + public List> loaded = new ArrayList<>(); public List>> loadedLayered = new ArrayList<>(); @@ -133,6 +158,26 @@ public class TypeEnchantment extends CITType { } } + @Override + public void globalProperty(String key, PropertyValue value) throws Exception { + switch (key) { + case "useGlint" -> { + globalUseGlint = Boolean.parseBoolean(value.value()); + if (!globalUseGlint && !"false".equalsIgnoreCase(value.value())) + throw new Exception("Could not parse boolean"); + } + case "cap" -> { + globalCap = Integer.parseInt(value.value()); + } + case "method" -> { + globalMergeMethod = MergeMethodIntensity.MergeMethod.parse(value.value()); + } + case "fade" -> { + globalFade = Float.parseFloat(value.value()); + } + } + } + @Override public void dispose() { appliedContext = null; @@ -143,6 +188,11 @@ public class TypeEnchantment extends CITType { loaded.clear(); loadedLayered.clear(); + + globalUseGlint = true; + globalCap = Integer.MAX_VALUE; + globalMergeMethod = MergeMethodIntensity.MergeMethod.AVERAGE; + globalFade = 0.5f; } public void apply() { @@ -155,7 +205,7 @@ public class TypeEnchantment extends CITType { } public boolean shouldNotApplyDefaultGlint() { - return apply && !defaultGlint; + return !globalUseGlint || (apply && !defaultGlint); } public Container setContext(CITContext context) { @@ -181,6 +231,8 @@ public class TypeEnchantment extends CITType { if (appliedContext.isEmpty()) appliedContext = null; + else + globalMergeMethod.applyMethod(appliedContext, context); return this; } @@ -252,9 +304,9 @@ public class TypeEnchantment extends CITType { public RenderLayer build(TypeEnchantment enchantment, Identifier propertiesIdentifier) { class Texturing implements Runnable { private final float speed, rotation, r, g, b, a; - private final WrappedMethodIntensity methodIntensity; + private final MergeMethodIntensity methodIntensity; - Texturing(float speed, float rotation, float r, float g, float b, float a, WrappedMethodIntensity methodIntensity) { + Texturing(float speed, float rotation, float r, float g, float b, float a, MergeMethodIntensity methodIntensity) { this.speed = speed; this.rotation = rotation; this.r = r; @@ -300,7 +352,7 @@ public class TypeEnchantment extends CITType { if (!CONTAINER.apply || CONTAINER.appliedContext == null || CONTAINER.appliedContext.size() == 0) return null; - VertexConsumer[] layers = new VertexConsumer[Math.min(CONTAINER.appliedContext.size(), Integer.MAX_VALUE /*todo cap global property*/)]; + VertexConsumer[] layers = new VertexConsumer[Math.min(CONTAINER.appliedContext.size(), CONTAINER.globalCap)]; for (int i = 0; i < layers.length; i++) layers[i] = provider.getBuffer(CONTAINER.appliedContext.get(i).type.renderLayers.get(GlintRenderLayer.this)); @@ -311,8 +363,90 @@ public class TypeEnchantment extends CITType { } } - private static class WrappedMethodIntensity { + public static class MergeMethodIntensity { public float intensity = 1f; + + public enum MergeMethod { + NONE, + AVERAGE { + @Override + public void applyIntensity(Map stackEnchantments, CIT cit) { + Identifier enchantment = null; + for (Identifier enchantmentMatch : cit.type.enchantmentChecks) + if (stackEnchantments.containsKey(enchantmentMatch)) { + enchantment = enchantmentMatch; + break; + } + + if (enchantment == null) { + cit.type.methodIntensity.intensity = 0f; + } else { + float sum = 0f; + for (Integer value : stackEnchantments.values()) + sum += value; + + cit.type.methodIntensity.intensity = (float) stackEnchantments.get(enchantment) / sum; + } + } + }, + LAYERED { + @Override + public void applyIntensity(Map stackEnchantments, CIT cit) { + Identifier enchantment = null; + for (Identifier enchantmentMatch : cit.type.enchantmentChecks) + if (stackEnchantments.containsKey(enchantmentMatch)) { + enchantment = enchantmentMatch; + break; + } + if (enchantment == null) { + cit.type.methodIntensity.intensity = 0f; + return; + } + + float max = 0f; + for (Integer value : stackEnchantments.values()) + if (value > max) + max = value; + + cit.type.methodIntensity.intensity = (float) stackEnchantments.get(enchantment) / max; + } + }, + CYCLE { + @Override + public void applyMethod(List> citEnchantments, CITContext context) { + List, Float>> durations = new ArrayList<>(); + for (CIT cit : citEnchantments) + durations.add(new HashMap.SimpleEntry<>(cit, cit.type.duration)); + + for (Map.Entry, Float> intensity : Loops.statelessFadingLoop(durations, CONTAINER.globalFade, ticks, 20).entrySet()) + intensity.getKey().type.methodIntensity.intensity = intensity.getValue(); + } + }; + + public static int ticks = 0; + + public void applyIntensity(Map stackEnchantments, CIT cit) { + cit.type.methodIntensity.intensity = 1f; + } + + public void applyMethod(List> citEnchantments, CITContext context) { + Map stackEnchantments = context.enchantments(); + + for (CIT cit : citEnchantments) + if (cit.type.enchantmentChecks != null) + applyIntensity(stackEnchantments, cit); + } + + public static MergeMethod parse(String value) { + return switch (value.toLowerCase(Locale.ROOT)) { + case "none" -> NONE; + case "average" -> AVERAGE; + case "layered" -> LAYERED; + case "cycle" -> CYCLE; + default -> throw new IllegalArgumentException("Unknown merge method"); + }; + } + } } public static class Blend extends RenderPhase.Transparency { diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/MinecraftClientMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/MinecraftClientMixin.java new file mode 100644 index 0000000..e8b346b --- /dev/null +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/MinecraftClientMixin.java @@ -0,0 +1,16 @@ +package shcm.shsupercm.fabric.citresewn.defaults.mixin.types.enchantment; + +import net.minecraft.client.MinecraftClient; +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.CallbackInfo; +import shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeEnchantment; + +@Mixin(MinecraftClient.class) +public class MinecraftClientMixin { + @Inject(method = "tick", at = @At("HEAD")) + public void onTick(CallbackInfo ci) { + TypeEnchantment.MergeMethodIntensity.MergeMethod.ticks++; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java index c9e2cf8..456faab 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java @@ -37,7 +37,7 @@ public class GlobalProperties extends PropertyGroup { } public void callHandlers() { - for (EntrypointContainer container : FabricLoader.getInstance().getEntrypointContainers("citresewn:cit_global_properties", CITGlobalProperties.class)) { + for (EntrypointContainer container : FabricLoader.getInstance().getEntrypointContainers(CITGlobalProperties.ENTRYPOINT, CITGlobalProperties.class)) { String containerNamespace = container.getProvider().getMetadata().getId(); if (containerNamespace.equals("citresewn-defaults")) containerNamespace = "citresewn"; -- cgit From 6c602e022e2316a553bdbcad09e84e93fa6273fc Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 4 Mar 2022 08:22:51 +0200 Subject: Cleaned up type activity checks --- .../citresewn/defaults/cit/types/TypeEnchantment.java | 10 ++-------- .../mixin/types/armor/ArmorFeatureRendererMixin.java | 4 +--- .../mixin/types/elytra/ElytraFeatureRendererMixin.java | 9 +++++---- .../types/enchantment/ArmorFeatureRendererMixin.java | 6 ++---- .../types/enchantment/ElytraFeatureRendererMixin.java | 6 ++---- .../mixin/types/enchantment/ItemRendererMixin.java | 8 +++----- .../defaults/mixin/types/item/ItemRendererMixin.java | 11 +++-------- .../defaults/mixin/types/item/ModelLoaderMixin.java | 7 +++---- .../fabric/citresewn/api/CITTypeContainer.java | 17 ++++++++++++++++- .../shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java | 2 +- 10 files changed, 38 insertions(+), 42 deletions(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java index 6f9481e..a59e96c 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java @@ -4,14 +4,7 @@ import com.mojang.blaze3d.systems.RenderSystem; import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import net.minecraft.client.MinecraftClient; import net.minecraft.client.render.*; -import net.minecraft.enchantment.EnchantmentHelper; -import net.minecraft.item.EnchantedBookItem; -import net.minecraft.item.ItemStack; -import net.minecraft.item.Items; -import net.minecraft.nbt.NbtCompound; -import net.minecraft.nbt.NbtElement; import net.minecraft.resource.ResourceManager; -import net.minecraft.text.Text; import net.minecraft.util.Identifier; import net.minecraft.util.Util; import net.minecraft.util.math.Matrix4f; @@ -181,6 +174,7 @@ public class TypeEnchantment extends CITType { @Override public void dispose() { appliedContext = null; + apply = false; for (CIT cit : loaded) for (RenderLayer renderLayer : cit.type.renderLayers.values()) @@ -201,7 +195,7 @@ public class TypeEnchantment extends CITType { } public boolean shouldApply() { - return apply; + return apply && active(); } public boolean shouldNotApplyDefaultGlint() { diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/armor/ArmorFeatureRendererMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/armor/ArmorFeatureRendererMixin.java index fba7159..d61af4c 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/armor/ArmorFeatureRendererMixin.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/armor/ArmorFeatureRendererMixin.java @@ -14,10 +14,8 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; import shcm.shsupercm.fabric.citresewn.cit.CIT; import shcm.shsupercm.fabric.citresewn.cit.CITContext; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; import shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeArmor; import java.util.Map; @@ -31,7 +29,7 @@ public class ArmorFeatureRendererMixin, A extends BipedEntityModel> { @Inject(method = "renderArmor", at = @At("HEAD")) private void citresewn$enchantment$setAppliedContextAndStartApplyingArmor(MatrixStack matrices, VertexConsumerProvider vertexConsumers, T livingEntity, EquipmentSlot armorSlot, int light, A model, CallbackInfo ci) { - if (CITResewnConfig.INSTANCE.enabled && ActiveCITs.isActive()) + if (CONTAINER.active()) CONTAINER.setContext(new CITContext(livingEntity.getEquippedStack(armorSlot), livingEntity.world, livingEntity)).apply(); } @Inject(method = "renderArmor", at = @At("RETURN")) private void citresewn$enchantment$stopApplyingArmor(MatrixStack matrices, VertexConsumerProvider vertexConsumers, T livingEntity, EquipmentSlot armorSlot, int light, A model, CallbackInfo ci) { - if (CITResewnConfig.INSTANCE.enabled && ActiveCITs.isActive()) + if (CONTAINER.active()) CONTAINER.setContext(null); } } diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/ElytraFeatureRendererMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/ElytraFeatureRendererMixin.java index 4966e6f..c64fb77 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/ElytraFeatureRendererMixin.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/ElytraFeatureRendererMixin.java @@ -9,9 +9,7 @@ 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.CallbackInfo; -import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; import shcm.shsupercm.fabric.citresewn.cit.CITContext; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; import static shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeEnchantment.CONTAINER; @@ -19,13 +17,13 @@ import static shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeEnchantment public class ElytraFeatureRendererMixin { @Inject(method = "render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;ILnet/minecraft/entity/LivingEntity;FFFFFF)V", at = @At("HEAD")) private void citresewn$enchantment$setAppliedContextAndStartApplyingElytra(MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int i, LivingEntity livingEntity, float f, float g, float h, float j, float k, float l, CallbackInfo ci) { - if (CITResewnConfig.INSTANCE.enabled && ActiveCITs.isActive()) + if (CONTAINER.active()) CONTAINER.setContext(new CITContext(livingEntity.getEquippedStack(EquipmentSlot.CHEST), livingEntity.world, livingEntity)).apply(); } @Inject(method = "render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;ILnet/minecraft/entity/LivingEntity;FFFFFF)V", at = @At("RETURN")) private void citresewn$enchantment$stopApplyingElytra(MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int i, LivingEntity livingEntity, float f, float g, float h, float j, float k, float l, CallbackInfo ci) { - if (CITResewnConfig.INSTANCE.enabled && ActiveCITs.isActive()) + if (CONTAINER.active()) CONTAINER.setContext(null); } } diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/ItemRendererMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/ItemRendererMixin.java index 138e7f9..b4bd37d 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/ItemRendererMixin.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/enchantment/ItemRendererMixin.java @@ -14,9 +14,7 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; import shcm.shsupercm.fabric.citresewn.cit.CITContext; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; import shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeEnchantment; import static shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeEnchantment.CONTAINER; @@ -25,19 +23,19 @@ import static shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeEnchantment public class ItemRendererMixin { @Inject(method = "getModel", at = @At("HEAD")) private void citresewn$enchantment$setAppliedContext(ItemStack stack, World world, LivingEntity entity, int seed, CallbackInfoReturnable cir) { - if (CITResewnConfig.INSTANCE.enabled && ActiveCITs.isActive()) + if (CONTAINER.active()) CONTAINER.setContext(new CITContext(stack, world, entity)); } @Inject(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;IILnet/minecraft/client/render/model/BakedModel;)V", at = @At("HEAD")) private void citresewn$enchantment$startApplyingItem(ItemStack stack, ModelTransformation.Mode renderMode, boolean leftHanded, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay, BakedModel model, CallbackInfo ci) { - if (CITResewnConfig.INSTANCE.enabled && ActiveCITs.isActive()) + if (CONTAINER.active()) CONTAINER.apply(); } @Inject(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;IILnet/minecraft/client/render/model/BakedModel;)V", at = @At("RETURN")) private void citresewn$enchantment$stopApplyingItem(ItemStack stack, ModelTransformation.Mode renderMode, boolean leftHanded, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay, BakedModel model, CallbackInfo ci) { - if (CITResewnConfig.INSTANCE.enabled && ActiveCITs.isActive()) + if (CONTAINER.active()) CONTAINER.setContext(null); } diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemRendererMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemRendererMixin.java index 49e26af..4a57445 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemRendererMixin.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ItemRendererMixin.java @@ -19,10 +19,8 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; import shcm.shsupercm.fabric.citresewn.cit.CIT; import shcm.shsupercm.fabric.citresewn.cit.CITContext; -import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; import shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeItem; import java.lang.ref.WeakReference; @@ -41,7 +39,7 @@ public class ItemRendererMixin { @Inject(method = "getModel", cancellable = true, at = @At("HEAD")) private void citresewn$getItemModel(ItemStack stack, World world, LivingEntity entity, int seed, CallbackInfoReturnable cir) { - if (!CITResewnConfig.INSTANCE.enabled || !ActiveCITs.isActive()) + if (!CONTAINER.active()) return; CITContext context = new CITContext(stack, world, entity); @@ -56,7 +54,7 @@ public class ItemRendererMixin { @Inject(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;IILnet/minecraft/client/render/model/BakedModel;)V", at = @At("HEAD")) private void citresewn$fixMojankCITsContext(ItemStack stack, ModelTransformation.Mode renderMode, boolean leftHanded, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay, BakedModel model, CallbackInfo ci) { - if (!CITResewnConfig.INSTANCE.enabled || !ActiveCITs.isActive()) + if (!CONTAINER.active()) return; citresewn$mojankCITModel = null; @@ -76,10 +74,7 @@ public class ItemRendererMixin { @ModifyVariable(method = "renderItem(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/render/model/json/ModelTransformation$Mode;ZLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;IILnet/minecraft/client/render/model/BakedModel;)V", at = @At(value = "LOAD", ordinal = 0, target = "Lnet/minecraft/client/render/model/BakedModel;getTransformation()Lnet/minecraft/client/render/model/json/ModelTransformation;"), argsOnly = true) private BakedModel citresewn$fixMojankCITs(BakedModel original) { - if (!CITResewnConfig.INSTANCE.enabled || !ActiveCITs.isActive()) - return original; - - if (citresewn$mojankCITModel != null) + if (CONTAINER.active() && citresewn$mojankCITModel != null) return citresewn$mojankCITModel.get(); return original; diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java index c7fa70d..93bab6a 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/mixin/types/item/ModelLoaderMixin.java @@ -20,7 +20,6 @@ import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import shcm.shsupercm.fabric.citresewn.CITResewn; -import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; import shcm.shsupercm.fabric.citresewn.cit.CIT; import shcm.shsupercm.fabric.citresewn.defaults.cit.types.TypeItem; import shcm.shsupercm.fabric.citresewn.defaults.common.ResewnItemModelIdentifier; @@ -41,7 +40,7 @@ public class ModelLoaderMixin { @At(value = "INVOKE", ordinal = 0, target = "Lnet/minecraft/util/profiler/Profiler;swap(Ljava/lang/String;)V")) public void citresewn$addTypeItemModels(ResourceManager resourceManager, BlockColors blockColors, Profiler profiler, int i, CallbackInfo ci) { profiler.swap("citresewn:type_item_models"); - if (!ActiveCITs.isActive()) + if (!CONTAINER.active()) return; info("Loading item CIT models..."); @@ -65,7 +64,7 @@ public class ModelLoaderMixin { @Inject(method = "upload", at = @At("RETURN")) public void citresewn$linkTypeItemModels(TextureManager textureManager, Profiler profiler, CallbackInfoReturnable cir) { - if (!ActiveCITs.isActive()) + if (!CONTAINER.active()) return; profiler.push("citresewn:type_item_linking"); @@ -92,7 +91,7 @@ public class ModelLoaderMixin { @ModifyArg(method = "loadModelFromJson", at = @At(value = "INVOKE", target = "Lnet/minecraft/resource/ResourceManager;getResource(Lnet/minecraft/util/Identifier;)Lnet/minecraft/resource/Resource;")) public Identifier citresewn$fixDuplicatePrefixSuffix(Identifier original) { - if (original.getPath().startsWith("models/models/") && original.getPath().endsWith(".json.json") && original.getPath().contains("cit")) + if (CONTAINER.active() && original.getPath().startsWith("models/models/") && original.getPath().endsWith(".json.json") && original.getPath().contains("cit")) return new Identifier(original.getNamespace(), original.getPath().substring(7, original.getPath().length() - 5)); return original; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java index a9666d3..5aa727d 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java @@ -1,7 +1,9 @@ package shcm.shsupercm.fabric.citresewn.api; +import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; import shcm.shsupercm.fabric.citresewn.cit.CIT; import shcm.shsupercm.fabric.citresewn.cit.CITType; +import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; import java.util.List; import java.util.function.Supplier; @@ -12,16 +14,29 @@ public abstract class CITTypeContainer implements CITDisposab public final Supplier createType; public final String id; + protected boolean empty = true; + public CITTypeContainer(Class type, Supplier createType, String id) { this.type = type; this.createType = createType; this.id = id; } - public abstract void load(List> parsedCITs); + protected abstract void load(List> parsedCITs); @SuppressWarnings("unchecked") public final void loadUntyped(List parsedCITs) { + if (!parsedCITs.isEmpty()) + empty = false; load((List>) parsedCITs); } + + public final void unload() { + dispose(); + empty = true; + } + + public boolean active() { + return !empty && CITResewnConfig.INSTANCE.enabled && ActiveCITs.isActive(); + } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java index f54cc54..c7ca38c 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java @@ -61,6 +61,6 @@ public class ActiveCITs implements CITDisposable { private ActiveCITs() {} disposable.dispose(); for (CITTypeContainer typeContainer : CITRegistry.TYPES.values()) - typeContainer.dispose(); + typeContainer.unload(); } } -- cgit From d2a7a6b219ff2b229774dba336417822ec019b7b Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 4 Mar 2022 09:55:50 +0200 Subject: Added back enchantment scroll multiplier config --- .../CITResewnDefaultsConfigScreenFactory.java | 9 ++++-- .../assets/citresewn-defaults/lang/en_us.json | 7 +++-- .../config/CITResewnConfigScreenFactory.java | 33 ++++++++++++---------- 3 files changed, 29 insertions(+), 20 deletions(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java index 6d89bc6..95b0579 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/config/CITResewnDefaultsConfigScreenFactory.java @@ -4,7 +4,6 @@ import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import me.shedaniel.clothconfig2.api.ConfigBuilder; import me.shedaniel.clothconfig2.api.ConfigCategory; import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; -import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.text.LiteralText; import net.minecraft.text.TranslatableText; @@ -17,13 +16,17 @@ public class CITResewnDefaultsConfigScreenFactory { ConfigBuilder builder = ConfigBuilder.create() .setParentScreen(parent) - .setTitle(new TranslatableText("config.citresewn.defaults.title")) + .setTitle(new TranslatableText("config.citresewn-defaults.title")) .setSavingRunnable(currentConfig::write); ConfigCategory category = builder.getOrCreateCategory(new LiteralText("")); ConfigEntryBuilder entryBuilder = builder.entryBuilder(); - + category.addEntry(entryBuilder.startFloatField(new TranslatableText("config.citresewn-defaults.type_enchantment_scroll_multiplier.title"), currentConfig.type_enchantment_scroll_multiplier) + .setTooltip(new TranslatableText("config.citresewn-defaults.type_enchantment_scroll_multiplier.tooltip")) + .setSaveConsumer(newConfig -> currentConfig.type_enchantment_scroll_multiplier = newConfig) + .setDefaultValue(defaultConfig.type_enchantment_scroll_multiplier) + .build()); return builder.build(); } diff --git a/defaults/src/main/resources/assets/citresewn-defaults/lang/en_us.json b/defaults/src/main/resources/assets/citresewn-defaults/lang/en_us.json index 72784ed..5f68e45 100644 --- a/defaults/src/main/resources/assets/citresewn-defaults/lang/en_us.json +++ b/defaults/src/main/resources/assets/citresewn-defaults/lang/en_us.json @@ -1,4 +1,7 @@ { - "config.citresewn.defaults.title": "CIT Resewn: Defaults", - "config.citresewn.defaults.tooltip": "Go to the defaults' config menu" + "config.citresewn-defaults.title": "CIT Resewn: Defaults", + "config.citresewn-defaults.tooltip": "Go to the defaults' config menu", + + "config.citresewn-defaults.type_enchantment_scroll_multiplier.title": "Type Enchantment: Scroll multiplier", + "config.citresewn-defaults.type_enchantment_scroll_multiplier.tooltip": "A general multiplier for how fast cit enchantment glints scroll" } \ No newline at end of file diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java index 2d584aa..b05dc6e 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java @@ -37,20 +37,23 @@ public class CITResewnConfigScreenFactory { .setDefaultValue(defaultConfig.enabled) .build()); - class CurrentScreen { Screen screen; boolean prevToggle = false; } final CurrentScreen currentScreen = new CurrentScreen(); - category.addEntry(entryBuilder.startBooleanToggle(new TranslatableText("config.citresewn.defaults.title"), false) - .setTooltip(new TranslatableText("config.citresewn.defaults.tooltip")) - .setYesNoTextSupplier((b) -> { - if (b != currentScreen.prevToggle) { - //noinspection unchecked - MinecraftClient.getInstance().setScreen((Screen) FabricLoader.getInstance().getEntrypoints(DEFAULTS_CONFIG_ENTRYPOINT, Function.class).stream().findAny().orElseThrow().apply(currentScreen.screen)); - - currentScreen.prevToggle = b; - } + if (FabricLoader.getInstance().isModLoaded("citresewn-defaults")) { + class CurrentScreen { boolean prevToggle = false; } final CurrentScreen currentScreen = new CurrentScreen(); + category.addEntry(entryBuilder.startBooleanToggle(new TranslatableText("config.citresewn-defaults.title"), false) + .setTooltip(new TranslatableText("config.citresewn-defaults.tooltip")) - return new TranslatableText("config.citresewn.configure"); - }) - .build()); + .setYesNoTextSupplier((b) -> { + if (b != currentScreen.prevToggle) { + //noinspection unchecked + MinecraftClient.getInstance().setScreen((Screen) FabricLoader.getInstance().getEntrypoints(DEFAULTS_CONFIG_ENTRYPOINT, Function.class).stream().findAny().orElseThrow().apply(create(parent))); + + currentScreen.prevToggle = b; + } + + return new TranslatableText("config.citresewn.configure"); + }) + .build()); + } category.addEntry(entryBuilder.startBooleanToggle(new TranslatableText("config.citresewn.mute_errors.title"), currentConfig.mute_errors) .setTooltip(new TranslatableText("config.citresewn.mute_errors.tooltip")) @@ -67,7 +70,7 @@ public class CITResewnConfigScreenFactory { category.addEntry(entryBuilder.startIntSlider(new TranslatableText("config.citresewn.cache_ms.title"), currentConfig.cache_ms / 50, 0, 5 * 20) .setTooltip(new TranslatableText("config.citresewn.cache_ms.tooltip")) .setSaveConsumer(newConfig -> currentConfig.cache_ms = newConfig * 50) - .setDefaultValue(currentConfig.cache_ms / 50) + .setDefaultValue(defaultConfig.cache_ms / 50) .setTextGetter(ticks -> { if (ticks <= 1) return new TranslatableText("config.citresewn.cache_ms.ticks." + ticks).formatted(Formatting.AQUA); @@ -90,6 +93,6 @@ public class CITResewnConfigScreenFactory { .requireRestart() .build()); - return currentScreen.screen = builder.build(); + return builder.build(); } } -- cgit From badaaeaae77bb8bc74b4e08cbce1087c68252914 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 4 Mar 2022 10:52:27 +0200 Subject: Readded citresewn command --- .../shcm/shsupercm/fabric/citresewn/CITResewn.java | 4 +++ .../fabric/citresewn/CITResewnCommand.java | 39 ++++++++++++++++++++++ .../fabric/citresewn/mixin/ChatScreenMixin.java | 29 ++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ChatScreenMixin.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java index 482d757..79e49aa 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java @@ -2,6 +2,7 @@ package shcm.shsupercm.fabric.citresewn; import io.shcm.shsupercm.fabric.fletchingtable.api.Entrypoint; import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.loader.api.FabricLoader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; @@ -15,6 +16,9 @@ public class CITResewn implements ClientModInitializer { @Override public void onInitializeClient() { CITRegistry.registerAll(); + + if (FabricLoader.getInstance().isModLoaded("fabric-command-api-v1")) + CITResewnCommand.register(); } public static void info(String message) { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java new file mode 100644 index 0000000..b06a8ba --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java @@ -0,0 +1,39 @@ +package shcm.shsupercm.fabric.citresewn; + +import net.fabricmc.fabric.api.client.command.v1.ClientCommandManager; +import net.fabricmc.loader.api.FabricLoader; +import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; +import shcm.shsupercm.fabric.citresewn.cit.CITRegistry; +import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; + +import java.util.Collection; + +import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal; +import static net.minecraft.text.Text.of; + +public class CITResewnCommand { + public static boolean openConfig = false; + + public static void register() { + ClientCommandManager.DISPATCHER.register(literal("citresewn") + .executes(context -> { + context.getSource().sendFeedback(of("CIT Resewn v" + FabricLoader.getInstance().getModContainer("citresewn").orElseThrow().getMetadata().getVersion() + ":")); + context.getSource().sendFeedback(of(" Registered: " + CITRegistry.TYPES.values().stream().distinct().count() + " types and " + CITRegistry.CONDITIONS.values().stream().distinct().count() + " conditions")); + + final boolean active = CITResewnConfig.INSTANCE.enabled && ActiveCITs.isActive(); + context.getSource().sendFeedback(of(" Active: " + (active ? "yes" : ("no, " + (CITResewnConfig.INSTANCE.enabled ? "no cit packs loaded" : "disabled in config"))))); + if (active) { + context.getSource().sendFeedback(of(" Loaded: " + ActiveCITs.getActive().cits.values().stream().mapToLong(Collection::size).sum() + " CITs from " + ActiveCITs.getActive().cits.values().stream().flatMap(Collection::stream).map(cit -> cit.packName).distinct().count() + " resourcepacks")); + } + context.getSource().sendFeedback(of("")); + + return 1; + }) + .then(literal("config") + .executes(context -> { + openConfig = true; + + return 1; + }))); + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ChatScreenMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ChatScreenMixin.java new file mode 100644 index 0000000..5bacbde --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ChatScreenMixin.java @@ -0,0 +1,29 @@ +package shcm.shsupercm.fabric.citresewn.mixin; + +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.screen.ChatScreen; +import net.minecraft.client.gui.screen.NoticeScreen; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.text.Text; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import shcm.shsupercm.fabric.citresewn.config.CITResewnConfigScreenFactory; + +import static shcm.shsupercm.fabric.citresewn.CITResewnCommand.openConfig; + +@Mixin(ChatScreen.class) +public class ChatScreenMixin { + @ModifyArg(method = "keyPressed", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/MinecraftClient;setScreen(Lnet/minecraft/client/gui/screen/Screen;)V")) + public Screen redirectConfigScreen(Screen original) { + if (openConfig) { + openConfig = false; + return FabricLoader.getInstance().isModLoaded("cloth-config2") ? + CITResewnConfigScreenFactory.create(null) : + new NoticeScreen(() -> MinecraftClient.getInstance().setScreen(null), Text.of("CIT Resewn"), Text.of("CIT Resewn requires Cloth Config to be able to show the config.")); + } + + return original; + } +} -- cgit From d5e4cfdad93267d7c3f574451a4ee7e0b4ef4098 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 4 Mar 2022 10:59:46 +0200 Subject: Fixed cit parsing with config not enabled --- .../shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java | 17 +++++++++++++---- .../shsupercm/fabric/citresewn/pack/PackParser.java | 3 ++- 2 files changed, 15 insertions(+), 5 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java index c7ca38c..2c31641 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java @@ -5,6 +5,7 @@ import net.minecraft.resource.ResourceManager; import net.minecraft.util.profiler.Profiler; import shcm.shsupercm.fabric.citresewn.api.CITDisposable; import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; +import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.PackParser; @@ -32,14 +33,19 @@ public class ActiveCITs implements CITDisposable { private ActiveCITs() {} active = null; } + if (!CITResewnConfig.INSTANCE.enabled) { + profiler.pop(); + return null; + } + ActiveCITs active = new ActiveCITs(); profiler.swap("citresewn:load_global_properties"); - PackParser.loadGlobalProperties(resourceManager, active.globalProperties); - active.globalProperties.callHandlers(); + PackParser.loadGlobalProperties(resourceManager, active.globalProperties).callHandlers(); profiler.swap("citresewn:load_cits"); - for (CIT cit : PackParser.loadCITs(resourceManager)) + List> cits = PackParser.loadCITs(resourceManager); + for (CIT cit : cits) active.cits.computeIfAbsent(cit.type.getClass(), type -> new ArrayList<>()).add(cit); for (Map.Entry, List>> entry : active.cits.entrySet()) { entry.getValue().sort(Comparator.>comparingInt(cit -> cit.weight).reversed().thenComparing(cit -> cit.propertiesIdentifier.toString())); @@ -52,7 +58,10 @@ public class ActiveCITs implements CITDisposable { private ActiveCITs() {} profiler.pop(); - return ActiveCITs.active = active; + if (!cits.isEmpty()) + ActiveCITs.active = active; + + return ActiveCITs.active; } @Override diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 163435b..794977d 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -43,7 +43,7 @@ public class PackParser { }); } - public static void loadGlobalProperties(ResourceManager resourceManager, GlobalProperties globalProperties) { + public static GlobalProperties loadGlobalProperties(ResourceManager resourceManager, GlobalProperties globalProperties) { forEachPack(resourceManager, pack -> { for (String root : ROOTS) { Identifier identifier = new Identifier("minecraft", root + "/cit.properties"); @@ -56,6 +56,7 @@ public class PackParser { } } }); + return globalProperties; } public static List> loadCITs(ResourceManager resourceManager) { -- cgit From de66a476d01d606c3815efebc904a5c6d9bce133 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 4 Mar 2022 15:29:14 +0200 Subject: Added analyze pack command --- .../fabric/citresewn/CITResewnCommand.java | 111 ++++++++++++++++++++- .../fabric/citresewn/cit/CITRegistry.java | 26 ++++- 2 files changed, 130 insertions(+), 7 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java index b06a8ba..01c08bf 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java @@ -1,13 +1,26 @@ package shcm.shsupercm.fabric.citresewn; +import com.mojang.brigadier.LiteralMessage; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; import net.fabricmc.fabric.api.client.command.v1.ClientCommandManager; import net.fabricmc.loader.api.FabricLoader; -import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; -import shcm.shsupercm.fabric.citresewn.cit.CITRegistry; +import net.minecraft.text.Text; +import shcm.shsupercm.fabric.citresewn.cit.*; import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; +import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; -import java.util.Collection; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; +import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.argument; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal; import static net.minecraft.text.Text.of; @@ -34,6 +47,96 @@ public class CITResewnCommand { openConfig = true; return 1; - }))); + })) + .then(literal("analyze") + .then(literal("pack") + .then(argument("pack", new CITPackArgument()) + .executes(context -> { + final String pack = context.getArgument("pack", String.class); + if (ActiveCITs.isActive()) { + context.getSource().sendFeedback(of("Analyzed CIT data of \"" + pack + "\u00a7r\":")); + + List builder = new ArrayList<>(); + + for (Map.Entry> entry : ActiveCITs.getActive().globalProperties.properties.entrySet()) + for (PropertyValue value : entry.getValue()) + if (value.packName().equals(pack)) + builder.add(of(" " + entry.getKey().toString() + (value.keyMetadata() == null ? "" : "." + value.keyMetadata()) + " = " + value.value())); + if (!builder.isEmpty()) { + context.getSource().sendFeedback(of(" Global Properties:")); + for (Text text : builder) + context.getSource().sendFeedback(text); + + builder.clear(); + } + + for (Map.Entry, List>> entry : ActiveCITs.getActive().cits.entrySet()) + if (!entry.getValue().isEmpty()) { + long count = entry.getValue().stream().filter(cit -> cit.packName.equals(pack)).count(); + if (count > 0) + builder.add(of(" " + CITRegistry.idOfType(entry.getKey()).toString() + " = " + count)); + } + if (!builder.isEmpty()) { + context.getSource().sendFeedback(of(" Types:")); + for (Text text : builder) + context.getSource().sendFeedback(text); + + builder.clear(); + } + + List conditions = ActiveCITs.getActive().cits.values().stream() + .flatMap(Collection::stream) + .filter(cit -> cit.packName.equals(pack)) + .flatMap(cit -> Arrays.stream(cit.conditions)) + .toList(); + if (!conditions.isEmpty()) + context.getSource().sendFeedback(of(" Utilizing " + conditions.size() + " conditions(" + conditions.stream().map(Object::getClass).distinct().count() + " unique condition types)")); + } else + context.getSource().sendFeedback(of("Not active")); + + return 1; + }) + ) + ) + ) + ); + } + + private static class CITPackArgument implements ArgumentType { + @Override + public String parse(StringReader reader) throws CommandSyntaxException { + StringBuilder builder = new StringBuilder(); + while (reader.canRead()) + builder.append(reader.read()); + + String pack = builder.toString().trim(); + + if (!getPacks().contains(pack)) { + LiteralMessage message = new LiteralMessage("Could not find CIT pack"); + throw new CommandSyntaxException(new SimpleCommandExceptionType(message), message); + } + + return pack; + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + return CompletableFuture.supplyAsync(() -> { + for (String pack : getPacks()) { + builder.suggest(pack); + } + return builder.build(); + }); + } + + private static Set getPacks() { + if (ActiveCITs.isActive()) + return ActiveCITs.getActive().cits.values().stream() + .flatMap(Collection::stream) + .map(cit -> cit.packName) + .collect(Collectors.toSet()); + else + return Collections.emptySet(); + } } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java index ff38ef8..47f79fe 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java @@ -20,6 +20,9 @@ public class CITRegistry { public static final Map> TYPES = new HashMap<>(); public static final Map> CONDITIONS = new HashMap<>(); + private static final Map, Identifier> TYPE_TO_ID = new IdentityHashMap<>(); + private static final Map, PropertyKey> CONDITION_TO_ID = new IdentityHashMap<>(); + public static void registerAll() { info("Registering CIT Conditions"); for (var entrypointContainer : FabricLoader.getInstance().getEntrypointContainers(CITConditionContainer.ENTRYPOINT, CITConditionContainer.class)) { @@ -27,8 +30,13 @@ public class CITRegistry { if (namespace.equals("citresewn-defaults")) namespace = "citresewn"; - for (String alias : entrypointContainer.getEntrypoint().aliases) - CONDITIONS.put(new PropertyKey(namespace, alias), (CITConditionContainer) entrypointContainer.getEntrypoint()); + for (String alias : entrypointContainer.getEntrypoint().aliases) { + final PropertyKey key = new PropertyKey(namespace, alias); + CITConditionContainer container = entrypointContainer.getEntrypoint(); + + CONDITIONS.put(key, container); + CONDITION_TO_ID.putIfAbsent(container.createCondition.get().getClass(), key); + } } info("Registering CIT Types"); @@ -37,7 +45,11 @@ public class CITRegistry { if (namespace.equals("citresewn-defaults")) namespace = "citresewn"; - TYPES.put(new Identifier(namespace, entrypointContainer.getEntrypoint().id), (CITTypeContainer) entrypointContainer.getEntrypoint()); + final Identifier id = new Identifier(namespace, entrypointContainer.getEntrypoint().id); + CITTypeContainer container = entrypointContainer.getEntrypoint(); + + TYPES.put(id, container); + TYPE_TO_ID.putIfAbsent(container.createType.get().getClass(), id); } } @@ -71,4 +83,12 @@ public class CITRegistry { return typeContainer.createType.get(); } + + public static Identifier idOfType(Class clazz) { + return TYPE_TO_ID.get(clazz); + } + + public static PropertyKey idOfCondition(Class clazz) { + return CONDITION_TO_ID.get(clazz); + } } -- cgit From 90bb38ef08f0173ddfa9abb8b4ca2542f10af04a Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 4 Mar 2022 17:52:54 +0200 Subject: Rewrote escaped unicode parsing in properties --- .../citresewn/pack/format/PropertiesGroupAdapter.java | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java index c0b3da6..7a8d2d4 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java @@ -1,11 +1,9 @@ package shcm.shsupercm.fabric.citresewn.pack.format; import net.minecraft.util.Identifier; -import net.minecraft.util.InvalidIdentifierException; import java.io.*; import java.nio.charset.StandardCharsets; -import java.util.Properties; public class PropertiesGroupAdapter extends PropertyGroup { public static final String EXTENSION = ".properties"; @@ -44,6 +42,8 @@ public class PropertiesGroupAdapter extends PropertyGroup { line = line.substring(0, line.length() - 1) + "\\n" + nextLine; } + line = line.stripTrailing(); + StringBuilder builder = new StringBuilder(); String key = null, keyMetadata = null; @@ -59,18 +59,12 @@ public class PropertiesGroupAdapter extends PropertyGroup { case 'f' -> '\f'; case 't' -> '\t'; case 'u' -> { - if (i + 4 >= line.length()) - yield c; - - //todo implement manually - java.util.Properties properties = new Properties(); - properties.load(new StringReader("k=\\u" + line.charAt(i + 1) + line.charAt(i + 2) + line.charAt(i + 3) + line.charAt(i + 4))); - String k = properties.getProperty("k"); - if (k.length() == 1) { + try { i += 4; - yield k.charAt(0); + yield (char) Integer.parseInt(line.substring(i - 3, i + 1), 16); + } catch (ArrayIndexOutOfBoundsException | NumberFormatException e) { + throw new IOException("Malformatted escaped unicode character"); } - yield c; } default -> c; -- cgit From d0bceef6b9287184f3d97c68f0429c86538d68eb Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 4 Mar 2022 18:07:36 +0200 Subject: Moved property separator api into enum --- .../citresewn/cit/builtin/conditions/ListCondition.java | 2 +- .../fabric/citresewn/pack/format/PropertiesGroupAdapter.java | 2 +- .../shsupercm/fabric/citresewn/pack/format/PropertyGroup.java | 6 +++--- .../fabric/citresewn/pack/format/PropertySeparator.java | 11 +++++++++++ .../shsupercm/fabric/citresewn/pack/format/PropertyValue.java | 2 +- 5 files changed, 17 insertions(+), 6 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertySeparator.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java index 151119b..3b9a264 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java @@ -39,7 +39,7 @@ public abstract class ListCondition extends CITCondition for (String conditionValue : delimiter.split(value.value())) { T condition = conditionSupplier.get(); - condition.load(new PropertyValue(value.keyMetadata(), conditionValue, value.delimiter(), value.position(), value.propertiesIdentifier(), value.packName()), properties); + condition.load(new PropertyValue(value.keyMetadata(), conditionValue, value.separator(), value.position(), value.propertiesIdentifier(), value.packName()), properties); conditions.add(condition); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java index 7a8d2d4..4912a71 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java @@ -92,7 +92,7 @@ public class PropertiesGroupAdapter extends PropertyGroup { int pos = linePos - multilineSkip; multilineSkip = 0; - this.put(pos, packName, identifier, key, keyMetadata, "=", builder.toString()); + this.put(pos, packName, identifier, key, keyMetadata, PropertySeparator.EQUALS, builder.toString()); } } return this; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java index 75949db..1f21ed5 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java @@ -21,11 +21,11 @@ public abstract class PropertyGroup { public abstract PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException; - protected void put(int position, String packName, Identifier propertiesIdentifier, String key, String keyMetadata, String delimiter, String value) throws InvalidIdentifierException { + protected void put(int position, String packName, Identifier propertiesIdentifier, String key, String keyMetadata, PropertySeparator separator, String value) throws InvalidIdentifierException { Objects.requireNonNull(key); Objects.requireNonNull(value); - this.properties.computeIfAbsent(PropertyKey.of(key), id -> new LinkedHashSet<>()).add(new PropertyValue(keyMetadata, value, delimiter, position, propertiesIdentifier, packName)); + this.properties.computeIfAbsent(PropertyKey.of(key), id -> new LinkedHashSet<>()).add(new PropertyValue(keyMetadata, value, separator, position, propertiesIdentifier, packName)); } public Set get(String namespace, String... pathAliases) { @@ -52,7 +52,7 @@ public abstract class PropertyGroup { public PropertyValue getLastWithoutMetadataOrDefault(String defaultValue, String namespace, String... pathAliases) { PropertyValue property = getLastWithoutMetadata(namespace, pathAliases); if (property == null) - property = new PropertyValue(null, defaultValue, "=", -1, this.identifier, this.packName); + property = new PropertyValue(null, defaultValue, PropertySeparator.EQUALS, -1, this.identifier, this.packName); return property; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertySeparator.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertySeparator.java new file mode 100644 index 0000000..612d83f --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertySeparator.java @@ -0,0 +1,11 @@ +package shcm.shsupercm.fabric.citresewn.pack.format; + +public enum PropertySeparator { + EQUALS("="); + + public final String separator; + + PropertySeparator(String separator) { + this.separator = separator; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java index 0294cb2..fe126d7 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java @@ -4,7 +4,7 @@ import net.minecraft.util.Identifier; public record PropertyValue(String keyMetadata, String value, - String delimiter, + PropertySeparator separator, int position, Identifier propertiesIdentifier, String packName) { -- cgit From b8b6fff68c3f24a1f4df9de0ea4170cfc3b0f619 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Fri, 4 Mar 2022 19:20:40 +0200 Subject: Documentation (4/44, 0/35) --- .../shcm/shsupercm/fabric/citresewn/CITResewn.java | 17 +++++++++ .../fabric/citresewn/CITResewnCommand.java | 30 ++++++++++++---- .../shsupercm/fabric/citresewn/cit/ActiveCITs.java | 2 +- .../fabric/citresewn/pack/GlobalProperties.java | 11 ++++++ .../fabric/citresewn/pack/PackParser.java | 41 ++++++++++++++++++++-- 5 files changed, 91 insertions(+), 10 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java index 79e49aa..7d4be88 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewn.java @@ -8,6 +8,9 @@ import org.apache.logging.log4j.Logger; import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; import shcm.shsupercm.fabric.citresewn.cit.CITRegistry; +/** + * Main initializer for CIT Resewn. Contains various internal utilities(just logging for now). + */ public class CITResewn implements ClientModInitializer { public static final Logger LOG = LogManager.getLogger("CITResewn"); @Entrypoint(Entrypoint.CLIENT) @@ -21,16 +24,30 @@ public class CITResewn implements ClientModInitializer { CITResewnCommand.register(); } + /** + * Logs an info line in CIT Resewn's name. + * @param message log message + */ public static void info(String message) { LOG.info("[citresewn] " + message); } + /** + * Logs a warning line in CIT Resewn's name if enabled in config. + * @see CITResewnConfig#mute_warns + * @param message warn message + */ public static void logWarnLoading(String message) { if (CITResewnConfig.INSTANCE.mute_warns) return; LOG.error("[citresewn] " + message); } + /** + * Logs an error line in CIT Resewn's name if enabled in config. + * @see CITResewnConfig#mute_errors + * @param message error message + */ public static void logErrorLoading(String message) { if (CITResewnConfig.INSTANCE.mute_errors) return; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java index 01c08bf..6583cd8 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java @@ -24,12 +24,27 @@ import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.arg import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal; import static net.minecraft.text.Text.of; +/** + * Logic for the /citresewn client command. Only enabled when Fabric API is present.
+ * Structure: + *
+ * /citresewn - General info command
+ * /citresewn config - Opens the config gui(only when Cloth Config is present)
+ * /citresewn analyze pack <pack> - Displays data for the given loaded cit pack.
+ * 
+ */ public class CITResewnCommand { + /** + * @see shcm.shsupercm.fabric.citresewn.mixin.ChatScreenMixin + */ public static boolean openConfig = false; - public static void register() { + /** + * Registers + */ + static void register() { ClientCommandManager.DISPATCHER.register(literal("citresewn") - .executes(context -> { + .executes(context -> { //citresewn context.getSource().sendFeedback(of("CIT Resewn v" + FabricLoader.getInstance().getModContainer("citresewn").orElseThrow().getMetadata().getVersion() + ":")); context.getSource().sendFeedback(of(" Registered: " + CITRegistry.TYPES.values().stream().distinct().count() + " types and " + CITRegistry.CONDITIONS.values().stream().distinct().count() + " conditions")); @@ -43,15 +58,15 @@ public class CITResewnCommand { return 1; }) .then(literal("config") - .executes(context -> { + .executes(context -> { //citresewn config openConfig = true; return 1; })) .then(literal("analyze") .then(literal("pack") - .then(argument("pack", new CITPackArgument()) - .executes(context -> { + .then(argument("pack", new LoadedCITPackArgument()) + .executes(context -> { //citresewn analyze final String pack = context.getArgument("pack", String.class); if (ActiveCITs.isActive()) { context.getSource().sendFeedback(of("Analyzed CIT data of \"" + pack + "\u00a7r\":")); @@ -102,7 +117,10 @@ public class CITResewnCommand { ); } - private static class CITPackArgument implements ArgumentType { + /** + * Greedy string argument that is limited to cit pack names loaded in {@link shcm.shsupercm.fabric.citresewn.cit.ActiveCITs}. + */ + private static class LoadedCITPackArgument implements ArgumentType { @Override public String parse(StringReader reader) throws CommandSyntaxException { StringBuilder builder = new StringBuilder(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java index 2c31641..57d34c3 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java @@ -44,7 +44,7 @@ public class ActiveCITs implements CITDisposable { private ActiveCITs() {} PackParser.loadGlobalProperties(resourceManager, active.globalProperties).callHandlers(); profiler.swap("citresewn:load_cits"); - List> cits = PackParser.loadCITs(resourceManager); + List> cits = PackParser.parseCITs(resourceManager); for (CIT cit : cits) active.cits.computeIfAbsent(cit.type.getClass(), type -> new ArrayList<>()).add(cit); for (Map.Entry, List>> entry : active.cits.entrySet()) { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java index 456faab..6788b1d 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java @@ -2,6 +2,7 @@ package shcm.shsupercm.fabric.citresewn.pack; import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.entrypoint.EntrypointContainer; +import net.minecraft.resource.ResourceManager; import net.minecraft.util.Identifier; import net.minecraft.util.InvalidIdentifierException; import shcm.shsupercm.fabric.citresewn.CITResewn; @@ -16,6 +17,10 @@ import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; +/** + * Property group representation of the global cit.properties file. + * @see PackParser#loadGlobalProperties(ResourceManager, GlobalProperties) + */ public class GlobalProperties extends PropertyGroup { public GlobalProperties() { super("global_properties", new Identifier("citresewn", "global_properties")); @@ -36,6 +41,12 @@ public class GlobalProperties extends PropertyGroup { return this; } + /** + * Calls all {@link CITGlobalProperties} handler entrypoints for every global property they're associated with.
+ * Global properties are matched to their entrypoints by mod id and it's the handler responsibility to filter the properties. + * + * @see CITGlobalProperties + */ public void callHandlers() { for (EntrypointContainer container : FabricLoader.getInstance().getEntrypointContainers(CITGlobalProperties.ENTRYPOINT, CITGlobalProperties.class)) { String containerNamespace = container.getProvider().getMetadata().getId(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 794977d..eab7e46 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -25,14 +25,29 @@ import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; -public class PackParser { +/** + * Utility parsing methods for packs. + */ +public final class PackParser { private PackParser() {} + /** + * Possible CIT roots in resourcepacks ordered in ascending order of priority. + */ private static final String[] ROOTS = new String[] { "mcpatcher", "optifine", "citresewn" }; + + /** + * Gets all resourcepacks from {@link GroupResourcePack} or null if not a group or Fabric API is not present. + */ private static final Function> PARSE_FAPI_GROUPS = FabricLoader.getInstance().isModLoaded("fabric-resource-loader-v0") ? parentPack -> parentPack instanceof GroupResourcePack ? ((GroupResourcePackAccessor) parentPack).getPacks() : null : parentPack -> null; - private static void forEachPack(ResourceManager resourceManager, Consumer run) { + /** + * Iterates over each loaded pack taking into account grouped packs. + * @param resourceManager the manager that contains the packs + * @param run resourcepack pack consumer + */ + public static void forEachPack(ResourceManager resourceManager, Consumer run) { resourceManager.streamResourcePacks().forEachOrdered(pack -> { List grouped = PARSE_FAPI_GROUPS.apply(pack); if (grouped != null) @@ -43,6 +58,14 @@ public class PackParser { }); } + /** + * Loads a merged global property group from loaded packs making sure to respect order. + * + * @see GlobalProperties#callHandlers() + * @param resourceManager the manager that contains the packs + * @param globalProperties global property group to parse into + * @return globalProperties + */ public static GlobalProperties loadGlobalProperties(ResourceManager resourceManager, GlobalProperties globalProperties) { forEachPack(resourceManager, pack -> { for (String root : ROOTS) { @@ -59,7 +82,12 @@ public class PackParser { return globalProperties; } - public static List> loadCITs(ResourceManager resourceManager) { + /** + * Attempts parsing all CITs out of all loaded packs. + * @param resourceManager the manager that contains the packs + * @return unordered list of successfully parsed CITs + */ + public static List> parseCITs(ResourceManager resourceManager) { List> cits = new ArrayList<>(); for (String root : ROOTS) @@ -78,6 +106,13 @@ public class PackParser { return cits; } + /** + * Attempts parsing a CIT from a property group. + * @param properties property group representation of the CIT + * @param resourceManager the manager that contains the the property group, used to resolve relative assets + * @return the successfully parsed CIT + * @throws CITParsingException if the CIT failed parsing for any reason + */ public static CIT parseCIT(PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException { CITType citType = CITRegistry.parseType(properties); -- cgit From 2aeadc2dd30c23aac6bb1d0a349720f28f2609ec Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 5 Mar 2022 08:25:26 +0200 Subject: Documentation (18/44, 0/35) --- .../citresewn/defaults/cit/types/TypeItem.java | 2 +- .../fabric/citresewn/cit/CITCondition.java | 2 +- .../fabric/citresewn/cit/CITRegistry.java | 2 +- .../shsupercm/fabric/citresewn/cit/CITType.java | 2 +- .../fabric/citresewn/ex/CITParsingException.java | 12 +-- .../citresewn/ex/UnknownCITTypeException.java | 3 + .../fabric/citresewn/mixin/ChatScreenMixin.java | 11 ++- .../citresewn/mixin/GroupResourcePackAccessor.java | 6 ++ .../fabric/citresewn/mixin/ModelLoaderMixin.java | 7 ++ .../AbstractFileResourcePackMixin.java | 16 +++- .../mixin/broken_paths/IdentifierMixin.java | 8 +- .../ReloadableResourceManagerImplMixin.java | 8 +- .../ResourcePackCompatibilityMixin.java | 8 +- .../pack/format/PropertiesGroupAdapter.java | 3 +- .../citresewn/pack/format/PropertyGroup.java | 100 +++++++++++++++++++-- .../fabric/citresewn/pack/format/PropertyKey.java | 12 +++ .../citresewn/pack/format/PropertySeparator.java | 12 ++- .../citresewn/pack/format/PropertyValue.java | 9 ++ 18 files changed, 197 insertions(+), 26 deletions(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java index f37fd6b..21e1ab0 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -406,7 +406,7 @@ public class TypeItem extends CITType { }; if (replacement != null) { - CITResewn.logWarnLoading(CITParsingException.descriptionOf("Warning: Using deprecated sub item id \"" + subItem + "\" instead of \"" + replacement + "\"", properties, position)); + CITResewn.logWarnLoading(properties.messageWithDescriptorOf("Warning: Using deprecated sub item id \"" + subItem + "\" instead of \"" + replacement + "\"", position)); return new Identifier("minecraft", "item/" + replacement); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java index b5c1996..fd00ac6 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java @@ -22,6 +22,6 @@ public abstract class CITCondition { public abstract boolean test(CITContext context); protected void warn(String message, PropertyValue value, PropertyGroup properties) { - CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value.position())); + CITResewn.logWarnLoading("Warning: " + properties.messageWithDescriptorOf(message, value.position())); } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java index 47f79fe..d8454a0 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java @@ -56,7 +56,7 @@ public class CITRegistry { public static CITCondition parseCondition(PropertyKey key, PropertyValue value, PropertyGroup properties) throws CITParsingException { CITConditionContainer conditionContainer = CONDITIONS.get(key); if (conditionContainer == null) { - logWarnLoading(CITParsingException.descriptionOf("Unknown condition type \"" + key.toString() + "\"", properties, value.position())); + logWarnLoading(properties.messageWithDescriptorOf("Unknown condition type \"" + key.toString() + "\"", value.position())); return new ConstantCondition(false); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java index c3bb134..b35d26c 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java @@ -16,7 +16,7 @@ public abstract class CITType { public abstract void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException; protected void warn(String message, PropertyValue value, PropertyGroup properties) { - CITResewn.logWarnLoading("Warning: " + CITParsingException.descriptionOf(message, properties, value == null ? -1 : value.position())); + CITResewn.logWarnLoading("Warning: " + properties.messageWithDescriptorOf(message, value == null ? -1 : value.position())); } /** diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java index 811d16b..f897ba7 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/CITParsingException.java @@ -2,16 +2,16 @@ package shcm.shsupercm.fabric.citresewn.ex; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +/** + * Thrown if errored while parsing the properties of a {@link PropertyGroup}. + * @see PropertyGroup#messageWithDescriptorOf(String, int) + */ public class CITParsingException extends Exception { public CITParsingException(String message, PropertyGroup propertyGroup, int position, Throwable throwable) { - super("Errored while parsing CIT: " + descriptionOf(message, propertyGroup, position), throwable); + super("Errored while parsing CIT: " + propertyGroup.messageWithDescriptorOf(message, position), throwable); } public CITParsingException(String message, PropertyGroup propertyGroup, int position) { - super("Errored while parsing CIT: " + descriptionOf(message, propertyGroup, position)); - } - - public static String descriptionOf(String message, PropertyGroup propertyGroup, int position) { - return message + (position != -1 ? " @L" + position : "") + " in " + propertyGroup.identifier.toString() + " from " + propertyGroup.packName; + super("Errored while parsing CIT: " + propertyGroup.messageWithDescriptorOf(message, position)); } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/UnknownCITTypeException.java b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/UnknownCITTypeException.java index eacbc69..23f9c82 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/ex/UnknownCITTypeException.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/ex/UnknownCITTypeException.java @@ -2,6 +2,9 @@ package shcm.shsupercm.fabric.citresewn.ex; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; +/** + * Thrown when a property group contains an unrecognized value associated with the "type" key. + */ public class UnknownCITTypeException extends CITParsingException { public UnknownCITTypeException(PropertyGroup propertyGroup, int position) { super("Unknown type", propertyGroup, position); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ChatScreenMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ChatScreenMixin.java index 5bacbde..c79143b 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ChatScreenMixin.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ChatScreenMixin.java @@ -9,14 +9,23 @@ import net.minecraft.text.Text; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; +import shcm.shsupercm.fabric.citresewn.CITResewnCommand; import shcm.shsupercm.fabric.citresewn.config.CITResewnConfigScreenFactory; import static shcm.shsupercm.fabric.citresewn.CITResewnCommand.openConfig; +/** + * Opens the config screen when running the "/citresewn config" command. + * @see CITResewnCommand#openConfig + */ @Mixin(ChatScreen.class) public class ChatScreenMixin { + /** + * If {@link CITResewnCommand#openConfig} is true, changes the screen that's opened when the chat is closed to the config screen. + * @see CITResewnCommand#openConfig + */ @ModifyArg(method = "keyPressed", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/MinecraftClient;setScreen(Lnet/minecraft/client/gui/screen/Screen;)V")) - public Screen redirectConfigScreen(Screen original) { + public Screen citresewn$redirectConfigScreen(Screen original) { if (openConfig) { openConfig = false; return FabricLoader.getInstance().isModLoaded("cloth-config2") ? diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java index 72af871..8263be8 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java @@ -4,9 +4,15 @@ import net.fabricmc.fabric.impl.resource.loader.GroupResourcePack; import net.minecraft.resource.ResourcePack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; +import shcm.shsupercm.fabric.citresewn.pack.PackParser; import java.util.List; +/** + * Access for individual packs in a grouped resourcepack.
+ * Used by Fabric API to bundle all mods' resources into a single pack. + * @see PackParser#forEachPack + */ @Mixin(GroupResourcePack.class) public interface GroupResourcePackAccessor { @Accessor diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java index ea1d5ab..df11ac9 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/ModelLoaderMixin.java @@ -10,8 +10,15 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; +/** + * Initializes the (re)loading of active cits in the resource manager. + * @see ActiveCITs + */ @Mixin(ModelLoader.class) public class ModelLoaderMixin { + /** + * @see ActiveCITs#load(ResourceManager, Profiler) + */ @Inject(method = "", at = @At(value = "INVOKE", ordinal = 0, target = "Lnet/minecraft/util/profiler/Profiler;push(Ljava/lang/String;)V")) private void citresewn$loadCITs(ResourceManager resourceManager, BlockColors blockColors, Profiler profiler, int i, CallbackInfo ci) { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java index 9ad7992..b241fff 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/AbstractFileResourcePackMixin.java @@ -14,33 +14,43 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import shcm.shsupercm.fabric.citresewn.config.BrokenPaths; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.zip.ZipFile; +/** + * Adds a resourcepack compatibility error message when broken paths are enabled and are detected in a pack. + * @see BrokenPaths + * @see ResourcePackCompatibilityMixin + */ @Mixin(AbstractFileResourcePack.class) public abstract class AbstractFileResourcePackMixin implements ResourcePack { @Shadow @Final protected File base; @SuppressWarnings({"unchecked", "ConstantConditions", "EqualsBetweenInconvertibleTypes"}) @Inject(method = "parseMetadata(Lnet/minecraft/resource/metadata/ResourceMetadataReader;)Ljava/lang/Object;", cancellable = true, at = @At("RETURN")) - public void parseMetadata(ResourceMetadataReader metaReader, CallbackInfoReturnable cir) { + public void citresewn$brokenpaths$parseMetadata(ResourceMetadataReader metaReader, CallbackInfoReturnable cir) { if (cir.getReturnValue() != null) try { if (this.getClass().equals(ZipResourcePack.class)) { try (ZipFile zipFile = new ZipFile(base)) { zipFile.stream() .forEach(entry -> { - if (entry.getName().startsWith("assets")) + if (entry.getName().startsWith("assets") && !entry.getName().endsWith(".DS_Store")) new Identifier("minecraft", entry.getName()); }); } } else if (this.getClass().equals(DirectoryResourcePack.class)) { final Path assets = new File(base, "assets").toPath(); Files.walk(assets) - .forEach(path -> new Identifier("minecraft", assets.relativize(path).toString().replace('\\', '/'))); + .forEach(fullPath -> { + String path = assets.relativize(fullPath).toString().replace('\\', '/'); + if (!path.endsWith(".DS_Store")) + new Identifier("minecraft", path); + }); } } catch (InvalidIdentifierException e) { cir.setReturnValue((T) new PackResourceMetadata(cir.getReturnValue().getDescription(), Integer.MAX_VALUE - 53)); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java index 0be08f9..0bc36c3 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/IdentifierMixin.java @@ -6,13 +6,19 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import shcm.shsupercm.fabric.citresewn.CITResewn; +import shcm.shsupercm.fabric.citresewn.config.BrokenPaths; import static shcm.shsupercm.fabric.citresewn.config.BrokenPaths.processingBrokenPaths; +/** + * Applies broken paths logic when active. + * @see BrokenPaths + * @see ReloadableResourceManagerImplMixin + */ @Mixin(Identifier.class) public class IdentifierMixin { @Inject(method = "isPathValid", cancellable = true, at = @At("RETURN")) - private static void processBrokenPaths(String path, CallbackInfoReturnable cir) { + private static void citresewn$brokenpaths$processBrokenPaths(String path, CallbackInfoReturnable cir) { if (!processingBrokenPaths) return; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java index 3f54be3..1d94285 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ReloadableResourceManagerImplMixin.java @@ -12,6 +12,7 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import shcm.shsupercm.fabric.citresewn.CITResewn; +import shcm.shsupercm.fabric.citresewn.config.BrokenPaths; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -19,12 +20,17 @@ import java.util.concurrent.Executor; import static shcm.shsupercm.fabric.citresewn.config.BrokenPaths.processingBrokenPaths; +/** + * Starts/Stops broken paths logic. + * @see BrokenPaths + * @see IdentifierMixin + */ @Mixin(ReloadableResourceManagerImpl.class) public class ReloadableResourceManagerImplMixin { @Shadow @Final private ResourceType type; @Inject(method = "reload", at = @At("RETURN")) - public void onReload(Executor prepareExecutor, Executor applyExecutor, CompletableFuture initialStage, List packs, CallbackInfoReturnable cir) { + public void citresewn$brokenpaths$onReload(Executor prepareExecutor, Executor applyExecutor, CompletableFuture initialStage, List packs, CallbackInfoReturnable cir) { if (processingBrokenPaths = this.type == ResourceType.CLIENT_RESOURCES) { CITResewn.LOG.error("[citresewn] Caution! Broken paths is enabled!"); cir.getReturnValue().whenComplete().thenRun(() -> processingBrokenPaths = false); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java index f187a56..813eb3d 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/broken_paths/ResourcePackCompatibilityMixin.java @@ -7,7 +7,13 @@ import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import shcm.shsupercm.fabric.citresewn.config.BrokenPaths; +/** + * Adds a resourcepack compatibility error message when broken paths are enabled and are detected in a pack. + * @see BrokenPaths + * @see AbstractFileResourcePackMixin + */ @Mixin(ResourcePackCompatibility.class) public abstract class ResourcePackCompatibilityMixin { private static final ResourcePackCompatibility BROKEN_PATHS = ResourcePackCompatibility("BROKEN_PATHS", -1, "broken_paths"); @@ -19,7 +25,7 @@ public abstract class ResourcePackCompatibilityMixin { } @Inject(method = "from(ILnet/minecraft/resource/ResourceType;)Lnet/minecraft/resource/ResourcePackCompatibility;", cancellable = true, at = @At("HEAD")) - private static void redirectBrokenPathsCompatibility(int packVersion, ResourceType type, CallbackInfoReturnable cir) { + private static void citresewn$brokenpaths$redirectBrokenPathsCompatibility(int packVersion, ResourceType type, CallbackInfoReturnable cir) { if (packVersion == Integer.MAX_VALUE - 53) cir.setReturnValue(BROKEN_PATHS); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java index 4912a71..0375079 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertiesGroupAdapter.java @@ -1,6 +1,7 @@ package shcm.shsupercm.fabric.citresewn.pack.format; import net.minecraft.util.Identifier; +import net.minecraft.util.InvalidIdentifierException; import java.io.*; import java.nio.charset.StandardCharsets; @@ -18,7 +19,7 @@ public class PropertiesGroupAdapter extends PropertyGroup { } @Override - public PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException { + public PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { String line; int linePos = 0, multilineSkip = 0; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java index 1f21ed5..8d185fd 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyGroup.java @@ -7,9 +7,29 @@ import java.io.IOException; import java.io.InputStream; import java.util.*; +/** + * Storage agnostic map of keys and values.
+ * Keys are stored as {@link PropertyKey}s holding the mod id of the property type.
+ * A key can have multiple values associated with it as they are stored in an ordered set. + * + * @see PropertyKey + * @see PropertyValue + * @see PropertiesGroupAdapter + */ public abstract class PropertyGroup { + /** + * The internal map that backs this property group. + */ public final Map> properties = new LinkedHashMap<>(); + + /** + * This group's location in its resourcepack. + */ public final Identifier identifier; + + /** + * The file name of the resourcepack that this property group is in. + */ public final String packName; protected PropertyGroup(String packName, Identifier identifier) { @@ -17,17 +37,63 @@ public abstract class PropertyGroup { this.identifier = identifier; } + /** + * Tries to parse a group out of a stream. + * @see #load(String, Identifier, InputStream) + * @see #getExtension() + * @see PropertiesGroupAdapter + * @param packName {@link #packName} + * @param identifier {@link #identifier}, needed for extension matching + * @param is a stream containing properties as specified by implementation + * @return the parsed group or null if could not match an adapter + * @throws IOException if errored while parsing the group + */ + public static PropertyGroup tryParseGroup(String packName, Identifier identifier, InputStream is) throws IOException { + PropertyGroup group = null; + if (identifier.getPath().endsWith(PropertiesGroupAdapter.EXTENSION)) + group = new PropertiesGroupAdapter(packName, identifier); + + return group == null ? null : group.load(packName, identifier, is); + } + + /** + * @return file suffix for this property group's implementation + */ public abstract String getExtension(); + /** + * Reads the given input stream into the group. + * @param packName {@link #packName} + * @param identifier {@link #identifier} + * @param is a stream containing properties as specified by implementation + * @return this + * @throws IOException if errored while reading the stream + * @throws InvalidIdentifierException if encountered a malformed {@link Identifier} while reading + */ public abstract PropertyGroup load(String packName, Identifier identifier, InputStream is) throws IOException, InvalidIdentifierException; - protected void put(int position, String packName, Identifier propertiesIdentifier, String key, String keyMetadata, PropertySeparator separator, String value) throws InvalidIdentifierException { + /** + * Adds the given value to the group. + * @param position implementation specific interpretation of the value's position in the group, has no effect on internal order + * @param packName the value's resourcepack file name + * @param propertiesIdentifier the value's property group location identifier + * @param key the value's key name + * @param keyMetadata nullable, implementation specific metadata for this value's key + * @param separator implementation specific connection between the key and the value + * @param value string representation of the value to be parsed by the group's user + */ + protected void put(int position, String packName, Identifier propertiesIdentifier, String key, String keyMetadata, PropertySeparator separator, String value) { Objects.requireNonNull(key); Objects.requireNonNull(value); this.properties.computeIfAbsent(PropertyKey.of(key), id -> new LinkedHashSet<>()).add(new PropertyValue(keyMetadata, value, separator, position, propertiesIdentifier, packName)); } + /** + * @param namespace the key's namespace(should be the value type's modid by convention) + * @param pathAliases all key name aliases to check for + * @return all values associated with the given key by alias>insertion order + */ public Set get(String namespace, String... pathAliases) { Set values = new LinkedHashSet<>(); @@ -40,6 +106,12 @@ public abstract class PropertyGroup { return values; } + /** + * @see #getLastWithoutMetadataOrDefault(String, String, String...) + * @param namespace the key's namespace(should be the value type's modid by convention) + * @param pathAliases all key name aliases to check for + * @return the last value associated with the key(by insertion order) that has a null key metadata or null if the key is not present in the group + */ public PropertyValue getLastWithoutMetadata(String namespace, String... pathAliases) { PropertyValue value = null; for (PropertyValue next : get(namespace, pathAliases)) @@ -49,6 +121,13 @@ public abstract class PropertyGroup { return value; } + /** + * @see #getLastWithoutMetadata(String, String...) + * @param defaultValue the dummy value to return if not present in the group + * @param namespace the key's namespace(should be the value type's modid by convention) + * @param pathAliases all key name aliases to check for + * @return the last value associated with the key(by insertion order) that has a null key metadata or the wrapped default value if the key is not present in the group + */ public PropertyValue getLastWithoutMetadataOrDefault(String defaultValue, String namespace, String... pathAliases) { PropertyValue property = getLastWithoutMetadata(namespace, pathAliases); if (property == null) @@ -57,15 +136,22 @@ public abstract class PropertyGroup { return property; } + /** + * @see #getExtension() + * @see #identifier + * @return the name of this group without its path or extension + */ public String stripName() { return identifier.getPath().substring(identifier.getPath().lastIndexOf('/') + 1, identifier.getPath().length() - getExtension().length()); } - public static PropertyGroup tryParseGroup(String packName, Identifier identifier, InputStream is) throws IOException { - PropertyGroup group = null; - if (identifier.getPath().endsWith(PropertiesGroupAdapter.EXTENSION)) - group = new PropertiesGroupAdapter(packName, identifier); - - return group == null ? null : group.load(packName, identifier, is); + /** + * Compiles a message with attached info on a value's origin. + * @param message message to add descriptor to + * @param position implementation specific position of + * @return the formatted message + */ + public String messageWithDescriptorOf(String message, int position) { + return message + (position != -1 ? " @L" + position : "") + " in " + this.identifier.toString() + " from " + this.packName; } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java index 37a698d..7bc2cdc 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyKey.java @@ -1,6 +1,18 @@ package shcm.shsupercm.fabric.citresewn.pack.format; +import net.minecraft.util.Identifier; + +/** + * Namespace/path pair of strings. Similar to {@link Identifier} but without validity restrictions. + * @see Identifier + */ public record PropertyKey(String namespace, String path) { + /** + * Attempts to split a given string into a namespace and path by the first occurrence of a colon.
+ * If a namespace cannot be extracted from the given string, "citresewn" is set instead. + * @param key key to parse + * @return parsed property key + */ public static PropertyKey of(String key) { String[] split = new String[] {"citresewn", key}; int i = key.indexOf(':'); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertySeparator.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertySeparator.java index 612d83f..ce4ebab 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertySeparator.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertySeparator.java @@ -1,8 +1,18 @@ package shcm.shsupercm.fabric.citresewn.pack.format; +/** + * Marker for the connection between a {@link PropertyKey} and its {@link PropertyValue}. + */ public enum PropertySeparator { - EQUALS("="); + /** + * Marks either a check for equality or an action to set a value. + */ + EQUALS("=") + ; + /** + * String representation of the separator. + */ public final String separator; PropertySeparator(String separator) { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java index fe126d7..f41119f 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/format/PropertyValue.java @@ -2,6 +2,15 @@ package shcm.shsupercm.fabric.citresewn.pack.format; import net.minecraft.util.Identifier; +/** + * Wrapped representation of a property group's value with additional attached metadata. + * @param keyMetadata nullable, implementation specific metadata for this value's key + * @param value string representation of the value to be parsed by the group's user + * @param separator implementation specific connection between the key and the value + * @param position implementation specific interpretation of the value's position in the group, has no effect on internal order + * @param propertiesIdentifier the value's property group location identifier + * @param packName the value's resourcepack file name + */ public record PropertyValue(String keyMetadata, String value, PropertySeparator separator, -- cgit From 7a6a31c7c5040959b47f55ec96fb614dfb4d8efb Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 5 Mar 2022 08:56:26 +0200 Subject: Documentation (23/44, 0/35) --- .../fabric/citresewn/config/BrokenPaths.java | 18 ++++++++++ .../fabric/citresewn/config/CITResewnConfig.java | 39 +++++++++++++++++++++- .../config/CITResewnConfigScreenFactory.java | 13 ++++++++ .../config/CITResewnMixinConfiguration.java | 8 +++++ .../fabric/citresewn/config/CITResewnModMenu.java | 3 ++ 5 files changed, 80 insertions(+), 1 deletion(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/BrokenPaths.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/BrokenPaths.java index c89e3cb..f4b2c65 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/BrokenPaths.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/BrokenPaths.java @@ -1,5 +1,23 @@ package shcm.shsupercm.fabric.citresewn.config; +import net.minecraft.util.Identifier; +import shcm.shsupercm.fabric.citresewn.mixin.broken_paths.*; + +/** + * Broken paths are resourcepack file paths that do not follow {@link Identifier}'s specifications.
+ * When enabled in config, CIT Resewn will forcibly allow broken paths to load.
+ * If not enabled, broken paths has no effect on the game. + * @see CITResewnConfig#broken_paths + * @see CITResewnMixinConfiguration#broken_paths + * @see ReloadableResourceManagerImplMixin + * @see IdentifierMixin + * @see AbstractFileResourcePackMixin + */ public class BrokenPaths { + /** + * When enabled, {@link Identifier}s will not check for their path's validity. + * @see ReloadableResourceManagerImplMixin + * @see IdentifierMixin + */ public static boolean processingBrokenPaths = false; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfig.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfig.java index 2f051f0..cd66fed 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfig.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfig.java @@ -2,22 +2,54 @@ package shcm.shsupercm.fabric.citresewn.config; import com.google.gson.Gson; import com.google.gson.stream.JsonWriter; +import net.fabricmc.loader.api.FabricLoader; import org.apache.commons.io.IOUtils; import shcm.shsupercm.fabric.citresewn.CITResewn; import java.io.*; +/** + * Contains runtime representation of CIT Resewn's config, encoded using GSON. + */ public class CITResewnConfig { + /** + * Whether CIT Resewn should work or not.
+ * Requires a restart. + */ public boolean enabled = true; + /** + * Mutes pack loading errors from logs. + */ public boolean mute_errors = false; + /** + * Mutes pack loading warnings from logs. + */ public boolean mute_warns = false; + /** + * Invalidating interval for CITs' caches in milliseconds. Set to 0 to disable caching. + */ public int cache_ms = 50; + /** + * Should broken paths be allowed in resourcepacks. Requires a restart. + * @see BrokenPaths + */ public boolean broken_paths = false; - private static final File FILE = new File("config/citresewn.json"); + /** + * CIT Resewn's config storage file. + */ + private static final File FILE = new File(FabricLoader.getInstance().getConfigDir().toFile(), "citresewn.json"); + /** + * Active instance of the current config. + */ public static final CITResewnConfig INSTANCE = read(); + /** + * Reads the stored config. + * @see #FILE + * @return the read config + */ public static CITResewnConfig read() { if (!FILE.exists()) return new CITResewnConfig().write(); @@ -33,6 +65,11 @@ public class CITResewnConfig { } } + /** + * Saves this config to file. + * @see #FILE + * @return this + */ public CITResewnConfig write() { Gson gson = new Gson(); JsonWriter writer = null; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java index b05dc6e..c1c35b2 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnConfigScreenFactory.java @@ -12,9 +12,22 @@ import net.minecraft.util.Formatting; import java.util.function.Function; +/** + * Cloth Config integration to CIT Resewn's config + * @see CITResewnConfig + */ public class CITResewnConfigScreenFactory { + /** + * Used to get CIT Resewn - Defaults's Cloth Config implementation. + */ public static final String DEFAULTS_CONFIG_ENTRYPOINT = "citresewn-defaults:config_screen"; + /** + * Creates a Cloth Config screen for the current active config instance. + * @param parent parent to return to from the config screen + * @return the config screen + * @throws NoClassDefFoundError if Cloth Config is not present + */ public static Screen create(Screen parent) { CITResewnConfig currentConfig = CITResewnConfig.INSTANCE, defaultConfig = new CITResewnConfig(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java index 29f64e9..742b929 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java @@ -8,9 +8,17 @@ import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import java.util.List; import java.util.Set; +/** + * Mixin configuration for CIT Resewn's mixins. + */ public class CITResewnMixinConfiguration implements IMixinConfigPlugin { private static final String MIXINS_ROOT = "shcm.shsupercm.fabric.citresewn.mixin"; + /** + * Is Broken Paths enabled in config. + * @see BrokenPaths + * @see CITResewnConfig#broken_paths + */ private boolean broken_paths; @Override diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java index 521c3b6..095f0cb 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnModMenu.java @@ -8,6 +8,9 @@ import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.NoticeScreen; import net.minecraft.text.Text; +/** + * Mod Menu config button integration. + */ @Entrypoint("modmenu") public class CITResewnModMenu implements ModMenuApi { @Override -- cgit From 6f84ebf371a7aa8728375c0633b19e489c67de5e Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 5 Mar 2022 13:40:37 +0200 Subject: Fixed Fabric API resources integration --- .../shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java index 8263be8..8acd336 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java @@ -3,6 +3,7 @@ package shcm.shsupercm.fabric.citresewn.mixin; import net.fabricmc.fabric.impl.resource.loader.GroupResourcePack; import net.minecraft.resource.ResourcePack; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.gen.Accessor; import shcm.shsupercm.fabric.citresewn.pack.PackParser; @@ -13,8 +14,9 @@ import java.util.List; * Used by Fabric API to bundle all mods' resources into a single pack. * @see PackParser#forEachPack */ -@Mixin(GroupResourcePack.class) +@Pseudo +@Mixin(value = GroupResourcePack.class, remap = false) public interface GroupResourcePackAccessor { - @Accessor + @Accessor(remap = false) List getPacks(); } -- cgit From 09792f49ee89c6b4ff37464acec4b94b3f9f370b Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 5 Mar 2022 14:21:15 +0200 Subject: Fixed log spam from Lambda Better Grass --- .../java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java | 2 +- src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java index 6788b1d..c16242f 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java @@ -28,7 +28,7 @@ public class GlobalProperties extends PropertyGroup { @Override public String getExtension() { - return ""; + return ".properties"; } @Override diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index eab7e46..adc935a 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -74,6 +74,9 @@ public final class PackParser { private PackParser() {} globalProperties.load(pack.getName(), identifier, pack.open(ResourceType.CLIENT_RESOURCES, identifier)); } catch (FileNotFoundException ignored) { } catch (IOException e) { + // fixes log spam from Lambda Better Grass + if (pack.getClass().getSimpleName().equals("LBGResourcePack")) continue; + CITResewn.logErrorLoading("Errored while loading global properties: " + identifier + " from " + pack.getName()); e.printStackTrace(); } -- cgit From bb9dcef4b53d201cf4bcac3bf88d2042a1ce226c Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sat, 5 Mar 2022 18:44:04 +0200 Subject: Documentation (29/44, 0/35) --- .../citresewn/defaults/cit/types/TypeItem.java | 7 ++- .../shcm/shsupercm/fabric/citresewn/cit/CIT.java | 30 ++++++++++++ .../shsupercm/fabric/citresewn/cit/CITCache.java | 51 ++++++++++++++++++-- .../fabric/citresewn/cit/CITCondition.java | 36 +++++++++++++++ .../shsupercm/fabric/citresewn/cit/CITContext.java | 26 ++++++++++- .../fabric/citresewn/cit/CITRegistry.java | 54 +++++++++++++++++++++- .../shsupercm/fabric/citresewn/cit/CITType.java | 23 +++++++++ 7 files changed, 218 insertions(+), 9 deletions(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java index 21e1ab0..aa4df72 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeItem.java @@ -40,8 +40,11 @@ import java.util.*; import java.util.stream.Collectors; /** - * Do not go through this class, it looks awful because it was ported from a "proof of concept".
- * The whole type will be rewritten at some point. + * ///// PORTED FROM BETA \\\\\ + * This shit was ported from the + * beta and will be rewritten at + * some point! + * \\\\\ ///// */ public class TypeItem extends CITType { @Entrypoint(CITTypeContainer.ENTRYPOINT) diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java index 3bc708f..7c7ba5b 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CIT.java @@ -2,11 +2,34 @@ package shcm.shsupercm.fabric.citresewn.cit; import net.minecraft.util.Identifier; +/** + * Runtime representation of a CIT, holding its type and conditions as well as additional metadata. + */ public class CIT { + /** + * The full location of this CIT in its resourcepack. + */ public final Identifier propertiesIdentifier; + + /** + * Name of the resourcepack that contains this CIT. + */ public final String packName; + + /** + * The CIT's type. + * @see CITType + */ public final T type; + + /** + * Conditions that must be met for this CIT to work. + */ public final CITCondition[] conditions; + + /** + * The weight of this CIT to be used when resolving multiple CIT matching conflicts. + */ public final int weight; public CIT(Identifier propertiesIdentifier, String packName, T type, CITCondition[] conditions, int weight) { @@ -17,6 +40,13 @@ public class CIT { this.weight = weight; } + /** + * Tests the given context against all of this CIT's conditions. + * + * @see #conditions + * @param context context to check + * @return true if none of this CIT's {@link #conditions} tested false + */ public boolean test(CITContext context) { try { for (CITCondition condition : conditions) diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCache.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCache.java index 5fc6f5a..31ccf04 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCache.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCache.java @@ -1,5 +1,6 @@ package shcm.shsupercm.fabric.citresewn.cit; +import net.minecraft.item.ItemStack; import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; import java.lang.ref.WeakReference; @@ -7,17 +8,42 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Function; +/** + * Runtime cache for a CIT type to be stored in type implementation specific locations. (usually ducked onto {@link ItemStack}s) + * @see Single + * @see MultiList + */ public abstract class CITCache { + /** + * The last time in epoch milliseconds that this cache invalidated its stored CIT. + */ public long lastCachedStamp = 0; + /** + * Common implementation of a single CIT per holder({@link ItemStack}) caching. + */ public static class Single extends CITCache { - public WeakReference> cit = null; - public final Function> realtime; + /** + * A reload-safe reference to the CIT that was last selected for this holder. + */ + protected WeakReference> cit = null; + + /** + * Real time Context -> CIT supplier for this cache for invalidated holders. + */ + protected final Function> realtime; public Single(Function> realtime) { this.realtime = realtime; } + /** + * Retrieves the CIT reference associated with this cache and invalidates it every config-defined interval. + * + * @see CITResewnConfig#cache_ms + * @param context context to check + * @return reference to the CIT or reference to null if no CIT applied + */ public WeakReference> get(CITContext context) { if (this.cit == null || System.currentTimeMillis() - this.lastCachedStamp >= CITResewnConfig.INSTANCE.cache_ms) { this.cit = new WeakReference<>(this.realtime.apply(context)); @@ -28,14 +54,31 @@ public abstract class CITCache { } } + /** + * Common implementation of multiple CITs per holder({@link ItemStack}) caching. + */ public static class MultiList extends CITCache { - public List>> cit = null; - public final Function>> realtime; + /** + * List of reload-safe references to CITs that were last selected for this holder. + */ + protected List>> cit = null; + + /** + * Real time Context -> CIT list supplier for this cache for invalidated holders. + */ + protected final Function>> realtime; public MultiList(Function>> realtime) { this.realtime = realtime; } + /** + * Retrieves the CIT references associated with this cache and invalidates them every config-defined interval. + * + * @see CITResewnConfig#cache_ms + * @param context context to check + * @return list of references to CITs or empty list no CIT applied + */ public List>> get(CITContext context) { if (this.cit == null || System.currentTimeMillis() - this.lastCachedStamp >= CITResewnConfig.INSTANCE.cache_ms) { this.cit = new ArrayList<>(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java index fd00ac6..cd4cb9d 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITCondition.java @@ -1,6 +1,8 @@ package shcm.shsupercm.fabric.citresewn.cit; import shcm.shsupercm.fabric.citresewn.CITResewn; +import shcm.shsupercm.fabric.citresewn.api.CITConditionContainer; +import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; @@ -8,19 +10,53 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import java.util.Collections; import java.util.Set; +/** + * Instanced parent for CIT Types that are applied to items when conditions pass.
+ * Common condition types are available under {@link shcm.shsupercm.fabric.citresewn.cit.builtin.conditions}. + * @see CITConditionContainer + * @see CIT + */ public abstract class CITCondition { + /** + * Parses the given property value into the condition. + * @param value value to read + * @param properties the group containing value + * @throws CITParsingException if errored while parsing the condition + */ public abstract void load(PropertyValue value, PropertyGroup properties) throws CITParsingException; + /** + * @return a set of classes of conditions that have integration with this condition + */ public Set> siblingConditions() { return Collections.emptySet(); } + /** + * Modifies the given sibling if present in the CIT and declared in {@link #siblingConditions()}. + * @param sibling sibling to modify or be modified by + * @return the sibling or null to remove it from the CIT. + */ public T modifySibling(T sibling) { return sibling; } + /** + * Tests the given context against this condition. + * @param context context to check + * @return true if the given context passes + */ public abstract boolean test(CITContext context); + /** + * Logs a warning with the given value's descriptor if enabled in config. + * + * @see CITResewn#logWarnLoading(String) + * @see CITResewnConfig#mute_warns + * @param message warning message + * @param value value associated with the warning + * @param properties property group associated with the warning + */ protected void warn(String message, PropertyValue value, PropertyGroup properties) { CITResewn.logWarnLoading("Warning: " + properties.messageWithDescriptorOf(message, value.position())); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java index c5f1922..cfc10f8 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITContext.java @@ -11,23 +11,47 @@ import net.minecraft.nbt.NbtElement; import net.minecraft.util.Identifier; import net.minecraft.world.World; +import javax.annotation.Nullable; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; +/** + * Holds momentary information to be used for CITs' condition matching and type effects. + */ public class CITContext { + /** + * The main item stack to check for the CIT. + */ public final ItemStack stack; + + /** + * The item's containing world(defaults to {@link MinecraftClient#world} if null) + */ public final World world; + + /** + * The item's associated living entity if present. (null if not relevant) + */ + @Nullable public final LivingEntity entity; + /** + * Cached enchantment map from {@link #stack}. + * @see #enchantments() + */ private Map enchantments = null; - public CITContext(ItemStack stack, World world, LivingEntity entity) { + public CITContext(ItemStack stack, @Nullable World world, @Nullable LivingEntity entity) { this.stack = stack; this.world = world == null ? MinecraftClient.getInstance().world : world; this.entity = entity; } + /** + * @see #enchantments + * @return a map of this context item's enchantments + */ public Map enchantments() { if (this.enchantments == null) { this.enchantments = new LinkedHashMap<>(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java index d8454a0..bf7c2ca 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITRegistry.java @@ -7,6 +7,7 @@ import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; import shcm.shsupercm.fabric.citresewn.cit.builtin.conditions.ConstantCondition; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.ex.UnknownCITTypeException; +import shcm.shsupercm.fabric.citresewn.pack.PackParser; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; @@ -16,13 +17,38 @@ import java.util.*; import static shcm.shsupercm.fabric.citresewn.CITResewn.info; import static shcm.shsupercm.fabric.citresewn.CITResewn.logWarnLoading; -public class CITRegistry { +/** + * Holds a static registry runtime for all types and conditions. + * @see PackParser + * @see CITTypeContainer + * @see CITConditionContainer + */ +public final class CITRegistry { private CITRegistry(){} + /** + * Currently registered CIT types. + */ public static final Map> TYPES = new HashMap<>(); + /** + * Currently registered condition types. + */ public static final Map> CONDITIONS = new HashMap<>(); + /** + * Fast id lookup map for types. + * @see #idOfType(Class) + */ private static final Map, Identifier> TYPE_TO_ID = new IdentityHashMap<>(); + /** + * Fast id lookup map for conditions. + * @see #idOfCondition(Class) + */ private static final Map, PropertyKey> CONDITION_TO_ID = new IdentityHashMap<>(); + /** + * Loads all available CIT and condition types to registry. (internal use only) + * @see CITTypeContainer + * @see CITConditionContainer + */ public static void registerAll() { info("Registering CIT Conditions"); for (var entrypointContainer : FabricLoader.getInstance().getEntrypointContainers(CITConditionContainer.ENTRYPOINT, CITConditionContainer.class)) { @@ -53,6 +79,15 @@ public class CITRegistry { } } + /** + * Parses a condition from the given property.
+ * + * @param key the condition's key in the group + * @param value the condition's value + * @param properties the containing property group + * @return the parsed condition or an always-failing {@link ConstantCondition} if unrecognized + * @throws CITParsingException if errored while parsing hte condition + */ public static CITCondition parseCondition(PropertyKey key, PropertyValue value, PropertyGroup properties) throws CITParsingException { CITConditionContainer conditionContainer = CONDITIONS.get(key); if (conditionContainer == null) { @@ -65,7 +100,14 @@ public class CITRegistry { return condition; } - public static CITType parseType(PropertyGroup properties) throws CITParsingException { + /** + * Parses a CIT type from the given property group.
+ * If the group does not contain a "citresewn:type" property, defaults to "citresewn:item". + * @param properties group of properties to parse the CIT type from + * @return a new instance of the group's CIT type + * @throws UnknownCITTypeException if the given type is unrecognized in the registry + */ + public static CITType parseType(PropertyGroup properties) throws UnknownCITTypeException { Identifier type = new Identifier("citresewn", "item"); PropertyValue propertiesType = properties.getLastWithoutMetadata("citresewn", "type"); @@ -84,10 +126,18 @@ public class CITRegistry { return typeContainer.createType.get(); } + /** + * @see #TYPE_TO_ID + * @return the id of the given CIT type's class. + */ public static Identifier idOfType(Class clazz) { return TYPE_TO_ID.get(clazz); } + /** + * @see #CONDITION_TO_ID + * @return the first key of the given condition's class. + */ public static PropertyKey idOfCondition(Class clazz) { return CONDITION_TO_ID.get(clazz); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java index b35d26c..65b3097 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/CITType.java @@ -3,6 +3,7 @@ package shcm.shsupercm.fabric.citresewn.cit; import net.minecraft.resource.ResourceManager; import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.CITResewn; +import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; @@ -10,9 +11,25 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import java.util.*; +/** + * Instanced parent for CIT Types that are applied to items when conditions pass. + * @see CITTypeContainer + * @see CIT + */ public abstract class CITType { + /** + * Used to determine which property keys are not conditions. + * @return a set of property keys used by this type + */ public abstract Set typeProperties(); + /** + * Loads the given property group into the type. + * @param conditions conditions that were parsed out of the property group + * @param properties group of properties to be read into this type + * @param resourceManager the CIT's containing resource manager + * @throws CITParsingException if errored while parsing the type + */ public abstract void load(List conditions, PropertyGroup properties, ResourceManager resourceManager) throws CITParsingException; protected void warn(String message, PropertyValue value, PropertyGroup properties) { @@ -20,6 +37,12 @@ public abstract class CITType { } /** + * ///// PORTED FROM BETA \\\\\ + * This shit was ported from the + * beta and will be rewritten at + * some point! + * \\\\\ ///// + * * Takes a defined path and resolves it to an identifier pointing to the resourcepack's path of the specified extension(returns null if no path can be resolved).
* If definedPath is null, will try to resolve a relative file with the same name as the rootIdentifier with the extension, otherwise:
* definedPath will be formatted to replace "\\" with "/" the extension will be appended if not there already.
-- cgit From 526a5f1da2354d328be10c4d6d2f58b3b73e0d20 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sun, 6 Mar 2022 17:07:48 +0200 Subject: Documentation (44/44, 0/35) --- .../citresewn/api/CITConditionContainer.java | 24 ++++++++++ .../fabric/citresewn/api/CITDisposable.java | 10 ++++ .../fabric/citresewn/api/CITGlobalProperties.java | 15 ++++++ .../fabric/citresewn/api/CITTypeContainer.java | 47 +++++++++++++++++- .../shsupercm/fabric/citresewn/cit/ActiveCITs.java | 55 ++++++++++++++++++---- .../cit/builtin/conditions/BooleanCondition.java | 13 ++++- .../cit/builtin/conditions/ConstantCondition.java | 6 +++ .../cit/builtin/conditions/DoubleCondition.java | 27 ++++++++++- .../cit/builtin/conditions/EnumCondition.java | 27 ++++++++++- .../cit/builtin/conditions/FloatCondition.java | 27 ++++++++++- .../builtin/conditions/IdentifierCondition.java | 13 ++++- .../cit/builtin/conditions/IntegerCondition.java | 27 ++++++++++- .../cit/builtin/conditions/ListCondition.java | 39 ++++++++++++++- .../cit/builtin/conditions/LongCondition.java | 27 ++++++++++- .../cit/builtin/conditions/WeightCondition.java | 5 ++ 15 files changed, 340 insertions(+), 22 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java index 56ac01f..886185c 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITConditionContainer.java @@ -1,13 +1,37 @@ package shcm.shsupercm.fabric.citresewn.api; import shcm.shsupercm.fabric.citresewn.cit.CITCondition; +import shcm.shsupercm.fabric.citresewn.cit.CITRegistry; import java.util.function.Supplier; +/** + * Wrapper to facilitate metadata, registry and creation of condition class types. + * @see #ENTRYPOINT + * @see CITRegistry + */ public class CITConditionContainer { + /** + * Entrypoint for container singletons, usually kept as a static final field in the condition type's class. + */ public static final String ENTRYPOINT = "citresewn:condition"; + + /** + * Associated condition's class. + */ public final Class condition; + + /** + * Method reference to the condition's constructor or any other supplier of new condition instances. + */ public final Supplier createCondition; + + /** + * Possible names in property groups for the associated condition type.
+ * Condition names are declared in groups with a mod id prefix to avoid conflicts with other 3rd party + * properties(formatted as "modid:alias").
+ * If a modid is not declared, defaults to "citresewn" which is handled by CIT Resewn: Defaults. + */ public final String[] aliases; public CITConditionContainer(Class condition, Supplier createCondition, String... aliases) { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITDisposable.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITDisposable.java index 240f197..dec7098 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITDisposable.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITDisposable.java @@ -1,8 +1,18 @@ package shcm.shsupercm.fabric.citresewn.api; +/** + * @see #dispose() + */ @FunctionalInterface public interface CITDisposable { + /** + * Entrypoint for any disposing method that is not covered by CIT Resewn automatically. + * @see #dispose() + */ String ENTRYPOINT = "citresewn:dispose"; + /** + * Invoked just before reloading CITs. Use to clean up and changes CIT loading made. + */ void dispose(); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java index ada5147..a3d78ae 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java @@ -2,9 +2,24 @@ package shcm.shsupercm.fabric.citresewn.api; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +/** + * @see #globalProperty(String, PropertyValue) + */ @FunctionalInterface public interface CITGlobalProperties { + /** + * Entrypoint for handlers of global properties. + * @see #globalProperty(String, PropertyValue) + */ String ENTRYPOINT = "citresewn:global_property"; + /** + * Invoked before CIT parsing for any global property name associated with the handler's modid.
+ * May be called multiple times for a key to overwrite its global property with higher-priority resourcepacks.
+ * Handlers should take care to reset back any changes global properties make by listening to CIT disposal. + * @see CITDisposable#dispose() + * @param key name of the property key stripped of its modid + * @param value the value it's been set to + */ void globalProperty(String key, PropertyValue value) throws Exception; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java index 5aa727d..b49b4a6 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITTypeContainer.java @@ -3,17 +3,43 @@ package shcm.shsupercm.fabric.citresewn.api; import shcm.shsupercm.fabric.citresewn.cit.ActiveCITs; import shcm.shsupercm.fabric.citresewn.cit.CIT; import shcm.shsupercm.fabric.citresewn.cit.CITType; +import shcm.shsupercm.fabric.citresewn.cit.CITRegistry; import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; import java.util.List; import java.util.function.Supplier; +/** + * Wrapper to facilitate metadata, registry and creation of CIT types. + * @see #ENTRYPOINT + * @see CITRegistry + */ public abstract class CITTypeContainer implements CITDisposable { - public static final String ENTRYPOINT = "citresewn:type"; + /** + * Entrypoint for container singletons, usually kept as a static final field in the type's class. + */ + public static final String ENTRYPOINT = "citresewn:type"; + + /** + * Associated type's class. + */ public final Class type; + + /** + * Method reference to the type's constructor or any other supplier of new CIT type instances. + */ public final Supplier createType; + + /** + * Identifier for this type to be used in the "type=" property.
+ * When used in property groups the type's modid must be added to avoid conflicts with other + * 3rd party types(formatted as "modid:id"). + */ public final String id; + /** + * True when the container should not have any CITs loaded. + */ protected boolean empty = true; public CITTypeContainer(Class type, Supplier createType, String id) { @@ -22,8 +48,16 @@ public abstract class CITTypeContainer implements CITDisposab this.id = id; } + /** + * Loads and keeps a copy of loaded CITs of this container's type. + * @param parsedCITs all loaded CITs of this container's type ordered by weight>path + */ protected abstract void load(List> parsedCITs); + /** + * Loads and keeps a copy of loaded CITs of this container's type. + * @param parsedCITs all loaded CITs of this container's type ordered by weight>path + */ @SuppressWarnings("unchecked") public final void loadUntyped(List parsedCITs) { if (!parsedCITs.isEmpty()) @@ -31,11 +65,22 @@ public abstract class CITTypeContainer implements CITDisposab load((List>) parsedCITs); } + /** + * Unloads CITs from this container.
+ * Override dispose() to add more logic. + * @see CITDisposable#dispose() + */ public final void unload() { dispose(); empty = true; } + /** + * @see #empty + * @see CITResewnConfig#enabled + * @see ActiveCITs#isActive() + * @return whether this container's associated type should work or not + */ public boolean active() { return !empty && CITResewnConfig.INSTANCE.enabled && ActiveCITs.isActive(); } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java index 57d34c3..5270d20 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java @@ -8,34 +8,69 @@ import shcm.shsupercm.fabric.citresewn.api.CITTypeContainer; import shcm.shsupercm.fabric.citresewn.config.CITResewnConfig; import shcm.shsupercm.fabric.citresewn.pack.GlobalProperties; import shcm.shsupercm.fabric.citresewn.pack.PackParser; +import shcm.shsupercm.fabric.citresewn.mixin.ModelLoaderMixin; import java.util.*; -public class ActiveCITs implements CITDisposable { private ActiveCITs() {} +/** + * Holds and manages the currently loaded CITs. + * @see #getActive() + * @see ModelLoaderMixin + */ +public class ActiveCITs { private ActiveCITs() {} + /** + * @see #load(ResourceManager, Profiler) + * @see #getActive() + * @see #isActive() + */ private static ActiveCITs active = null; + /** + * @see #isActive() + * @return the current active CITs manager or null if none are loaded + */ public static ActiveCITs getActive() { return active; } - + + /** + * @see #getActive() + * @return whether there are active; loaded CITs + */ public static boolean isActive() { return active != null; } + /** + * Currently effective global properties merged from all loaded packs. + */ public final GlobalProperties globalProperties = new GlobalProperties(); + /** + * All loaded CITs ordered by their type's class and their weight. + */ public final Map, List>> cits = new IdentityHashMap<>(); - public static ActiveCITs load(ResourceManager resourceManager, Profiler profiler) { + /** + * Attempts to load/activate CITs from packs in the given resource manager, disposing of any previously loaded CITs if present. + * @see ModelLoaderMixin + * @see PackParser#loadGlobalProperties(ResourceManager, GlobalProperties) + * @see GlobalProperties#callHandlers() + * @see PackParser#parseCITs(ResourceManager) + * @param resourceManager manager containing resourcepacks with possible CITs + * @param profiler loading profiler that was pushed once into "citresewn:reloading_cits" and would pop after + */ + public static void load(ResourceManager resourceManager, Profiler profiler) { profiler.push("citresewn:disposing"); + disposeAll(); if (active != null) { - active.dispose(); + //todo send reset calls to global properties with null value active = null; } if (!CITResewnConfig.INSTANCE.enabled) { profiler.pop(); - return null; + return; } ActiveCITs active = new ActiveCITs(); @@ -60,12 +95,14 @@ public class ActiveCITs implements CITDisposable { private ActiveCITs() {} if (!cits.isEmpty()) ActiveCITs.active = active; - - return ActiveCITs.active; } - @Override - public void dispose() { + /** + * Cleans up any registered disposable element. + * @see CITDisposable + * @see CITTypeContainer + */ + public static void disposeAll() { for (CITDisposable disposable : FabricLoader.getInstance().getEntrypoints(CITDisposable.ENTRYPOINT, CITDisposable.class)) disposable.dispose(); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java index 62f1da1..989318f 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/BooleanCondition.java @@ -6,11 +6,22 @@ import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +/** + * Common condition parser for booleans. + */ public abstract class BooleanCondition extends CITCondition { + /** + * Parsed boolean. + */ protected boolean value; + /** + * Converts the given context to a boolean to compare the parsed value to. + * @param context context to retrieve the compared value from + * @return the boolean value associated with the given context + */ protected boolean getValue(CITContext context) { - throw new AssertionError(); + throw new AssertionError("Not implemented by this condition"); } @Override diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ConstantCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ConstantCondition.java index 081c2d8..5bc9354 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ConstantCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ConstantCondition.java @@ -6,7 +6,13 @@ import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +/** + * Common condition type with no parsing for constant true/false testing output. + */ public class ConstantCondition extends CITCondition { + /** + * What testing contexts will always result in. + */ public final boolean value; public ConstantCondition(boolean value) { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java index 0f392d4..44bb906 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/DoubleCondition.java @@ -8,10 +8,23 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import static java.lang.Double.*; +/** + * Common condition parser for doubles with optional support for ranges, negatives and percentages. + */ public abstract class DoubleCondition extends CITCondition { + /** + * Whether this condition should accept given ranges/negatives/percentages. + */ protected final boolean supportsRanges, supportsNegatives, supportsPercentages; + /** + * If ranges are accepted, parsed minimum/maximum double. If not, minimum is the parsed value. + */ protected double min, max; + + /** + * Whether the parsed value is a range/percentage. + */ protected boolean range = false, percentage = false; protected DoubleCondition(boolean supportsRanges, boolean supportsNegatives, boolean supportsPercentages) { @@ -20,12 +33,22 @@ public abstract class DoubleCondition extends CITCondition { this.supportsPercentages = supportsPercentages; } + /** + * Converts the given context to a double to compare the parsed value to. + * @param context context to retrieve the compared value from + * @return the double value associated with the given context + */ protected double getValue(CITContext context) { - throw new AssertionError(); + throw new AssertionError("Not implemented by this condition"); } + /** + * Converts the given context to a max double to be used when percentages are enabled. + * @param context context to retrieve the max value from + * @return the max double value associated with the given context + */ protected double getPercentageTotalValue(CITContext context) { - throw new AssertionError(); + throw new AssertionError("Not implemented by this condition"); } @Override diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java index 56f5fb7..ed69fed 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/EnumCondition.java @@ -8,14 +8,33 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import java.util.function.Supplier; +/** + * Common condition parser for enum values. + * @see EnumCondition.Aliased + */ public abstract class EnumCondition> extends CITCondition { + /** + * Fetches the all of the enum's parsable values. + */ protected final Supplier values; + + /** + * Should letter casing be ignored when parsing the enum value. (default true) + */ protected final boolean ignoreCase; + /** + * Parsed enum value. + */ protected T value; + /** + * Converts the given context to an enum value to compare the parsed value to. + * @param context context to retrieve the compared value from + * @return the enum value associated with the given context + */ protected T getValue(CITContext context) { - throw new AssertionError(); + throw new AssertionError("Not implemented by this condition"); } protected EnumCondition(Supplier values, boolean ignoreCase) { @@ -44,7 +63,13 @@ public abstract class EnumCondition) this).name() }; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java index afc3954..aadaa76 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/FloatCondition.java @@ -8,10 +8,23 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import static java.lang.Float.*; +/** + * Common condition parser for floats with optional support for ranges, negatives and percentages. + */ public abstract class FloatCondition extends CITCondition { + /** + * Whether this condition should accept given ranges/negatives/percentages. + */ protected final boolean supportsRanges, supportsNegatives, supportsPercentages; + /** + * If ranges are accepted, parsed minimum/maximum float. If not, minimum is the parsed value. + */ protected float min, max; + + /** + * Whether the parsed value is a range/percentage. + */ protected boolean range = false, percentage = false; protected FloatCondition(boolean supportsRanges, boolean supportsNegatives, boolean supportsPercentages) { @@ -20,12 +33,22 @@ public abstract class FloatCondition extends CITCondition { this.supportsPercentages = supportsPercentages; } + /** + * Converts the given context to a float to compare the parsed value to. + * @param context context to retrieve the compared value from + * @return the float value associated with the given context + */ protected float getValue(CITContext context) { - throw new AssertionError(); + throw new AssertionError("Not implemented by this condition"); } + /** + * Converts the given context to a max float to be used when percentages are enabled. + * @param context context to retrieve the max value from + * @return the max float value associated with the given context + */ protected float getPercentageTotalValue(CITContext context) { - throw new AssertionError(); + throw new AssertionError("Not implemented by this condition"); } @Override diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java index 0df5330..4d04b76 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IdentifierCondition.java @@ -8,11 +8,22 @@ import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +/** + * Common condition parser for identifiers. + */ public abstract class IdentifierCondition extends CITCondition { + /** + * Parsed identifier. + */ protected Identifier value; + /** + * Converts the given context to an identifier to compare the parsed value to. + * @param context context to retrieve the compared value from + * @return the identifier value associated with the given context + */ protected Identifier getValue(CITContext context) { - throw new AssertionError(); + throw new AssertionError("Not implemented by this condition"); } @Override diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java index 13c87c6..80937f5 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/IntegerCondition.java @@ -8,10 +8,23 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import static java.lang.Integer.*; +/** + * Common condition parser for integers with optional support for ranges, negatives and percentages. + */ public abstract class IntegerCondition extends CITCondition { + /** + * Whether this condition should accept given ranges/negatives/percentages. + */ protected final boolean supportsRanges, supportsNegatives, supportsPercentages; + /** + * If ranges are accepted, parsed minimum/maximum integers. If not, minimum is the parsed value. + */ protected int min, max; + + /** + * Whether the parsed value is a range/percentage. + */ protected boolean range = false, percentage = false; protected IntegerCondition(boolean supportsRanges, boolean supportsNegatives, boolean supportsPercentages) { @@ -20,12 +33,22 @@ public abstract class IntegerCondition extends CITCondition { this.supportsPercentages = supportsPercentages; } + /** + * Converts the given context to an integer to compare the parsed value to. + * @param context context to retrieve the compared value from + * @return the integer value associated with the given context + */ protected int getValue(CITContext context) { - throw new AssertionError(); + throw new AssertionError("Not implemented by this condition"); } + /** + * Converts the given context to a max integer to be used when percentages are enabled. + * @param context context to retrieve the max value from + * @return the max integer value associated with the given context + */ protected int getPercentageTotalValue(CITContext context) { - throw new AssertionError(); + throw new AssertionError("Not implemented by this condition"); } @Override diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java index 3b9a264..e264b27 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/ListCondition.java @@ -12,14 +12,39 @@ import java.util.List; import java.util.function.Supplier; import java.util.regex.Pattern; +/** + * Common condition parser for multiple values separated by any regex expression. + */ public abstract class ListCondition extends CITCondition { - private static final Pattern PATTERN_WHITESPACE = Pattern.compile("\\p{Zs}+"); + /** + * Regex pattern for any amount of whitespace. + */ + public static final Pattern PATTERN_WHITESPACE = Pattern.compile("\\p{Zs}+"); + /** + * Enum class type associated with this condition. + */ private final Class conditionType; + + /** + * Determines how testing the conditions should work(either in OR checks or AND checks). + * @see ListCondition.Type + */ protected final Type listType; + + /** + * Regex pattern to use to separate given input into conditions. + */ protected final Pattern delimiter; + + /** + * Constructor for new parsed conditions. + */ protected final Supplier conditionSupplier; + /** + * Parsed conditions. + */ protected T[] conditions; protected ListCondition(Class conditionType, Type listType, Pattern delimiter, Supplier conditionSupplier) { @@ -52,7 +77,13 @@ public abstract class ListCondition extends CITCondition return listType.test(conditions, context); } + /** + * Provides OR and AND gates for all of the list's conditions. + */ public enum Type { + /** + * Testing passes if any of the conditions pass and fails otherwise. + */ OR { @Override public boolean test(CITCondition[] conditions, CITContext context) { @@ -63,6 +94,9 @@ public abstract class ListCondition extends CITCondition return false; } }, + /** + * Testing passes if all of the conditions pass and fails otherwise. + */ AND { @Override public boolean test(CITCondition[] conditions, CITContext context) { @@ -74,6 +108,9 @@ public abstract class ListCondition extends CITCondition } }; + /** + * Tests the given context against all of the conditions. + */ public abstract boolean test(CITCondition[] conditions, CITContext context); } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/LongCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/LongCondition.java index 97f58b5..da68bd8 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/LongCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/LongCondition.java @@ -8,10 +8,23 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import static java.lang.Long.*; +/** + * Common condition parser for longs with optional support for ranges, negatives and percentages. + */ public abstract class LongCondition extends CITCondition { + /** + * Whether this condition should accept given ranges/negatives/percentages. + */ protected final boolean supportsRanges, supportsNegatives, supportsPercentages; + /** + * If ranges are accepted, parsed minimum/maximum longs. If not, minimum is the parsed value. + */ protected long min, max; + + /** + * Whether the parsed value is a range/percentage. + */ protected boolean range = false, percentage = false; protected LongCondition(boolean supportsRanges, boolean supportsNegatives, boolean supportsPercentages) { @@ -20,12 +33,22 @@ public abstract class LongCondition extends CITCondition { this.supportsPercentages = supportsPercentages; } + /** + * Converts the given context to a long to compare the parsed value to. + * @param context context to retrieve the compared value from + * @return the long value associated with the given context + */ protected long getValue(CITContext context) { - throw new AssertionError(); + throw new AssertionError("Not implemented by this condition"); } + /** + * Converts the given context to a max long to be used when percentages are enabled. + * @param context context to retrieve the max value from + * @return the max llong value associated with the given context + */ protected long getPercentageTotalValue(CITContext context) { - throw new AssertionError(); + throw new AssertionError("Not implemented by this condition"); } @Override diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java index 2e887d6..a53e019 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/builtin/conditions/WeightCondition.java @@ -8,6 +8,11 @@ import shcm.shsupercm.fabric.citresewn.cit.CITContext; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyGroup; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +/** + * Internal condition used to determine the priority CITs get tested in.
+ * Weights default to 0 and higher weights get chosen over lower weights.
+ * When two conflicting CITs have the same weight, their path in the resourcepack is used as a tie breaker. + */ public class WeightCondition extends IntegerCondition { @Entrypoint(CITConditionContainer.ENTRYPOINT) public static final CITConditionContainer CONTAINER = new CITConditionContainer<>(WeightCondition.class, WeightCondition::new, -- cgit From 2356c6bb055079ef03cfd26e9d505ab9cea3960d Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Sun, 6 Mar 2022 17:42:04 +0200 Subject: Modified global properties api a bit --- .../defaults/cit/types/TypeEnchantment.java | 16 ++++++--------- .../fabric/citresewn/api/CITGlobalProperties.java | 9 ++++---- .../shsupercm/fabric/citresewn/cit/ActiveCITs.java | 24 ++++++++-------------- .../fabric/citresewn/pack/GlobalProperties.java | 14 ++++++------- 4 files changed, 27 insertions(+), 36 deletions(-) (limited to 'src/main/java/shcm') diff --git a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java index a59e96c..0bd29e7 100644 --- a/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java +++ b/defaults/src/main/java/shcm/shsupercm/fabric/citresewn/defaults/cit/types/TypeEnchantment.java @@ -23,6 +23,7 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyKey; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import shcm.shsupercm.util.logic.Loops; +import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.*; import java.util.function.Consumer; @@ -152,21 +153,21 @@ public class TypeEnchantment extends CITType { } @Override - public void globalProperty(String key, PropertyValue value) throws Exception { + public void globalProperty(String key, @Nullable PropertyValue value) throws Exception { switch (key) { case "useGlint" -> { - globalUseGlint = Boolean.parseBoolean(value.value()); + globalUseGlint = value == null ? true : Boolean.parseBoolean(value.value()); if (!globalUseGlint && !"false".equalsIgnoreCase(value.value())) throw new Exception("Could not parse boolean"); } case "cap" -> { - globalCap = Integer.parseInt(value.value()); + globalCap = value == null ? Integer.MAX_VALUE : Integer.parseInt(value.value()); } case "method" -> { - globalMergeMethod = MergeMethodIntensity.MergeMethod.parse(value.value()); + globalMergeMethod = value == null ? MergeMethodIntensity.MergeMethod.AVERAGE : MergeMethodIntensity.MergeMethod.parse(value.value()); } case "fade" -> { - globalFade = Float.parseFloat(value.value()); + globalFade = value == null ? 0.5f : Float.parseFloat(value.value()); } } } @@ -182,11 +183,6 @@ public class TypeEnchantment extends CITType { loaded.clear(); loadedLayered.clear(); - - globalUseGlint = true; - globalCap = Integer.MAX_VALUE; - globalMergeMethod = MergeMethodIntensity.MergeMethod.AVERAGE; - globalFade = 0.5f; } public void apply() { diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java index a3d78ae..05495af 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/api/CITGlobalProperties.java @@ -2,6 +2,8 @@ package shcm.shsupercm.fabric.citresewn.api; import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; +import javax.annotation.Nullable; + /** * @see #globalProperty(String, PropertyValue) */ @@ -16,10 +18,9 @@ public interface CITGlobalProperties { /** * Invoked before CIT parsing for any global property name associated with the handler's modid.
* May be called multiple times for a key to overwrite its global property with higher-priority resourcepacks.
- * Handlers should take care to reset back any changes global properties make by listening to CIT disposal. - * @see CITDisposable#dispose() + * When unloading resourcepacks(usually before reloading), all keys that were invoked in the previous load will get called again with a null value to allow for disposal. * @param key name of the property key stripped of its modid - * @param value the value it's been set to + * @param value the value it's been set to or null if resetting */ - void globalProperty(String key, PropertyValue value) throws Exception; + void globalProperty(String key, @Nullable PropertyValue value) throws Exception; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java index 5270d20..82f341f 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/cit/ActiveCITs.java @@ -62,9 +62,16 @@ public class ActiveCITs { private ActiveCITs() {} */ public static void load(ResourceManager resourceManager, Profiler profiler) { profiler.push("citresewn:disposing"); - disposeAll(); + for (CITDisposable disposable : FabricLoader.getInstance().getEntrypoints(CITDisposable.ENTRYPOINT, CITDisposable.class)) + disposable.dispose(); + + for (CITTypeContainer typeContainer : CITRegistry.TYPES.values()) + typeContainer.unload(); + if (active != null) { - //todo send reset calls to global properties with null value + active.globalProperties.properties.replaceAll((key, value) -> Set.of()); + active.globalProperties.callHandlers(); + active = null; } @@ -96,17 +103,4 @@ public class ActiveCITs { private ActiveCITs() {} if (!cits.isEmpty()) ActiveCITs.active = active; } - - /** - * Cleans up any registered disposable element. - * @see CITDisposable - * @see CITTypeContainer - */ - public static void disposeAll() { - for (CITDisposable disposable : FabricLoader.getInstance().getEntrypoints(CITDisposable.ENTRYPOINT, CITDisposable.class)) - disposable.dispose(); - - for (CITTypeContainer typeContainer : CITRegistry.TYPES.values()) - typeContainer.unload(); - } } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java index c16242f..3e93b07 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/GlobalProperties.java @@ -19,6 +19,7 @@ import java.util.Set; /** * Property group representation of the global cit.properties file. + * @see CITGlobalProperties * @see PackParser#loadGlobalProperties(ResourceManager, GlobalProperties) */ public class GlobalProperties extends PropertyGroup { @@ -59,13 +60,12 @@ public class GlobalProperties extends PropertyGroup { for (PropertyValue value : entry.getValue()) lastValue = value; - if (lastValue != null) - try { - container.getEntrypoint().globalProperty(entry.getKey().path(), lastValue); - } catch (Exception e) { - CITResewn.logErrorLoading("Errored while parsing global properties: Line " + lastValue.position() + " of " + lastValue.propertiesIdentifier() + " in " + lastValue.packName()); - e.printStackTrace(); - } + try { + container.getEntrypoint().globalProperty(entry.getKey().path(), lastValue); + } catch (Exception e) { + CITResewn.logErrorLoading(lastValue == null ? "Errored while disposing global properties" : "Errored while parsing global properties: Line " + lastValue.position() + " of " + lastValue.propertiesIdentifier() + " in " + lastValue.packName()); + e.printStackTrace(); + } } } } -- cgit From 884c895ba059286072333dec8dbe5a99b07a27ff Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Wed, 9 Mar 2022 05:18:45 +0200 Subject: Partially fixed quilt fapi support Quilt fabric api will now not support layered mod global properties. A better solution will be looked into eventually. Closes #107 --- src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index adc935a..f27056a 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -49,7 +49,10 @@ public final class PackParser { private PackParser() {} */ public static void forEachPack(ResourceManager resourceManager, Consumer run) { resourceManager.streamResourcePacks().forEachOrdered(pack -> { - List grouped = PARSE_FAPI_GROUPS.apply(pack); + List grouped = null; + try { + grouped = PARSE_FAPI_GROUPS.apply(pack); + } catch (Exception ignored) { } if (grouped != null) for (ResourcePack subPack : grouped) run.accept(subPack); -- cgit From 6470d4bdf3c42b116bee5dd581800e0042fe39d1 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Thu, 10 Mar 2022 17:24:38 +0200 Subject: Fixed different namespaces for global properties Fixes #107 --- .../config/CITResewnMixinConfiguration.java | 4 -- .../citresewn/mixin/GroupResourcePackAccessor.java | 22 ------- .../fabric/citresewn/pack/PackParser.java | 73 +++++++--------------- 3 files changed, 21 insertions(+), 78 deletions(-) delete mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java index 742b929..ca0b149 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java @@ -1,6 +1,5 @@ package shcm.shsupercm.fabric.citresewn.config; -import net.fabricmc.loader.api.FabricLoader; import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; @@ -37,9 +36,6 @@ public class CITResewnMixinConfiguration implements IMixinConfigPlugin { if (mixinClassName.startsWith("broken_paths")) return broken_paths; - if (mixinClassName.equals("GroupResourcePackAccessor")) - return FabricLoader.getInstance().isModLoaded("fabric-resource-loader-v0"); - return true; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java deleted file mode 100644 index 8acd336..0000000 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/GroupResourcePackAccessor.java +++ /dev/null @@ -1,22 +0,0 @@ -package shcm.shsupercm.fabric.citresewn.mixin; - -import net.fabricmc.fabric.impl.resource.loader.GroupResourcePack; -import net.minecraft.resource.ResourcePack; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Pseudo; -import org.spongepowered.asm.mixin.gen.Accessor; -import shcm.shsupercm.fabric.citresewn.pack.PackParser; - -import java.util.List; - -/** - * Access for individual packs in a grouped resourcepack.
- * Used by Fabric API to bundle all mods' resources into a single pack. - * @see PackParser#forEachPack - */ -@Pseudo -@Mixin(value = GroupResourcePack.class, remap = false) -public interface GroupResourcePackAccessor { - @Accessor(remap = false) - List getPacks(); -} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index f27056a..72ed57b 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -1,13 +1,13 @@ package shcm.shsupercm.fabric.citresewn.pack; -import net.fabricmc.fabric.impl.resource.loader.GroupResourcePack; -import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.resource.*; +import net.minecraft.resource.Resource; +import net.minecraft.resource.ResourceManager; +import net.minecraft.resource.ResourcePack; +import net.minecraft.resource.ResourceType; import net.minecraft.util.Identifier; import shcm.shsupercm.fabric.citresewn.CITResewn; import shcm.shsupercm.fabric.citresewn.cit.builtin.conditions.WeightCondition; import shcm.shsupercm.fabric.citresewn.ex.CITParsingException; -import shcm.shsupercm.fabric.citresewn.mixin.GroupResourcePackAccessor; import shcm.shsupercm.fabric.citresewn.cit.CIT; import shcm.shsupercm.fabric.citresewn.cit.CITCondition; import shcm.shsupercm.fabric.citresewn.cit.CITRegistry; @@ -18,49 +18,18 @@ import shcm.shsupercm.fabric.citresewn.pack.format.PropertyValue; import java.io.FileNotFoundException; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Function; +import java.util.*; +import java.util.stream.Collectors; /** * Utility parsing methods for packs. */ public final class PackParser { private PackParser() {} /** - * Possible CIT roots in resourcepacks ordered in ascending order of priority. + * Possible CIT roots in resourcepacks ordered in increasing order of priority. */ private static final String[] ROOTS = new String[] { "mcpatcher", "optifine", "citresewn" }; - /** - * Gets all resourcepacks from {@link GroupResourcePack} or null if not a group or Fabric API is not present. - */ - private static final Function> PARSE_FAPI_GROUPS = - FabricLoader.getInstance().isModLoaded("fabric-resource-loader-v0") ? - parentPack -> parentPack instanceof GroupResourcePack ? ((GroupResourcePackAccessor) parentPack).getPacks() : null - : parentPack -> null; - - /** - * Iterates over each loaded pack taking into account grouped packs. - * @param resourceManager the manager that contains the packs - * @param run resourcepack pack consumer - */ - public static void forEachPack(ResourceManager resourceManager, Consumer run) { - resourceManager.streamResourcePacks().forEachOrdered(pack -> { - List grouped = null; - try { - grouped = PARSE_FAPI_GROUPS.apply(pack); - } catch (Exception ignored) { } - if (grouped != null) - for (ResourcePack subPack : grouped) - run.accept(subPack); - else - run.accept(pack); - }); - } - /** * Loads a merged global property group from loaded packs making sure to respect order. * @@ -70,21 +39,21 @@ public final class PackParser { private PackParser() {} * @return globalProperties */ public static GlobalProperties loadGlobalProperties(ResourceManager resourceManager, GlobalProperties globalProperties) { - forEachPack(resourceManager, pack -> { - for (String root : ROOTS) { - Identifier identifier = new Identifier("minecraft", root + "/cit.properties"); - try { - globalProperties.load(pack.getName(), identifier, pack.open(ResourceType.CLIENT_RESOURCES, identifier)); - } catch (FileNotFoundException ignored) { - } catch (IOException e) { - // fixes log spam from Lambda Better Grass - if (pack.getClass().getSimpleName().equals("LBGResourcePack")) continue; - - CITResewn.logErrorLoading("Errored while loading global properties: " + identifier + " from " + pack.getName()); - e.printStackTrace(); + for (ResourcePack pack : resourceManager.streamResourcePacks().collect(Collectors.toList())) + for (String namespace : pack.getNamespaces(ResourceType.CLIENT_RESOURCES)) + for (String root : ROOTS) { + Identifier identifier = new Identifier(namespace, root + "/cit.properties"); + try { + globalProperties.load(pack.getName(), identifier, pack.open(ResourceType.CLIENT_RESOURCES, identifier)); + } catch (FileNotFoundException ignored) { + } catch (IOException e) { + // fixes log spam from Lambda Better Grass todo move to a compat mixin + if (pack.getClass().getSimpleName().equals("LBGResourcePack")) continue; + + CITResewn.logErrorLoading("Errored while loading global properties: " + identifier + " from " + pack.getName()); + e.printStackTrace(); + } } - } - }); return globalProperties; } -- cgit From c33015c87439e563ee953a57765bb7fa639c3b5f Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Thu, 17 Mar 2022 05:36:11 +0200 Subject: Set up compat mixin system and moved lbg compat --- .../config/CITResewnMixinConfiguration.java | 17 ++++++++++++++ .../compat/lambdabettergrass/PackParserMixin.java | 26 ++++++++++++++++++++++ .../fabric/citresewn/pack/PackParser.java | 3 --- 3 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 src/main/java/shcm/shsupercm/fabric/citresewn/mixin/compat/lambdabettergrass/PackParserMixin.java (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java index ca0b149..bfabb8f 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java @@ -1,9 +1,12 @@ package shcm.shsupercm.fabric.citresewn.config; +import net.fabricmc.loader.api.FabricLoader; import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import shcm.shsupercm.fabric.citresewn.CITResewn; +import java.util.HashSet; import java.util.List; import java.util.Set; @@ -20,6 +23,11 @@ public class CITResewnMixinConfiguration implements IMixinConfigPlugin { */ private boolean broken_paths; + /** + * Set of mod ids that had compatibility mixins loaded for them. + */ + private Set compatMods = new HashSet<>(); + @Override public void onLoad(String mixinPackage) { CITResewnConfig launchConfig = CITResewnConfig.read(); @@ -36,6 +44,15 @@ public class CITResewnMixinConfiguration implements IMixinConfigPlugin { if (mixinClassName.startsWith("broken_paths")) return broken_paths; + if (mixinClassName.startsWith("compat.")) { + mixinClassName = mixinClassName.substring(7); + String modid = mixinClassName.substring(0, mixinClassName.indexOf('.')); + boolean loaded = FabricLoader.getInstance().isModLoaded(modid); + if (loaded && compatMods.add(modid)) + CITResewn.info("Loading compatibility for " + modid); + return loaded; + } + return true; } diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/compat/lambdabettergrass/PackParserMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/compat/lambdabettergrass/PackParserMixin.java new file mode 100644 index 0000000..2e43143 --- /dev/null +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/compat/lambdabettergrass/PackParserMixin.java @@ -0,0 +1,26 @@ +package shcm.shsupercm.fabric.citresewn.mixin.compat.lambdabettergrass; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import shcm.shsupercm.fabric.citresewn.pack.PackParser; + +import java.io.IOException; + +@SuppressWarnings("UnresolvedMixinReference") +@Mixin(PackParser.class) +public class PackParserMixin { + @ModifyVariable(method = "loadGlobalProperties(Lnet/minecraft/resource/ResourceManager;Lshcm/shsupercm/fabric/citresewn/pack/GlobalProperties;)Lshcm/shsupercm/fabric/citresewn/pack/GlobalProperties;", at = + @At(value = "INVOKE", target = "shcm/shsupercm/fabric/citresewn/CITResewn.logErrorLoading(Ljava/lang/String;)V")) + private static IOException citresewn$compat$lambdabettergrass$muteStacktrace(IOException exception) { + if (exception.getMessage().contains("lambdabettergrass")) + return new IOException() { + @Override + public void printStackTrace() { + //no + } + }; + + return exception; + } +} diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java index 72ed57b..9f57760 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/pack/PackParser.java @@ -47,9 +47,6 @@ public final class PackParser { private PackParser() {} globalProperties.load(pack.getName(), identifier, pack.open(ResourceType.CLIENT_RESOURCES, identifier)); } catch (FileNotFoundException ignored) { } catch (IOException e) { - // fixes log spam from Lambda Better Grass todo move to a compat mixin - if (pack.getClass().getSimpleName().equals("LBGResourcePack")) continue; - CITResewn.logErrorLoading("Errored while loading global properties: " + identifier + " from " + pack.getName()); e.printStackTrace(); } -- cgit From db592ed372f22e71206a6debab11389898c69f01 Mon Sep 17 00:00:00 2001 From: SHsuperCM Date: Thu, 17 Mar 2022 15:49:35 +0200 Subject: Minor cleanups --- .../shsupercm/fabric/citresewn/CITResewnCommand.java | 4 ++-- .../citresewn/config/CITResewnMixinConfiguration.java | 19 +++++++++++++------ .../compat/lambdabettergrass/PackParserMixin.java | 2 +- 3 files changed, 16 insertions(+), 9 deletions(-) (limited to 'src/main/java/shcm') diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java index 6583cd8..e07a772 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/CITResewnCommand.java @@ -40,9 +40,9 @@ public class CITResewnCommand { public static boolean openConfig = false; /** - * Registers + * Registers all of CIT Resewn's commands. */ - static void register() { + public static void register() { ClientCommandManager.DISPATCHER.register(literal("citresewn") .executes(context -> { //citresewn context.getSource().sendFeedback(of("CIT Resewn v" + FabricLoader.getInstance().getModContainer("citresewn").orElseThrow().getMetadata().getVersion() + ":")); diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java index bfabb8f..6e4d2ce 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/config/CITResewnMixinConfiguration.java @@ -1,6 +1,7 @@ package shcm.shsupercm.fabric.citresewn.config; import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; @@ -24,15 +25,18 @@ public class CITResewnMixinConfiguration implements IMixinConfigPlugin { private boolean broken_paths; /** - * Set of mod ids that had compatibility mixins loaded for them. + * Slightly modified mod ids for loaded mods and mods with compat mixins. */ - private Set compatMods = new HashSet<>(); + private final Set mods = new HashSet<>(), compatMods = new HashSet<>(); @Override public void onLoad(String mixinPackage) { CITResewnConfig launchConfig = CITResewnConfig.read(); this.broken_paths = launchConfig.broken_paths; + + for (ModContainer mod : FabricLoader.getInstance().getAllMods()) + mods.add(mod.getMetadata().getId().replace('-', '_')); } @Override @@ -47,10 +51,13 @@ public class CITResewnMixinConfiguration implements IMixinConfigPlugin { if (mixinClassName.startsWith("compat.")) { mixinClassName = mixinClassName.substring(7); String modid = mixinClassName.substring(0, mixinClassName.indexOf('.')); - boolean loaded = FabricLoader.getInstance().isModLoaded(modid); - if (loaded && compatMods.add(modid)) - CITResewn.info("Loading compatibility for " + modid); - return loaded; + if (mods.contains(modid)) { + if (compatMods.add(modid)) + CITResewn.info("Loading compatibility for " + modid); + + return true; + } + return false; } return true; diff --git a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/compat/lambdabettergrass/PackParserMixin.java b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/compat/lambdabettergrass/PackParserMixin.java index 2e43143..69e432c 100644 --- a/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/compat/lambdabettergrass/PackParserMixin.java +++ b/src/main/java/shcm/shsupercm/fabric/citresewn/mixin/compat/lambdabettergrass/PackParserMixin.java @@ -8,7 +8,7 @@ import shcm.shsupercm.fabric.citresewn.pack.PackParser; import java.io.IOException; @SuppressWarnings("UnresolvedMixinReference") -@Mixin(PackParser.class) +@Mixin(value = PackParser.class, remap = false) public class PackParserMixin { @ModifyVariable(method = "loadGlobalProperties(Lnet/minecraft/resource/ResourceManager;Lshcm/shsupercm/fabric/citresewn/pack/GlobalProperties;)Lshcm/shsupercm/fabric/citresewn/pack/GlobalProperties;", at = @At(value = "INVOKE", target = "shcm/shsupercm/fabric/citresewn/CITResewn.logErrorLoading(Ljava/lang/String;)V")) -- cgit