Compare commits

...
22 Commits
Author SHA1 Message Date
frqnny 3b91570a8c 1.21 update 2024-06-17 17:16:47 -04:00
frqnny de04d5a2cf minor toolchain changes 2024-06-17 16:45:00 -04:00
frqnny f9b19cff35 bump version 2024-06-17 16:30:50 -04:00
frqnny 89132f1e54 fix jitpack.yml 2024-06-17 16:29:05 -04:00
frqnny 08824ba045 1.20.6 update 2024-06-17 16:15:07 -04:00
frqnny 8b2f1db5e9 let's see if this fixes things? 2024-06-17 14:19:40 -04:00
Draylar 5f19348fdc 1.20.1 update without Omega Config GUI 2023-07-01 16:30:59 -05:00
Draylar 505d3e70f8 1.19.2 update with maven publishing and README polishing 2023-03-01 21:16:38 -06:00
DraylarandGitHub 239ec7c3bc 1.2.3 version bump 2022-01-18 11:14:38 -06:00
DraylarandGitHub 0f0abe558e Merge pull request #12 from Luligabi1/1.18
Better config screen title
2022-01-18 11:14:04 -06:00
Luligabi1 5bdce25e29 OmegaConfigGui's generated config screen now has a TranslatableText for its title rather than a LiteralText.q 2021-12-28 15:07:41 -03:00
frqnny 9d7aa7581d Automated fabric mod json version
Closes #11
2021-12-28 10:58:42 -05:00
Draylar 8611edb92c update README 2021-12-20 18:38:58 -06:00
Draylar 58c420d35f add null check for modid when registering modmenu screens 2021-12-20 17:52:54 -06:00
Draylar 270db37dba fix omega config class loading too early in static block, make modmenu dep transitive 2021-12-20 17:41:14 -06:00
Draylar 2968111445 Move ModMenu dependency to the GUI module 2021-12-20 17:20:50 -06:00
Draylar 136cfe6a9a fix classloading for mod menu by moving registration methods to OmegaConfigGui class, fix versioning 2021-12-20 17:16:02 -06:00
Draylar 3f7c461689 Add mod icons, finish GUI support through Cloth Config Lite 2021-12-20 16:40:03 -06:00
Draylar 36ce7bc924 🦀 proguard is dead, clean up build.gradle 2021-12-20 15:23:52 -06:00
DraylarandGitHub a3cde2c8e7 JDK17 for JitPack.yml on 1.18 2021-12-13 20:39:14 -06:00
DraylarandGitHub 6fa8e58665 Merge pull request #7 from Luligabi1/1.17
Updates to 1.18.1
2021-12-13 20:37:46 -06:00
Luligabi1 ed4e9f6c19 Updates to 1.18.1 2021-12-11 15:09:18 -03:00
32 changed files with 199 additions and 753 deletions
+72 -5
View File
@@ -1,15 +1,15 @@
# ΩConfig
<h1 align="center">Omega Config Ω </h1>
<p align="center">A configuration library by <a href="https://github.com/Draylar">Draylar</a></p>
---
*The last config library you will ever use.*
ΩConfig is a hyper-minimal config library based on [Auto Config](https://github.com/shedaniel/AutoConfig). It aims to
achieve the following goals:
- Be lightweight (<10 KB) for JIJ usage
- Be lightweight (<25 KB) for JIJ usage
- Exceedingly simple design & API for developers
- Intuition and usability for players
- Bonus annotations for advanced config options (syncing values)
The following is an example of a simple ΩConfig setup:
@@ -19,6 +19,10 @@ public class TestConfig implements Config {
@Comment(value = "Hello!")
boolean value = false;
@Syncing
@Comment(value = "This value will sync to the client!")
boolean syncableValue = false;
@Override
public String getFileName() {
return "test-config";
@@ -39,6 +43,66 @@ public class MyModInitializer {
}
```
Looking for a simple config screen? Talk about easy!
```java
public class ClientInitializer implements ClientModInitializer {
@Override
public void onInitializeClient() {
// Make sure you implement getModid in your config class!
OmegaConfigGui.registerConfigScreen(MainInitializer.CONFIG);
}
}
```
---
### Pulling Omega Config into Development
To use Omega Config, you will have to add it to your build.gradle file.
What you pull in depends on whether you want GUI functionality. For basic config files using the base module (~20KB),
you can use the following gradle declarations:
```groovy
repositories {
maven { url 'https://maven.draylar.dev/releases' }
}
// 1.19.2 version: 1.3.0+1.19.2
dependencies {
modImplementation include("dev.draylar.omega-config:omega-config-base:${project.omega_config_version}")
}
```
Easy - you now have a bundled configuration library. Use the examples in the first section to implement your config.
If you want to add GUI functionality (most likely Mod Menu support), you can pull in the GUI module (~25 KB):
```groovy
repositories {
...
// Needed to retrieve Cloth Config Lite for Omega Config in development environments.
maven {
name = "Shedaniel's Maven"
url = "https://maven.shedaniel.me/"
}
// Optional dependency for Mod Menu - recommended for viewing your screen in development
maven {
name = "TerraformersMC"
url = "https://maven.terraformersmc.com/releases/"
}
}
dependencies {
... (including the base declarations)
modImplementation include("dev.draylar.omega-config:omega-config-gui:${project.omega_config_version}")
modRuntimeOnly ("com.terraformersmc:modmenu:${project.modmenu_version}") // 3.0.1 for 1.18.1
}
```
---
### Extra API Utilities
@@ -52,8 +116,11 @@ MyModInitializer.CONFIG.value=false;
MyModInitializer.CONFIG.save(); // writes the new value to disk
```
`@Syncing` - *configuration options marked with this annotation will automatically sync to the client when they join a server.*
---
### License
ΩConfig is available under Public Domain. You are encouraged to utilize the code in this repository in any way you wish.
ΩConfig is available under MIT. Omega Config will bundle the MIT license inside the jar you pull as a dependency, which means you can distribute it as a bundled dependency without any additional steps.
+40 -182
View File
@@ -1,188 +1,90 @@
import java.nio.charset.StandardCharsets
// this build.gradle is tweaked from CCA: https://github.com/OnyxStudios/Cardinal-Components-API/blob/master/build.gradle
buildscript {
repositories {
mavenLocal()
google()
}
dependencies {
classpath 'com.guardsquare:proguard-gradle:7.1.0-beta4'
}
}
plugins {
id "fabric-loom" version "0.8-SNAPSHOT"
id "fabric-loom" version "1.6-SNAPSHOT"
id "maven-publish"
id "java-library"
}
group = "draylar"
group = "dev.draylar"
archivesBaseName = "omega-config"
subprojects {
apply plugin: 'fabric-loom'
apply plugin: 'maven-publish'
apply plugin: 'java-library'
archivesBaseName = project.name
group = "draylar.${project.group}"
// import utility functions
apply from: "https://raw.githubusercontent.com/NerdHubMC/Gradle-Scripts/master/scripts/utilities.gradle"
repositories {
mavenCentral()
}
compileJava {
options.encoding = StandardCharsets.UTF_8.name()
}
if (JavaVersion.current().isJava8Compatible()) {
allprojects {
tasks.withType(Javadoc) {
options.addStringOption("Xdoclint:none", "-quiet")
}
}
}
jar {
from "LICENSE.md"
from "LICENSE"
manifest.mainAttributes(
"Implementation-Title": project.archivesBaseName,
"Implementation-Version": mod_version,
"Maven-Artifact": "${project.group}:${project.name}:${mod_version}".toLowerCase(Locale.ROOT),
"Built-On-Minecraft": "${project.minecraft_version}",
"Built-On-Java": "${System.getProperty("java.vm.version")} (${System.getProperty("java.vm.vendor")})"
)
}
task sourcesJar(type: Jar, dependsOn: classes) {
from sourceSets.main.allSource
classifier = "sources"
}
task javadocJar(type: Jar, dependsOn: javadoc) {
from javadoc.destinationDir
classifier = "javadoc"
}
tasks.build.dependsOn javadocJar
group = "dev.draylar.${project.group}"
// Only publish for submodules (not the root project) - add standard jar, + sources & development jar
publishing {
repositories {
maven {
name = "draylarRepository"
url = "https://maven.draylar.dev/releases"
credentials(PasswordCredentials)
authentication {
basic(BasicAuthentication)
}
}
}
publications {
mavenJava(MavenPublication) {
artifact(remapJar) {
builtBy remapJar
}
artifact(sourcesJar) {
builtBy remapSourcesJar
}
artifact(file("${project.buildDir}/libs/${archivesBaseName}-${project.mod_version}-min.jar")) {
builtBy(remapJar)
classifier = 'min'
}
pom.withXml {
def depsNode = asNode().appendNode("dependencies")
subprojects.each {
def depNode = depsNode.appendNode("dependency")
depNode.appendNode("groupId", it.group)
depNode.appendNode("artifactId", it.name)
depNode.appendNode("version", it.version)
depNode.appendNode("scope", "compile")
}
}
from components.java
}
}
}
tasks.publish.dependsOn build //stupid fix for maven/loom not publishing the main artifact
task('proguard', type: proguard.gradle.ProGuardTask) {
configuration './proguard.conf'
verbose
injars project.buildDir.toString() + '/libs/' + archivesBaseName + "-" + project.mod_version + ".jar"
outjars project.buildDir.toString() + '/libs/' + archivesBaseName + "-" + project.mod_version + "-min.jar"
printmapping 'out.map'
keepparameternames
renamesourcefileattribute 'SourceFile'
keepattributes 'Signature,Exceptions,InnerClasses,PermittedSubclasses,EnclosingMethod,Deprecated,SourceFile,LineNumberTable'
keepattributes '*Annotation*'
keep 'public class * { \
public protected *; \
}'
keepclassmembernames 'class * { \
java.lang.Class class$(java.lang.String); \
java.lang.Class class$(java.lang.String, boolean); \
}'
keepclassmembers 'class draylar.omegaconfig.mixin.* {\
<fields>;\
<init>();\
<methods>;\
}'
// Add sources & javadoc artifacts
java {
withSourcesJar()
withJavadocJar()
}
remapJar.finalizedBy proguard
}
allprojects {
apply plugin: "fabric-loom"
sourceCompatibility = targetCompatibility = JavaVersion.VERSION_16
version = System.getenv("TRAVIS_TAG") ?: project.mod_version
sourceCompatibility = targetCompatibility = JavaVersion.VERSION_21
version = project.mod_version + "-" + project.minecraft_version
repositories {
maven {
name = "FabricMC"
url = "https://maven.fabricmc.net"
}
maven { url = "https://maven.terraformersmc.com/releases/" }
}
dependencies {
//to change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
modRuntime "com.terraformersmc:modmenu:2.0.0-beta.4"
modCompileOnly "com.terraformersmc:modmenu:2.0.0-beta.4"
}
processResources {
inputs.property "version", project.version
filesMatching("fabric.mod.json") {
expand "version": project.version
}
}
tasks.withType(JavaCompile) {
javadoc.options.addStringOption('Xdoclint:none', '-quiet')
}
jar {
from(rootProject.file("LICENSE.md")) {
from(rootProject.file("LICENSE")) {
rename { "LICENSE_${project.archivesBaseName.replace('-', '_')}" }
}
}
}
// Main project depends on the base & gui module for testing
dependencies {
implementation project(path: ":omega-config-base", configuration: "namedElements")
afterEvaluate {
processResources {
// this will ensure that this task is redone when there"s a change
inputs.property "version", mod_version
// replace stuff in fabric.mod.json, nothing else
from(sourceSets.main.resources.srcDirs) {
include "fabric.mod.json"
// add mod metadata
expand "version": mod_version
}
// copy everything else, that"s not the fabric.mod.json
from(sourceSets.main.resources.srcDirs) {
exclude "fabric.mod.json"
}
testmodImplementation sourceSets.main.output
}
}
@@ -191,53 +93,9 @@ sourceSets {
compileClasspath += main.compileClasspath
runtimeClasspath += main.runtimeClasspath
}
test {
compileClasspath += main.compileClasspath
runtimeClasspath += main.runtimeClasspath
}
}
task licenseFormatAll
subprojects { p -> licenseFormatAll.dependsOn("${p.path}:licenseFormat") }
subprojects.each { remapJar.dependsOn("${it.path}:remapJar") }
repositories {
maven {
name = "JitPack"
url = "https://jitpack.io"
}
}
dependencies {
implementation project(":omega-config-base")
implementation project(":omega-config-gui")
modRuntime "com.terraformersmc:modmenu:1.16.8"
modCompileOnly "com.terraformersmc:modmenu:1.16.8"
afterEvaluate {
testmodImplementation sourceSets.main.output
}
}
publishing {
publications {
mavenJava(MavenPublication) {
artifact(file("${project.buildDir}/libs/${archivesBaseName}-${project.mod_version}.jar")) {
builtBy(remapJar)
}
pom.withXml {
def depsNode = asNode().appendNode("dependencies")
subprojects.each {
def depNode = depsNode.appendNode("dependency")
depNode.appendNode("groupId", it.group)
depNode.appendNode("artifactId", it.name)
depNode.appendNode("version", it.version)
depNode.appendNode("scope", "compile")
}
}
}
}
}
tasks.publish.dependsOn build //stupid fix for maven/loom not publishing the main artifact
+11 -7
View File
@@ -1,14 +1,18 @@
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx2G
# Fabric Properties
# check these on https://fabricmc.net/versions.html
minecraft_version=1.17
yarn_mappings=1.17+build.7
loader_version=0.11.3
#Fabric api
fabric_version=0.34.10+1.17
minecraft_version=1.21
yarn_mappings=1.21+build.2
loader_version=0.15.11
# Fabric API
fabric_version=0.100.2+1.21
# Mod Properties
mod_version=1.1.0
maven_group=draylar
mod_version=1.4.4
maven_group=dev.draylar
archives_base_name=omega-config
modmenu_version=7.1.0
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+4 -3
View File
@@ -1,4 +1,5 @@
jdk:
- openjdk21
before_install:
- wget https://github.com/sormuras/bach/raw/master/install-jdk.sh
- source install-jdk.sh --feature 16
- jshell --version
- sdk install java 21.0.3-open
- sdk use java 21.0.3-open
-3
View File
@@ -1,3 +0,0 @@
-ignorewarnings
-keep class net.fabricmc.api.** { *; }
@@ -5,13 +5,16 @@ import com.google.gson.GsonBuilder;
import draylar.omegaconfig.api.Comment;
import draylar.omegaconfig.api.Config;
import draylar.omegaconfig.gson.SyncableExclusionStrategy;
import io.netty.buffer.Unpooled;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtList;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.network.codec.PacketCodec;
import net.minecraft.network.codec.PacketCodecs;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.util.Identifier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -23,44 +26,15 @@ import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.*;
public class OmegaConfig {
public class OmegaConfig implements ModInitializer {
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static final Identifier CONFIG_SYNC_PACKET = new Identifier("omegaconfig", "sync");
public static final Gson SYNC_ONLY_GSON = new GsonBuilder().addSerializationExclusionStrategy(new SyncableExclusionStrategy()).setPrettyPrinting().create();
private static final Logger LOGGER = LogManager.getLogger();
public static final Logger LOGGER = LogManager.getLogger();
private static final List<Config> REGISTERED_CONFIGURATIONS = new ArrayList<>();
static {
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> server.execute(() -> {
PacketByteBuf packet = new PacketByteBuf(Unpooled.buffer());
// list of configurations that are synced
NbtCompound root = new NbtCompound();
NbtList configurations = new NbtList();
// Iterate over each configuration.
// Find values that should be synced and send the value over.
OmegaConfig.getRegisteredConfigurations().forEach(config -> {
if (config.hasAnySyncable()) {
configurations.add(config.writeSyncingTag());
}
});
// save to packet and send to user
root.put("Configurations", configurations);
packet.writeNbt(root);
handler.sendPacket(ServerPlayNetworking.createS2CPacket(CONFIG_SYNC_PACKET, packet));
}));
}
public static <T extends Config> T register(Class<T> configClass) {
try {
// Attempt to instantiate a new instance of this class.
@@ -94,7 +68,8 @@ public class OmegaConfig {
}
return config;
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException exception) {
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException |
InvocationTargetException exception) {
exception.printStackTrace();
throw new RuntimeException("No valid constructor found for: " + configClass.getName());
}
@@ -162,7 +137,7 @@ public class OmegaConfig {
}
}
private static List<Class<?>> flatten(Class<?>[] array) {
public static List<Class<?>> flatten(Class<?>[] array) {
List<Class<?>> list = new ArrayList<>();
for (Class<?> clazz : array) {
@@ -177,12 +152,10 @@ public class OmegaConfig {
Class<?>[] classes = aClass.getDeclaredClasses();
if (classes.length != 0) {
for (Class<?> clazz : classes) {
populateRecursively(list, clazz);
}
}
}
private static void addFieldComments(Field field, Map<String, String> keyToComments) {
String fieldName = field.getName();
@@ -239,4 +212,38 @@ public class OmegaConfig {
public static List<Config> getRegisteredConfigurations() {
return REGISTERED_CONFIGURATIONS;
}
@Override
public void onInitialize() {
PayloadTypeRegistry.playS2C().register(OmegaConfig.SyncConfigPayload.ID, OmegaConfig.SyncConfigPayload.CODEC);
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> server.execute(() -> {
// list of configurations that are synced
NbtCompound root = new NbtCompound();
NbtList configurations = new NbtList();
// Iterate over each configuration.
// Find values that should be synced and send the value over.
OmegaConfig.getRegisteredConfigurations().forEach(config -> {
if (config.hasAnySyncable()) {
configurations.add(config.writeSyncingTag());
}
});
// save to packet and send to user
root.put("Configurations", configurations);
sender.sendPacket(new SyncConfigPayload(root));
}));
}
public record SyncConfigPayload(NbtCompound nbtCompound) implements CustomPayload {
public static final Identifier CONFIG_SYNC_PACKET = Identifier.of("omegaconfig", "sync");
public static final CustomPayload.Id<SyncConfigPayload> ID = new Id<>(CONFIG_SYNC_PACKET);
public static final PacketCodec<PacketByteBuf, SyncConfigPayload> CODEC = PacketCodecs.NBT_COMPOUND.xmap(SyncConfigPayload::new, SyncConfigPayload::nbtCompound).cast();
@Override
public Id<? extends CustomPayload> getId() {
return ID;
}
}
}
@@ -30,11 +30,12 @@ public class ClientMixin {
method = "<init>",
at = @At("RETURN"))
private void onReturn(RunArgs args, CallbackInfo ci) {
ClientPlayNetworking.registerGlobalReceiver(OmegaConfig.CONFIG_SYNC_PACKET, (client, handler, buf, responseSender) -> {
NbtCompound tag = buf.readNbt();
ClientPlayNetworking.registerGlobalReceiver(OmegaConfig.SyncConfigPayload.ID, (payload, context) -> {
NbtCompound tag = payload.nbtCompound();
savedClientConfig.clear();
client.execute(() -> {
context.client().execute(() -> {
if (tag != null && tag.contains("Configurations")) {
NbtList list = tag.getList("Configurations", NbtType.COMPOUND);
list.forEach(compound -> {
Binary file not shown.

After

Width:  |  Height:  |  Size: 225 B

@@ -1,13 +1,18 @@
{
"schemaVersion": 1,
"id": "omega-config",
"version": "1.0.8",
"version": "${version}",
"name": "OmegaConfig",
"description": "The last config solution you will ever use.",
"authors": [
"Draylar",
"Frqnny"
],
"entrypoints": {
"main": [
"draylar.omegaconfig.OmegaConfig"
]
},
"contact": {
"homepage": "https://github.com/Draylar/omega-config",
"sources": "https://github.com/Draylar/omega-config",
-3
View File
@@ -1,3 +0,0 @@
dependencies {
implementation project(":omega-config-base")
}
-3
View File
@@ -1,3 +0,0 @@
-ignorewarnings
-keep class net.fabricmc.api.** { *; }
@@ -1,24 +0,0 @@
package draylar.omegaconfiggui;
import draylar.omegaconfig.api.Config;
import draylar.omegaconfiggui.api.screen.ModMenuHelper;
import draylar.omegaconfiggui.api.screen.OmegaConfigScreen;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.loader.api.FabricLoader;
@Environment(EnvType.CLIENT)
public class OmegaConfigGui {
/**
* Registers a ModMenu configuration screen for the given {@link Config} instance.
*
* @param config registered config to create a ModMenu screen for
* @param <T> config type
*/
public static <T extends Config> void registerConfigScreen(T config) {
if (FabricLoader.getInstance().isModLoaded("modmenu")) {
ModMenuHelper.injectScreen(config, parent -> new OmegaConfigScreen<>(config, parent));
}
}
}
@@ -1,21 +0,0 @@
package draylar.omegaconfiggui.api.screen;
import com.google.common.collect.ImmutableMap;
import com.terraformersmc.modmenu.api.ConfigScreenFactory;
import draylar.omegaconfig.api.Config;
import draylar.omegaconfiggui.mixin.ModMenuAccessor;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
@Environment(EnvType.CLIENT)
public class ModMenuHelper {
public static <T extends Config> void injectScreen(T config, OmegaConfigScreenSupplier<T> factory) {
// they will suspect nothing
ModMenuAccessor.setConfigScreenFactories(
new ImmutableMap.Builder<String, ConfigScreenFactory<?>>()
.putAll(ModMenuAccessor.getConfigScreenFactories())
.put(config.getModid(), factory::get)
.build());
}
}
@@ -1,142 +0,0 @@
package draylar.omegaconfiggui.api.screen;
import com.mojang.blaze3d.systems.RenderSystem;
import draylar.omegaconfig.api.Config;
import draylar.omegaconfiggui.api.screen.widget.LabelWidget;
import draylar.omegaconfiggui.api.screen.widget.TypeWidgets;
import draylar.omegaconfiggui.api.screen.widget.WidgetSupplier;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.ClickableWidget;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.render.BufferBuilder;
import net.minecraft.client.render.Tessellator;
import net.minecraft.client.render.VertexFormat;
import net.minecraft.client.render.VertexFormats;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.LiteralText;
import net.minecraft.util.Pair;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class OmegaConfigScreen<T extends Config> extends Screen {
private static final List<Class<?>> validClasses = Arrays.asList(Double.class, String.class, Boolean.class);
private final T config;
private final Screen parent;
private final Map<Field, Pair<WidgetSupplier<Object, ClickableWidget>, ClickableWidget>> fieldWidgets = new HashMap<>();
public OmegaConfigScreen(T config, Screen parent) {
super(new LiteralText(""));
this.config = config;
this.parent = parent;
}
@Override
public void init() {
super.init();
try {
// add label & button for each config entry
// TODO: SUB-CLASS SUPPORT
List<Field> collect = Arrays.stream(config.getClass().getDeclaredFields()).filter(field -> validClasses.contains(TypeWidgets.unbox(field.getType()))).collect(Collectors.toList());
int over = 0;
for (Field field : collect) {
Class<?> unbox = TypeWidgets.unbox(field.getType());
// label
addDrawable(new LabelWidget(150, 15 + height / 6 + 20 * over, new LiteralText(field.getName())));
// get value
field.setAccessible(true);
Object value = field.get(config);
// button / interact
ClickableWidget button;
WidgetSupplier<Object, ClickableWidget> widgetSupplier = (WidgetSupplier<Object, ClickableWidget>) TypeWidgets.get(unbox);
if (widgetSupplier != null) {
button = widgetSupplier.create(this, 250, 5 + height / 6 + 25 * over, 100, 20, new LiteralText(field.getName()), value);
} else {
button = new TextFieldWidget(client.textRenderer, 250, 5 + height / 6 + 25 * over, 100, 20, new LiteralText(field.getName()));
}
fieldWidgets.put(field, new Pair<>(widgetSupplier, button));
addSelectableChild(button);
over++;
}
} catch (Exception e) {
e.printStackTrace();
}
// save and exit
ButtonWidget exit = new ButtonWidget(width - 60, height - 30, 50, 20, new LiteralText("Exit"), widget -> onClose());
ButtonWidget save = new ButtonWidget(10, height - 30, 50, 20, new LiteralText("Save"), widget -> {
fieldWidgets.forEach((field, pair) -> {
try {
field.set(config, pair.getLeft().get(pair.getRight()));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
config.save();
});
addSelectableChild(save);
addSelectableChild(exit);
}
@Override
public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) {
renderBackground(matrices);
//TODO make this work. for Drawables (children) it works in parent method
/*
for (ClickableWidget button : this.) {
button.render(matrices, mouseX, mouseY, delta);
}
for (Element element : this.children) {
if (element instanceof Drawable && !buttons.contains(element)) {
((Drawable) element).render(matrices, mouseX, mouseY, delta);
}
}
*/
}
@Override
public void onClose() {
client.openScreen(parent);
}
@Override
public void renderBackground(MatrixStack matrices) {
// TODO: option for transparent BG
// this.fillGradient(matrices, 0, 0, this.width, this.height, -1072689136, -804253680);
renderCustomBackgroundTexture(0, 64, 64, 64, 0, 0, this.height, this.width);
renderCustomBackgroundTexture(0, 32, 32, 32, 0, this.height / 8, this.height / 8 * 6, this.width);
textRenderer.draw(matrices, config.getName(), width / 2f - textRenderer.getWidth(config.getName()) / 2f, 10, 0xffffff);
}
public void renderCustomBackgroundTexture(int vOffset, int r, int g, int b, int x, int y, int height, int width) {
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder bufferBuilder = tessellator.getBuffer();
this.client.getTextureManager().bindTexture(OPTIONS_BACKGROUND_TEXTURE);
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
bufferBuilder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_TEXTURE_COLOR);
bufferBuilder.vertex(x, height + y, 0.0D).texture(0.0F, (float) height / 32.0F + (float) vOffset).color(r, g, b, 255).next();
bufferBuilder.vertex(width + x, height + y, 0.0D).texture((float) width / 32.0F, (float) height / 32.0F + (float) vOffset).color(r, g, b, 255).next();
bufferBuilder.vertex(width + x, y, 0.0D).texture((float) width / 32.0F, (float) vOffset).color(r, g, b, 255).next();
bufferBuilder.vertex(x, y, 0.0D).texture(0.0F, (float) vOffset).color(r, g, b, 255).next();
tessellator.draw();
}
}
@@ -1,8 +0,0 @@
package draylar.omegaconfiggui.api.screen;
import draylar.omegaconfig.api.Config;
import net.minecraft.client.gui.screen.Screen;
public interface OmegaConfigScreenSupplier<T extends Config> {
OmegaConfigScreen<T> get(Screen parent);
}
@@ -1,30 +0,0 @@
package draylar.omegaconfiggui.api.screen.widget;
import draylar.omegaconfiggui.mixin.ClickableWidgetInvoker;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ClickableWidget;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.text.Text;
public class BaseTextFieldWidget extends TextFieldWidget {
protected final Screen parent;
public BaseTextFieldWidget(Screen parent, TextRenderer textRenderer, int x, int y, int width, int height, Text text) {
super(textRenderer, x, y, width, height, text);
this.parent = parent;
}
@Override
public void setTextFieldFocused(boolean focused) {
// unfocus all others
parent.children().forEach(element -> {
if (element instanceof ClickableWidget) {
((ClickableWidgetInvoker) element).callSetFocused(false);
}
});
super.setFocused(focused);
}
}
@@ -1,25 +0,0 @@
package draylar.omegaconfiggui.api.screen.widget;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.text.Text;
public class DoubleFieldWidget extends BaseTextFieldWidget {
public DoubleFieldWidget(Screen parent, TextRenderer textRenderer, int x, int y, int width, int height, Text text) {
super(parent, textRenderer, x, y, width, height, text);
}
@Override
public void write(String string) {
try {
if (!string.equals(".") || getText().contains(".")) {
Double.parseDouble(string);
}
super.write(string);
} catch (NumberFormatException ignored) {
}
}
}
@@ -1,26 +0,0 @@
package draylar.omegaconfiggui.api.screen.widget;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.Drawable;
import net.minecraft.client.gui.DrawableHelper;
import net.minecraft.client.gui.Element;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.Text;
public class LabelWidget extends DrawableHelper implements Drawable, Element {
private final int x;
private final int y;
private final Text message;
public LabelWidget(int x, int y, Text message) {
this.x = x;
this.y = y;
this.message = message;
}
@Override
public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) {
drawTextWithShadow(matrices, MinecraftClient.getInstance().textRenderer, message, x, y, 0xffffff);
}
}
@@ -1,45 +0,0 @@
package draylar.omegaconfiggui.api.screen.widget;
import draylar.omegaconfiggui.api.screen.widget.supplier.BooleanWidgetSupplier;
import draylar.omegaconfiggui.api.screen.widget.supplier.DoubleWidgetSupplier;
import draylar.omegaconfiggui.api.screen.widget.supplier.StringWidgetSupplier;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
public class TypeWidgets {
public static final Map<Class<?>, WidgetSupplier<?, ?>> CLASS_WIDGETS = new HashMap<>();
public static final Map<Class<?>, Class<?>> PRIMITIVE_TO_BOXED = new HashMap<>();
static {
CLASS_WIDGETS.put(Double.class, new DoubleWidgetSupplier());
CLASS_WIDGETS.put(Boolean.class, new BooleanWidgetSupplier());
CLASS_WIDGETS.put(String.class, new StringWidgetSupplier());
// primitive -> boxed
PRIMITIVE_TO_BOXED.put(boolean.class, Boolean.class);
PRIMITIVE_TO_BOXED.put(byte.class, Byte.class);
PRIMITIVE_TO_BOXED.put(char.class, Character.class);
PRIMITIVE_TO_BOXED.put(double.class, Double.class);
PRIMITIVE_TO_BOXED.put(float.class, Float.class);
PRIMITIVE_TO_BOXED.put(int.class, Integer.class);
PRIMITIVE_TO_BOXED.put(long.class, Long.class);
PRIMITIVE_TO_BOXED.put(short.class, Short.class);
PRIMITIVE_TO_BOXED.put(void.class, Void.class);
}
private TypeWidgets() {
// NO-OP
}
@Nullable
public static <T> WidgetSupplier<T, ?> get(Class<T> typeClass) {
return (WidgetSupplier<T, ?>) CLASS_WIDGETS.get(unbox(typeClass));
}
public static Class<?> unbox(Class<?> c) {
return PRIMITIVE_TO_BOXED.getOrDefault(c, c);
}
}
@@ -1,11 +0,0 @@
package draylar.omegaconfiggui.api.screen.widget;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ClickableWidget;
import net.minecraft.text.LiteralText;
public interface WidgetSupplier<T, A extends ClickableWidget> {
ClickableWidget create(Screen parent, int x, int y, int width, int height, LiteralText prompt, T value);
T get(A widget);
}
@@ -1,19 +0,0 @@
package draylar.omegaconfiggui.api.screen.widget.supplier;
import draylar.omegaconfiggui.api.screen.widget.WidgetSupplier;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.CheckboxWidget;
import net.minecraft.text.LiteralText;
public class BooleanWidgetSupplier implements WidgetSupplier<Boolean, CheckboxWidget> {
@Override
public CheckboxWidget create(Screen parent, int x, int y, int width, int height, LiteralText prompt, Boolean value) {
return new CheckboxWidget(x, y, 20, 20, new LiteralText(""), value);
}
@Override
public Boolean get(CheckboxWidget widget) {
return widget.isChecked();
}
}
@@ -1,35 +0,0 @@
package draylar.omegaconfiggui.api.screen.widget.supplier;
import draylar.omegaconfiggui.api.screen.widget.DoubleFieldWidget;
import draylar.omegaconfiggui.api.screen.widget.WidgetSupplier;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.text.LiteralText;
public class DoubleWidgetSupplier implements WidgetSupplier<Double, DoubleFieldWidget> {
@Override
public DoubleFieldWidget create(Screen parent, int x, int y, int width, int height, LiteralText prompt, Double value) {
LiteralText text = new LiteralText(String.valueOf(value));
DoubleFieldWidget widget = new DoubleFieldWidget(parent, MinecraftClient.getInstance().textRenderer, x, y, width, height, text);
widget.setText(text.asString());
return widget;
}
@Override
public Double get(DoubleFieldWidget widget) {
String message = widget.getText();
// if it is just a . or empty, return 0
if (message.equals(".") || message.isEmpty()) {
return 0.0;
}
// trim potential trailing .
if (message.indexOf(".") == message.length()) {
message = message.substring(0, message.length() - 1);
}
return Double.parseDouble(message);
}
}
@@ -1,24 +0,0 @@
package draylar.omegaconfiggui.api.screen.widget.supplier;
import draylar.omegaconfiggui.api.screen.widget.BaseTextFieldWidget;
import draylar.omegaconfiggui.api.screen.widget.WidgetSupplier;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.text.LiteralText;
public class StringWidgetSupplier implements WidgetSupplier<String, TextFieldWidget> {
@Override
public TextFieldWidget create(Screen parent, int x, int y, int width, int height, LiteralText prompt, String value) {
LiteralText text = new LiteralText(value);
TextFieldWidget textField = new BaseTextFieldWidget(parent, MinecraftClient.getInstance().textRenderer, x, y, width, height, text);
textField.setText(value);
return textField;
}
@Override
public String get(TextFieldWidget widget) {
return widget.getText();
}
}
@@ -1,11 +0,0 @@
package draylar.omegaconfiggui.mixin;
import net.minecraft.client.gui.widget.ClickableWidget;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(ClickableWidget.class)
public interface ClickableWidgetInvoker {
@Invoker
void callSetFocused(boolean focused);
}
@@ -1,20 +0,0 @@
package draylar.omegaconfiggui.mixin;
import com.google.common.collect.ImmutableMap;
import com.terraformersmc.modmenu.ModMenu;
import com.terraformersmc.modmenu.api.ConfigScreenFactory;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(ModMenu.class)
public interface ModMenuAccessor {
@Accessor
static ImmutableMap<String, ConfigScreenFactory<?>> getConfigScreenFactories() {
throw new UnsupportedOperationException();
}
@Accessor
static void setConfigScreenFactories(ImmutableMap<String, ConfigScreenFactory<?>> configScreenFactories) {
throw new UnsupportedOperationException();
}
}
@@ -1,30 +0,0 @@
{
"schemaVersion": 1,
"id": "omega-config-gui",
"version": "${version}",
"name": "OmegaConfigGui",
"description": "GUI support for Omega Config.",
"authors": [
"Draylar"
],
"contact": {
"homepage": "https://github.com/Draylar/omega-config",
"sources": "https://github.com/Draylar/omega-config",
"issues": "https://github.com/Draylar/omega-config/issues"
},
"license": "MIT",
"environment": "*",
"mixins": [
"omega-config-gui.mixins.json"
],
"depends": {
"fabricloader": "*",
"fabric": "*",
"minecraft": "*"
},
"custom": {
"modmenu": {
"badges": [ "library" ]
}
}
}
@@ -1,15 +0,0 @@
{
"required": true,
"minVersion": "0.8",
"package": "draylar.omegaconfiggui.mixin",
"compatibilityLevel": "JAVA_16",
"mixins": [
"ClickableWidgetInvoker",
"ModMenuAccessor"
],
"client": [
],
"injectors": {
"defaultRequire": 1
}
}
-3
View File
@@ -1,3 +0,0 @@
-ignorewarnings
-keep class net.fabricmc.api.** { *; }
-1
View File
@@ -12,4 +12,3 @@ pluginManagement {
rootProject.name = 'omega-config'
include 'omega-config-base'
include 'omega-config-gui'
@@ -1,20 +1,19 @@
package draylar.omegatest;
import draylar.omegaconfiggui.OmegaConfigGui;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.minecraft.client.MinecraftClient;
import net.minecraft.text.LiteralText;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.text.Text;
public class OmegaTestClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
OmegaConfigGui.registerConfigScreen(OmegaTestMain.CONFIG);
HudRenderCallback.EVENT.register((stack, delta) -> {
MinecraftClient.getInstance().textRenderer.draw(stack, new LiteralText(String.valueOf(OmegaTestMain.CONFIG.v)), 15, 15, 0xffffff);
MinecraftClient.getInstance().textRenderer.draw(stack, new LiteralText(String.valueOf(OmegaTestMain.CONFIG.doubleTest)), 15, 30, 0xffffff);
HudRenderCallback.EVENT.register((context, delta) -> {
TextRenderer tr = MinecraftClient.getInstance().textRenderer;
context.drawText(tr, Text.literal(String.valueOf(OmegaTestMain.CONFIG.v)), 15, 15, 0xffffff, true);
context.drawText(tr, Text.literal(String.valueOf(OmegaTestMain.CONFIG.doubleTest)), 15, 25, 0xffffff, true);
});
}
}
@@ -0,0 +1,3 @@
{
"config.omega-config-test.test-config": "Omega Config - Test Config"
}