From f19289ada50383e2da83ac4220027ece102e4654 Mon Sep 17 00:00:00 2001 From: Motschen Date: Mon, 1 Mar 2021 20:17:22 +0100 Subject: [PATCH] Cull Leaves 2.1.0 - MidnightConfig Use MidnightConfig instead of AutoConfig/ClothConfig, decreasing file size substantually and increasing compatiblility Also fix #6 :) --- build.gradle | 8 - gradle.properties | 12 +- .../cullleaves/CullLeavesClient.java | 6 +- .../cullleaves/config/CullLeavesConfig.java | 13 +- .../cullleaves/config/MidnightConfig.java | 288 ++++++++++++++++++ .../cullleaves/config/ModMenuIntegration.java | 3 +- .../cullleaves/mixin/MixinLeavesBlock.java | 4 +- .../assets/cullleaves/lang/en_us.json | 6 +- .../assets/minecraft/models/block/leaves.json | 24 +- 9 files changed, 315 insertions(+), 49 deletions(-) create mode 100644 src/main/java/eu/midnightdust/cullleaves/config/MidnightConfig.java diff --git a/build.gradle b/build.gradle index c0e4cd7..8912264 100644 --- a/build.gradle +++ b/build.gradle @@ -25,17 +25,9 @@ dependencies { modCompile "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" - modImplementation ("me.sargunvohra.mcmods:autoconfig1u:${project.auto_config_version}"){ - exclude module: "fabric-api" - } - modImplementation ("me.shedaniel.cloth:config-2:${project.cloth_config_version}"){ - exclude module: "fabric-api" - } modImplementation ("io.github.prospector:modmenu:${project.mod_menu_version}"){ exclude module: "fabric-api" } - include "me.sargunvohra.mcmods:autoconfig1u:${project.auto_config_version}" - include "me.shedaniel.cloth:config-2:${project.cloth_config_version}" } processResources { diff --git a/gradle.properties b/gradle.properties index 0d48300..08ab733 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,19 +3,17 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check these on https://fabricmc.net/use - minecraft_version=1.16.4 - yarn_mappings=1.16.4+build.7 - loader_version=0.10.8 + minecraft_version=1.16.5 + yarn_mappings=1.16.5+build.5 + loader_version=0.11.2 # Mod Properties - mod_version = 2.0.0 + mod_version = 2.1.0 maven_group = eu.midnightdust archives_base_name = cullleaves # Dependencies # currently not on the main fabric site, check on the maven: https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api - fabric_version=0.26.1+1.16 + fabric_version=0.31.0+1.16 - auto_config_version = 3.3.1 - cloth_config_version = 4.8.3 mod_menu_version = 1.14.6+build.31 \ No newline at end of file diff --git a/src/main/java/eu/midnightdust/cullleaves/CullLeavesClient.java b/src/main/java/eu/midnightdust/cullleaves/CullLeavesClient.java index 6fc7979..763d087 100644 --- a/src/main/java/eu/midnightdust/cullleaves/CullLeavesClient.java +++ b/src/main/java/eu/midnightdust/cullleaves/CullLeavesClient.java @@ -1,19 +1,15 @@ package eu.midnightdust.cullleaves; import eu.midnightdust.cullleaves.config.CullLeavesConfig; -import me.sargunvohra.mcmods.autoconfig1u.AutoConfig; -import me.sargunvohra.mcmods.autoconfig1u.serializer.JanksonConfigSerializer; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.resource.ResourceManagerHelper; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; public class CullLeavesClient implements ClientModInitializer { - public static CullLeavesConfig CL_CONFIG; public void onInitializeClient() { - AutoConfig.register(CullLeavesConfig.class, JanksonConfigSerializer::new); - CL_CONFIG = AutoConfig.getConfigHolder(CullLeavesConfig.class).getConfig(); + CullLeavesConfig.init("cullleaves", CullLeavesConfig.class); FabricLoader.getInstance().getModContainer("cullleaves").ifPresent(modContainer -> { ResourceManagerHelper.registerBuiltinResourcePack(new Identifier("cullleaves:smartleaves"), "resourcepacks/smartleaves", modContainer, true); diff --git a/src/main/java/eu/midnightdust/cullleaves/config/CullLeavesConfig.java b/src/main/java/eu/midnightdust/cullleaves/config/CullLeavesConfig.java index a0db0d4..874be45 100644 --- a/src/main/java/eu/midnightdust/cullleaves/config/CullLeavesConfig.java +++ b/src/main/java/eu/midnightdust/cullleaves/config/CullLeavesConfig.java @@ -1,14 +1,7 @@ package eu.midnightdust.cullleaves.config; -import me.sargunvohra.mcmods.autoconfig1u.ConfigData; -import me.sargunvohra.mcmods.autoconfig1u.annotation.Config; -import me.sargunvohra.mcmods.autoconfig1u.annotation.ConfigEntry; -import me.sargunvohra.mcmods.autoconfig1u.shadowed.blue.endless.jankson.Comment; -import net.minecraft.client.render.entity.PlayerModelPart; +public class CullLeavesConfig extends MidnightConfig { -@Config(name = "cullleaves") -public class CullLeavesConfig implements ConfigData { - - @ConfigEntry.Gui.PrefixText // Enable/Disable the mod. Requires Chunk Reload (F3 + A). - public boolean enabled = true; + @Entry // Enable/Disable the mod. Requires Chunk Reload (F3 + A). + public static boolean enabled = true; } diff --git a/src/main/java/eu/midnightdust/cullleaves/config/MidnightConfig.java b/src/main/java/eu/midnightdust/cullleaves/config/MidnightConfig.java new file mode 100644 index 0000000..41bd2d3 --- /dev/null +++ b/src/main/java/eu/midnightdust/cullleaves/config/MidnightConfig.java @@ -0,0 +1,288 @@ +package eu.midnightdust.cullleaves.config; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.screen.ScreenTexts; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.client.gui.widget.TextFieldWidget; +import net.minecraft.client.resource.language.I18n; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.text.*; +import net.minecraft.util.Formatting; + +import java.lang.annotation.*; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.*; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.regex.Pattern; + +// MidnightConfig v0.1.0 // + +/* Based on https://github.com/Minenash/TinyConfig + Credits to Minenash - CC0-1.0 + You can copy this class to get a standalone version of MidnightConfig */ + +@SuppressWarnings("rawtypes") +public class MidnightConfig { + + private static final Pattern INTEGER_ONLY = Pattern.compile("(-?[0-9]*)"); + private static final Pattern DECIMAL_ONLY = Pattern.compile("-?([\\d]+\\.?[\\d]*|[\\d]*\\.?[\\d]+|\\.)"); + + private static final List entries = new ArrayList<>(); + + protected static class EntryInfo { + Field field; + Object widget; + int width; + Method dynamicTooltip; + Map.Entry error; + Object defaultValue; + Object value; + String tempValue; + boolean inLimits = true; + } + + private static Class configClass; + private static String translationPrefix; + private static Path path; + + private static final Gson gson = new GsonBuilder() + .excludeFieldsWithModifiers(Modifier.TRANSIENT) + .excludeFieldsWithModifiers(Modifier.PRIVATE) + .setPrettyPrinting() + .create(); + + public static void init(String modid, Class config) { + translationPrefix = modid + ".midnightconfig."; + path = FabricLoader.getInstance().getConfigDir().resolve(modid + ".json"); + configClass = config; + + for (Field field : config.getFields()) { + Class type = field.getType(); + EntryInfo info = new EntryInfo(); + + Entry e; + try { e = field.getAnnotation(Entry.class); } + catch (Exception ignored) { continue; } + + info.width = e.width(); + info.field = field; + + if (type == int.class) textField(info, Integer::parseInt, INTEGER_ONLY, e.min(), e.max(), true); + else if (type == double.class) textField(info, Double::parseDouble, DECIMAL_ONLY, e.min(), e.max(),false); + else if (type == String.class) textField(info, String::length, null, Math.min(e.min(),0), Math.max(e.max(),1),true); + else if (type == boolean.class) { + Function func = value -> new LiteralText((Boolean) value ? "True" : "False").formatted((Boolean) value ? Formatting.GREEN : Formatting.RED); + info.widget = new AbstractMap.SimpleEntry>(button -> { + info.value = !(Boolean) info.value; + button.setMessage(func.apply(info.value)); + }, func); + } + else if (type.isEnum()) { + List values = Arrays.asList(field.getType().getEnumConstants()); + Function func = value -> new TranslatableText(translationPrefix + "enum." + type.getSimpleName() + "." + info.value.toString()); + info.widget = new AbstractMap.SimpleEntry>( button -> { + int index = values.indexOf(info.value) + 1; + info.value = values.get(index >= values.size()? 0 : index); + button.setMessage(func.apply(info.value)); + }, func); + } + else + continue; + + entries.add(info); + + try { info.defaultValue = field.get(null); } + catch (IllegalAccessException ignored) {} + + try { + info.dynamicTooltip = config.getMethod(e.dynamicTooltip()); + info.dynamicTooltip.setAccessible(true); + } catch (Exception ignored) {} + + } + + try { gson.fromJson(Files.newBufferedReader(path), config); } + catch (Exception e) { write(); } + + for (EntryInfo info : entries) { + try { + info.value = info.field.get(null); + info.tempValue = info.value.toString(); + } + catch (IllegalAccessException ignored) {} + } + + } + + private static void textField(EntryInfo info, Function f, Pattern pattern, double min, double max, boolean cast) { + boolean isNumber = pattern != null; + info.widget = (BiFunction>) (t, b) -> s -> { + s = s.trim(); + if (!(s.isEmpty() || !isNumber || pattern.matcher(s).matches())) + return false; + + Number value = 0; + boolean inLimits = false; + System.out.println(((isNumber ^ s.isEmpty()))); + System.out.println(!s.equals("-") && !s.equals(".")); + info.error = null; + if (!(isNumber && s.isEmpty()) && !s.equals("-") && !s.equals(".")) { + value = f.apply(s); + inLimits = value.doubleValue() >= min && value.doubleValue() <= max; + info.error = inLimits? null : new AbstractMap.SimpleEntry<>(t, new LiteralText(value.doubleValue() < min ? + "§cMinimum " + (isNumber? "value" : "length") + (cast? " is " + (int)min : " is " + min) : + "§cMaximum " + (isNumber? "value" : "length") + (cast? " is " + (int)max : " is " + max))); + } + + info.tempValue = s; + t.setEditableColor(inLimits? 0xFFFFFFFF : 0xFFFF7777); + info.inLimits = inLimits; + b.active = entries.stream().allMatch(e -> e.inLimits); + + if (inLimits) + info.value = isNumber? value : s; + + return true; + }; + } + + public static void write() { + try { + if (!Files.exists(path)) Files.createFile(path); + Files.write(path, gson.toJson(configClass.newInstance()).getBytes()); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + public Screen getScreen(Screen parent) { + return new TinyConfigScreen(parent); + } + + private static class TinyConfigScreen extends Screen { + protected TinyConfigScreen(Screen parent) { + super(new TranslatableText(MidnightConfig.translationPrefix + "title")); + this.parent = parent; + } + private final Screen parent; + + // Real Time config update // + @Override + public void tick() { + for (EntryInfo info : entries) + try { info.field.set(null, info.value); } + catch (IllegalAccessException ignore) {} + } + + @Override + protected void init() { + super.init(); + this.addButton(new ButtonWidget(this.width / 2 - 154, this.height - 28, 150, 20, ScreenTexts.CANCEL, button -> { + try { gson.fromJson(Files.newBufferedReader(path), configClass); } + catch (Exception e) { write(); } + + for (EntryInfo info : entries) { + try { + info.value = info.field.get(null); + info.tempValue = info.value.toString(); + } + catch (IllegalAccessException ignored) {} + } + Objects.requireNonNull(client).openScreen(parent); + })); + + ButtonWidget done = this.addButton(new ButtonWidget(this.width / 2 + 4, this.height - 28, 150, 20, ScreenTexts.DONE, (button) -> { + for (EntryInfo info : entries) + try { info.field.set(null, info.value); } + catch (IllegalAccessException ignore) {} + write(); + Objects.requireNonNull(client).openScreen(parent); + })); + + int y = 45; + for (EntryInfo info : entries) { + addButton(new ButtonWidget(width - 155, y, 40,20, new LiteralText("Reset").formatted(Formatting.RED), (button -> { + info.value = info.defaultValue; + info.tempValue = info.value.toString(); + Objects.requireNonNull(client).openScreen(this); + }))); + + if (info.widget instanceof Map.Entry) { + Map.Entry> widget = (Map.Entry>) info.widget; + addButton(new ButtonWidget(width-110,y,info.width,20, widget.getValue().apply(info.value), widget.getKey())); + } + else { + TextFieldWidget widget = addButton(new TextFieldWidget(textRenderer, width-110, y, info.width, 20, null)); + widget.setText(info.tempValue); + + Predicate processor = ((BiFunction>) info.widget).apply(widget,done); + widget.setTextPredicate(processor); + + children.add(widget); + } + y += 25; + } + + } + int aniX = this.width / 2; + @Override + public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) { + this.renderBackground(matrices); + + if (aniX < this.width / 2) { + aniX = aniX +40; + } + + int stringWidth = (int) (title.getString().length() * 2.75f); + this.fillGradient(matrices, this.width / 2 - stringWidth, 10, this.width /2 + stringWidth, 29, -1072689136, -804253680); + this.fillGradient(matrices, this.width / 2 - aniX, 35, width/2 + aniX, this.height - 40, -1072689136, -804253680); + + super.render(matrices, mouseX, mouseY, delta); + drawCenteredText(matrices, textRenderer, title, width/2, 15, 0xFFFFFF); + + int y = 40; + for (EntryInfo info : entries) { + drawTextWithShadow(matrices, textRenderer, new TranslatableText(translationPrefix + info.field.getName()), 12, y + 10, 0xFFFFFF); + + if (info.error != null && info.error.getKey().isMouseOver(mouseX,mouseY)) + renderTooltip(matrices, info.error.getValue(), mouseX, mouseY); + else if (mouseY >= y && mouseY < (y + 25)) { + if (info.dynamicTooltip != null) { + try { + renderTooltip(matrices, (List) info.dynamicTooltip.invoke(null, entries), mouseX, mouseY); + y += 25; + continue; + } catch (Exception e) { e.printStackTrace(); } + } + String key = translationPrefix + info.field.getName() + ".tooltip"; + if (I18n.hasTranslation(key)) { + List list = new ArrayList<>(); + for (String str : I18n.translate(key).split("\n")) + list.add(new LiteralText(str)); + renderTooltip(matrices, list, mouseX, mouseY); + } + } + y += 25; + } + } + } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + public @interface Entry { + String dynamicTooltip() default ""; + int width() default 100; + double min() default Double.MIN_NORMAL; + double max() default Double.MAX_VALUE; + } +} \ No newline at end of file diff --git a/src/main/java/eu/midnightdust/cullleaves/config/ModMenuIntegration.java b/src/main/java/eu/midnightdust/cullleaves/config/ModMenuIntegration.java index 5742114..3146d86 100644 --- a/src/main/java/eu/midnightdust/cullleaves/config/ModMenuIntegration.java +++ b/src/main/java/eu/midnightdust/cullleaves/config/ModMenuIntegration.java @@ -2,7 +2,6 @@ import io.github.prospector.modmenu.api.ConfigScreenFactory; import io.github.prospector.modmenu.api.ModMenuApi; -import me.sargunvohra.mcmods.autoconfig1u.AutoConfig; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @@ -11,6 +10,6 @@ public class ModMenuIntegration implements ModMenuApi { @Override public ConfigScreenFactory getModConfigScreenFactory() { - return parent -> AutoConfig.getConfigScreen(CullLeavesConfig.class, parent).get(); + return parent -> new CullLeavesConfig().getScreen(parent); } } \ No newline at end of file diff --git a/src/main/java/eu/midnightdust/cullleaves/mixin/MixinLeavesBlock.java b/src/main/java/eu/midnightdust/cullleaves/mixin/MixinLeavesBlock.java index fd53cb8..fe06a2f 100644 --- a/src/main/java/eu/midnightdust/cullleaves/mixin/MixinLeavesBlock.java +++ b/src/main/java/eu/midnightdust/cullleaves/mixin/MixinLeavesBlock.java @@ -1,6 +1,6 @@ package eu.midnightdust.cullleaves.mixin; -import eu.midnightdust.cullleaves.CullLeavesClient; +import eu.midnightdust.cullleaves.config.CullLeavesConfig; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.block.Block; @@ -20,7 +20,7 @@ public MixinLeavesBlock(Settings settings) { @Override @SuppressWarnings("deprecation") public boolean isSideInvisible(BlockState state, BlockState neighborState, Direction offset) { - if (CullLeavesClient.CL_CONFIG.enabled) { + if (CullLeavesConfig.enabled) { return neighborState.getBlock() instanceof LeavesBlock; } else return false; diff --git a/src/main/resources/assets/cullleaves/lang/en_us.json b/src/main/resources/assets/cullleaves/lang/en_us.json index eac7e9b..1c29f84 100644 --- a/src/main/resources/assets/cullleaves/lang/en_us.json +++ b/src/main/resources/assets/cullleaves/lang/en_us.json @@ -1,5 +1,5 @@ { - "text.autoconfig.cullleaves.title":"Cull Leaves Config", - "text.autoconfig.cullleaves.option.enabled.@PrefixText":"After changing this setting you have to reload all chunks (F3 + A)", - "text.autoconfig.cullleaves.option.enabled":"Enabled" + "cullleaves.midnightconfig.title":"Cull Leaves Config", + "cullleaves.midnightconfig.enabled.tooltip":"After changing this setting you have to reload all chunks (F3 + A)", + "cullleaves.midnightconfig.enabled":"Enabled" } \ No newline at end of file diff --git a/src/main/resources/resourcepacks/smartleaves/assets/minecraft/models/block/leaves.json b/src/main/resources/resourcepacks/smartleaves/assets/minecraft/models/block/leaves.json index aa7c3f9..bff56c6 100644 --- a/src/main/resources/resourcepacks/smartleaves/assets/minecraft/models/block/leaves.json +++ b/src/main/resources/resourcepacks/smartleaves/assets/minecraft/models/block/leaves.json @@ -20,32 +20,32 @@ }, { "name": "bottom", - "from": [0, 0, 0], - "to": [16, 0, 16], + "from": [0, 0.01, 0], + "to": [16, 0.01, 16], "faces": { "up": {"uv": [0, 0, 16, 16], "texture": "#all", "cullface": "down", "tintindex": 0} } }, { "name": "west", - "from": [0, 0, 0], - "to": [0, 16, 16], + "from": [0.01, 0, 0], + "to": [0.01, 16, 16], "faces": { "east": {"uv": [0, 0, 16, 16], "texture": "#all", "cullface": "west", "tintindex": 0} } }, { "name": "north", - "from": [0, 0, 0], - "to": [16, 16, 0], + "from": [0, 0, 0.01], + "to": [16, 16, 0.01], "faces": { "south": {"uv": [0, 0, 16, 16], "texture": "#all", "cullface": "north", "tintindex": 0} } }, { "name": "east", - "from": [16, 0, 0], - "to": [16, 16, 16], + "from": [15.99, 0, 0], + "to": [15.99, 16, 16], "rotation": {"angle": 0, "axis": "y", "origin": [23, 8, 8]}, "faces": { "west": {"uv": [0, 0, 16, 16], "texture": "#all", "cullface": "east", "tintindex": 0} @@ -53,8 +53,8 @@ }, { "name": "south", - "from": [0, 0, 16], - "to": [16, 16, 16], + "from": [0, 0, 15.99], + "to": [16, 16, 15.99], "rotation": {"angle": 0, "axis": "y", "origin": [8, 8, 23]}, "faces": { "north": {"uv": [0, 0, 16, 16], "texture": "#all", "cullface": "south", "tintindex": 0} @@ -62,8 +62,8 @@ }, { "name": "up", - "from": [0, 16, 0], - "to": [16, 16, 16], + "from": [0, 15.99, 0], + "to": [16, 15.99, 16], "rotation": {"angle": 0, "axis": "y", "origin": [8, 23, 8]}, "faces": { "down": {"uv": [0, 0, 16, 16], "texture": "#all", "cullface": "up", "tintindex": 0}