From d4bb5a94308d4379ef3d6cc7b9221ea0d98ff051 Mon Sep 17 00:00:00 2001 From: Wyvest <45589059+Wyvest@users.noreply.github.com> Date: Sat, 2 Jul 2022 06:12:23 +0700 Subject: Separate Minecraft dependant and non-dependant code --- build.gradle.kts | 237 ++------------- root.gradle.kts | 10 - settings.gradle.kts | 18 +- .../compatibility/vigilance/VigilanceConfig.java | 8 +- .../oneconfig/config/profiles/Profiles.java | 16 +- .../oneconfig/events/event/ChatReceiveEvent.java | 11 +- .../oneconfig/events/event/ReceivePacketEvent.java | 6 +- .../oneconfig/events/event/ScreenOpenEvent.java | 5 +- .../oneconfig/events/event/SendPacketEvent.java | 5 +- .../oneconfig/events/event/TimerUpdateEvent.java | 19 +- .../java/cc/polyfrost/oneconfig/gui/GuiPause.java | 9 + .../java/cc/polyfrost/oneconfig/gui/HudGui.java | 65 ++-- .../cc/polyfrost/oneconfig/gui/OneConfigGui.java | 25 +- .../java/cc/polyfrost/oneconfig/gui/SideBar.java | 8 +- .../oneconfig/gui/elements/BasicElement.java | 4 +- .../oneconfig/gui/elements/ColorSelector.java | 18 +- .../polyfrost/oneconfig/gui/elements/ModCard.java | 8 +- .../polyfrost/oneconfig/gui/elements/Slider.java | 4 +- .../gui/elements/config/ConfigCheckbox.java | 4 +- .../gui/elements/config/ConfigDropdown.java | 22 +- .../gui/elements/config/ConfigPageButton.java | 4 +- .../gui/elements/config/ConfigSlider.java | 4 +- .../gui/elements/config/ConfigSwitch.java | 4 +- .../gui/elements/config/ConfigTextBox.java | 4 +- .../gui/elements/text/TextInputField.java | 17 +- .../cc/polyfrost/oneconfig/gui/pages/Page.java | 8 +- src/main/java/cc/polyfrost/oneconfig/hud/Hud.java | 12 +- .../java/cc/polyfrost/oneconfig/hud/TextHud.java | 3 +- .../java/cc/polyfrost/oneconfig/images/Image.java | 8 +- .../cc/polyfrost/oneconfig/internal/OneConfig.java | 87 ------ .../oneconfig/internal/config/OneConfigConfig.java | 14 +- .../oneconfig/internal/config/Preferences.java | 14 +- .../oneconfig/internal/config/core/ConfigCore.java | 2 + .../oneconfig/internal/gui/BlurHandler.java | 140 +-------- .../oneconfig/internal/init/OneConfigInit.java | 2 - .../internal/mixin/FontRendererMixin.java | 15 - .../internal/mixin/GuiIngameForgeMixin.java | 17 -- .../oneconfig/internal/mixin/MinecraftMixin.java | 98 ------ .../internal/mixin/NetHandlerPlayClientMixin.java | 36 --- .../internal/mixin/NetworkManagerMixin.java | 23 -- .../internal/mixin/OptifineConfigMixin.java | 21 -- .../internal/mixin/ShaderGroupAccessor.java | 14 - .../oneconfig/internal/mixin/VigilantMixin.java | 8 - .../oneconfig/internal/mixin/WorldClientMixin.java | 21 -- .../internal/plugin/asm/ClassTransformer.java | 102 ------- .../internal/plugin/asm/ITransformer.java | 24 -- .../internal/plugin/asm/OneConfigTweaker.java | 117 -------- .../asm/tweakers/NanoVGGLConfigTransformer.java | 47 --- .../plugin/asm/tweakers/VigilantTransformer.java | 89 ------ .../plugin/hooks/Lwjgl2FunctionProvider.java | 39 --- .../internal/plugin/hooks/OptifineConfigHook.java | 23 -- .../internal/plugin/hooks/VigilantHook.java | 27 -- .../polyfrost/oneconfig/platform/GLPlatform.java | 17 ++ .../polyfrost/oneconfig/platform/GuiPlatform.java | 8 + .../polyfrost/oneconfig/platform/I18nPlatform.java | 5 + .../oneconfig/platform/LoaderPlatform.java | 19 ++ .../oneconfig/platform/MousePlatform.java | 15 + .../cc/polyfrost/oneconfig/platform/Platform.java | 55 ++++ .../oneconfig/platform/ServerPlatform.java | 7 + .../oneconfig/renderer/RenderManager.java | 29 +- .../polyfrost/oneconfig/test/TestConfig_Test.java | 6 +- .../cc/polyfrost/oneconfig/test/TestMod_Test.java | 14 - .../oneconfig/test/TestMultilineHud_Test.java | 3 - .../oneconfig/test/TestNanoVGGui_Test.java | 1 - .../cc/polyfrost/oneconfig/utils/InputUtils.java | 13 +- .../oneconfig/utils/commands/CommandManager.java | 328 +------------------- .../utils/commands/PlatformCommandManager.java | 7 + .../cc/polyfrost/oneconfig/utils/gui/GuiUtils.java | 27 +- .../polyfrost/oneconfig/utils/gui/OneUIScreen.java | 31 +- .../oneconfig/utils/hypixel/HypixelUtils.java | 19 +- .../cc/polyfrost/oneconfig/utils/dsl/DSLs.kt | 9 - .../polyfrost/oneconfig/utils/dsl/GuiUtilsDSL.kt | 11 - src/main/resources/mixins.oneconfig.json | 22 -- versions/build.gradle.kts | 306 +++++++++++++++++++ versions/root.gradle.kts | 9 + .../oneconfig/events/event/ChatReceiveEvent.java | 22 ++ .../oneconfig/events/event/ReceivePacketEvent.java | 11 + .../oneconfig/events/event/ScreenOpenEvent.java | 17 ++ .../oneconfig/events/event/SendPacketEvent.java | 11 + .../oneconfig/events/event/TimerUpdateEvent.java | 24 ++ .../cc/polyfrost/oneconfig/internal/OneConfig.java | 93 ++++++ .../internal/gui/impl/BlurHandlerImpl.java | 132 +++++++++ .../internal/mixin/GuiIngameForgeMixin.java | 19 ++ .../oneconfig/internal/mixin/MinecraftMixin.java | 100 +++++++ .../internal/mixin/NetHandlerPlayClientMixin.java | 38 +++ .../internal/mixin/NetworkManagerMixin.java | 25 ++ .../internal/mixin/OptifineConfigMixin.java | 23 ++ .../internal/mixin/ShaderGroupAccessor.java | 16 + .../oneconfig/internal/mixin/VigilantMixin.java | 10 + .../oneconfig/internal/mixin/WorldClientMixin.java | 23 ++ .../internal/plugin/asm/ClassTransformer.java | 102 +++++++ .../internal/plugin/asm/ITransformer.java | 24 ++ .../internal/plugin/asm/OneConfigTweaker.java | 117 ++++++++ .../asm/tweakers/NanoVGGLConfigTransformer.java | 47 +++ .../plugin/asm/tweakers/VigilantTransformer.java | 89 ++++++ .../plugin/hooks/Lwjgl2FunctionProvider.java | 47 +++ .../internal/plugin/hooks/OptifineConfigHook.java | 22 ++ .../internal/plugin/hooks/VigilantHook.java | 26 ++ .../oneconfig/platform/impl/GLPlatformImpl.java | 67 +++++ .../oneconfig/platform/impl/GuiPlatformImpl.java | 31 ++ .../oneconfig/platform/impl/I18nPlatformImpl.java | 13 + .../platform/impl/LoaderPlatformImpl.java | 26 ++ .../oneconfig/platform/impl/MousePlatformImpl.java | 53 ++++ .../oneconfig/platform/impl/PlatformImpl.java | 12 + .../platform/impl/ServerPlatformImpl.java | 22 ++ .../utils/commands/PlatformCommandManagerImpl.java | 330 +++++++++++++++++++++ .../cc/polyfrost/oneconfig/utils/gui/GuiUtils.java | 100 +++++++ .../cc/polyfrost/oneconfig/utils/dsl/DSLs.kt | 9 + .../polyfrost/oneconfig/utils/dsl/GuiUtilsDSL.kt | 11 + ...cc.polyfrost.oneconfig.internal.gui.BlurHandler | 1 + .../cc.polyfrost.oneconfig.platform.GLPlatform | 1 + .../cc.polyfrost.oneconfig.platform.GuiPlatform | 1 + .../cc.polyfrost.oneconfig.platform.I18nPlatform | 1 + .../cc.polyfrost.oneconfig.platform.LoaderPlatform | 1 + .../cc.polyfrost.oneconfig.platform.MousePlatform | 1 + .../cc.polyfrost.oneconfig.platform.Platform | 1 + .../cc.polyfrost.oneconfig.platform.ServerPlatform | 1 + ...oneconfig.utils.commands.PlatformCommandManager | 1 + versions/src/main/resources/mixins.oneconfig.json | 21 ++ 119 files changed, 2455 insertions(+), 1794 deletions(-) delete mode 100644 root.gradle.kts create mode 100644 src/main/java/cc/polyfrost/oneconfig/gui/GuiPause.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/OneConfig.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/mixin/FontRendererMixin.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/mixin/GuiIngameForgeMixin.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/mixin/MinecraftMixin.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetHandlerPlayClientMixin.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetworkManagerMixin.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/mixin/OptifineConfigMixin.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/mixin/ShaderGroupAccessor.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/mixin/VigilantMixin.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/mixin/WorldClientMixin.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ClassTransformer.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ITransformer.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/OneConfigTweaker.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/NanoVGGLConfigTransformer.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/VigilantTransformer.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/OptifineConfigHook.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/VigilantHook.java create mode 100644 src/main/java/cc/polyfrost/oneconfig/platform/GLPlatform.java create mode 100644 src/main/java/cc/polyfrost/oneconfig/platform/GuiPlatform.java create mode 100644 src/main/java/cc/polyfrost/oneconfig/platform/I18nPlatform.java create mode 100644 src/main/java/cc/polyfrost/oneconfig/platform/LoaderPlatform.java create mode 100644 src/main/java/cc/polyfrost/oneconfig/platform/MousePlatform.java create mode 100644 src/main/java/cc/polyfrost/oneconfig/platform/Platform.java create mode 100644 src/main/java/cc/polyfrost/oneconfig/platform/ServerPlatform.java delete mode 100644 src/main/java/cc/polyfrost/oneconfig/test/TestMod_Test.java create mode 100644 src/main/java/cc/polyfrost/oneconfig/utils/commands/PlatformCommandManager.java delete mode 100644 src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/DSLs.kt delete mode 100644 src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/GuiUtilsDSL.kt delete mode 100644 src/main/resources/mixins.oneconfig.json create mode 100644 versions/build.gradle.kts create mode 100644 versions/root.gradle.kts create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/events/event/ChatReceiveEvent.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/events/event/ReceivePacketEvent.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/events/event/ScreenOpenEvent.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/events/event/SendPacketEvent.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/events/event/TimerUpdateEvent.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/OneConfig.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/gui/impl/BlurHandlerImpl.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/GuiIngameForgeMixin.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/MinecraftMixin.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetHandlerPlayClientMixin.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetworkManagerMixin.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/OptifineConfigMixin.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/ShaderGroupAccessor.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/VigilantMixin.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/WorldClientMixin.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ClassTransformer.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ITransformer.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/OneConfigTweaker.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/NanoVGGLConfigTransformer.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/VigilantTransformer.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/OptifineConfigHook.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/VigilantHook.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/GLPlatformImpl.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/GuiPlatformImpl.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/I18nPlatformImpl.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/LoaderPlatformImpl.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/MousePlatformImpl.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/PlatformImpl.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/ServerPlatformImpl.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/utils/commands/PlatformCommandManagerImpl.java create mode 100644 versions/src/main/java/cc/polyfrost/oneconfig/utils/gui/GuiUtils.java create mode 100644 versions/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/DSLs.kt create mode 100644 versions/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/GuiUtilsDSL.kt create mode 100644 versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.internal.gui.BlurHandler create mode 100644 versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.GLPlatform create mode 100644 versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.GuiPlatform create mode 100644 versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.I18nPlatform create mode 100644 versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.LoaderPlatform create mode 100644 versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.MousePlatform create mode 100644 versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.Platform create mode 100644 versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.ServerPlatform create mode 100644 versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.utils.commands.PlatformCommandManager create mode 100644 versions/src/main/resources/mixins.oneconfig.json diff --git a/build.gradle.kts b/build.gradle.kts index 1f20571..944612c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,25 +1,22 @@ -import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar +import gg.essential.gradle.multiversion.StripReferencesTransform.Companion.registerStripReferencesAttribute import gg.essential.gradle.util.RelocationTransform.Companion.registerRelocationAttribute -import gg.essential.gradle.util.noServerRunConfigs import gg.essential.gradle.util.prebundle -import net.fabricmc.loom.task.RemapSourcesJarTask plugins { - kotlin("jvm") - id("gg.essential.multi-version") + kotlin("jvm") version "1.6.21" id("gg.essential.defaults.repo") id("gg.essential.defaults.java") - id("gg.essential.defaults.loom") - id("com.github.johnrengelman.shadow") id("net.kyori.blossom") version "1.3.0" - id("io.github.juuxel.loom-quiltflower-mini") - id("org.jetbrains.dokka") version "1.6.21" id("maven-publish") id("signing") java } +kotlin.jvmToolchain { + (this as JavaToolchainSpec).languageVersion.set(JavaLanguageVersion.of(8)) +} + java { withSourcesJar() } @@ -28,10 +25,6 @@ val mod_name: String by project val mod_version: String by project val mod_id: String by project -preprocess { - vars.put("MODERN", if (project.platform.mcMinor >= 16) 1 else 0) -} - blossom { replaceToken("@VER@", mod_version) replaceToken("@NAME@", mod_name) @@ -40,25 +33,6 @@ blossom { version = mod_version group = "cc.polyfrost" -base { - archivesName.set("$mod_id-$platform") -} -loom { - noServerRunConfigs() - if (project.platform.isLegacyForge) { - launchConfigs.named("client") { - arg("--tweakClass", "cc.polyfrost.oneconfig.internal.plugin.asm.OneConfigTweaker") - property("mixin.debug.export", "true") - property("debugBytecode", "true") - } - } - if (project.platform.isForge) { - forge { - mixinConfig("mixins.${mod_id}.json") - } - } - mixin.defaultRefmapName.set("mixins.${mod_id}.refmap.json") -} repositories { maven("https://repo.polyfrost.cc/releases") @@ -90,12 +64,29 @@ sourceSets { } } +val common = registerStripReferencesAttribute("common") { + excludes.add("net.minecraft") + excludes.add("net.minecraftforge") +} + dependencies { - compileOnly("gg.essential:vigilance-$platform:222") { + + compileOnly("com.google.code.gson:gson:2.2.4") + compileOnly("commons-io:commons-io:2.4") + compileOnly("com.google.guava:guava:17.0") + compileOnly("org.lwjgl:lwjgl-opengl:3.3.1") + compileOnly("org.apache.logging.log4j:log4j-core:2.0-beta9") + compileOnly("org.apache.logging.log4j:log4j-api:2.0-beta9") + compileOnly("org.ow2.asm:asm-debug-all:5.0.3") + compileOnly("org.apache.commons:commons-lang3:3.3.2") + + compileOnly("gg.essential:vigilance-1.8.9-forge:222") { + attributes { attribute(common, true) } isTransitive = false } - shadeRelocated("gg.essential:universalcraft-$platform:211") { + shadeRelocated("gg.essential:universalcraft-1.8.9-forge:211") { + attributes { attribute(common, true) } isTransitive = false } @@ -130,197 +121,29 @@ dependencies { shade("cc.polyfrost:lwjgl:1.0.0-alpha1") shadeNoPom(prebundle(shadeRelocated)) - dokkaHtmlPlugin("org.jetbrains.dokka:kotlin-as-java-plugin:1.6.21") - configurations.named(JavaPlugin.COMPILE_CLASSPATH_CONFIGURATION_NAME) { extendsFrom(shadeNoPom) } configurations.named(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME) { extendsFrom(shadeNoPom) } } -tasks.processResources { - inputs.property("id", mod_id) - inputs.property("name", mod_name) - val java = if (project.platform.mcMinor >= 18) { - 17 - } else { - if (project.platform.mcMinor == 17) 16 else 8 - } - val compatLevel = "JAVA_${java}" - inputs.property("java", java) - inputs.property("java_level", compatLevel) - inputs.property("version", mod_version) - inputs.property("mcVersionStr", project.platform.mcVersionStr) - filesMatching(listOf("mcmod.info", "mixins.${mod_id}.json", "mods.toml")) { - expand( - mapOf( - "id" to mod_id, - "name" to mod_name, - "java" to java, - "java_level" to compatLevel, - "version" to mod_version, - "mcVersionStr" to project.platform.mcVersionStr - ) - ) - } - filesMatching("fabric.mod.json") { - expand( - mapOf( - "id" to mod_id, - "name" to mod_name, - "java" to java, - "java_level" to compatLevel, - "version" to mod_version, - "mcVersionStr" to project.platform.mcVersionStr.substringBeforeLast(".") + ".x" - ) - ) - } -} - tasks { withType(Jar::class.java) { - if (project.platform.isFabric) { - exclude("mcmod.info", "mods.toml") - } else { - exclude("fabric.mod.json") - if (project.platform.isLegacyForge) { - exclude("mods.toml") - exclude("META-INF/versions/**") - exclude("**/module-info.class") - exclude("**/package-info.class") - } else { - exclude("mcmod.info") - } - } + duplicatesStrategy = DuplicatesStrategy.EXCLUDE if (!name.contains("sourcesjar", ignoreCase = true) || !name.contains("dokka", ignoreCase = true)) { exclude("**/**_Test.**") exclude("**/**_Test$**.**") } } - named("shadowJar") { - archiveClassifier.set("donotusethis") - configurations = listOf(shade, shadeNoPom) - duplicatesStrategy = DuplicatesStrategy.EXCLUDE - dependsOn(jar) - } - remapJar { - input.set(shadowJar.get().archiveFile) - archiveClassifier.set("full") - } - fun Jar.excludeInternal() { - exclude("**/internal/**") - } jar { - dependsOn(shadeNoPom) - from({ shadeNoPom.map { if (it.isDirectory) it else zipTree(it) } }) - manifest { - attributes( - mapOf( - "ModSide" to "CLIENT", - "ForceLoadAsMod" to true, - "TweakOrder" to "0", - "MixinConfigs" to "mixins.oneconfig.json", - "TweakClass" to "cc.polyfrost.oneconfig.internal.plugin.asm.OneConfigTweaker" - ) - ) - } - excludeInternal() + dependsOn(shadeNoPom, shade) + from({ ArrayList().also { it.addAll(shadeNoPom); it.addAll(shade) }.map { if (it.isDirectory) it else zipTree(it) } }) + archiveClassifier.set("") } - dokkaHtml.configure { - outputDirectory.set(buildDir.resolve("dokka")) - moduleName.set("OneConfig $platform") - moduleVersion.set(mod_version) - dokkaSourceSets { - configureEach { - jdkVersion.set(8) - //reportUndocumented.set(true) - } - } - doLast { - val outputFile = outputDirectory.get().resolve("images/logo-icon.svg") - if (outputFile.exists()) { - outputFile.delete() - } - val inputFile = project.rootDir.resolve("src/main/resources/assets/oneconfig/icons/OneConfig.svg") - inputFile.copyTo(outputFile) - } - } - val dokkaJar = create("dokkaJar", Jar::class.java) { - archiveClassifier.set("dokka") - group = "build" - dependsOn(dokkaHtml) - from(layout.buildDirectory.dir("dokka")) - } named("sourcesJar") { - dependsOn(dokkaJar) - excludeInternal() + exclude("**/internal/**") archiveClassifier.set("sources") doFirst { archiveClassifier.set("sources") } } - withType { - enabled = false - } -} - -afterEvaluate { - val checkFile = file(".gradle/loom-cache/SETUP") - @Suppress("UNUSED_VARIABLE") - val setupGradle by tasks.creating { - group = "loom" - description = "Setup OneConfig" - dependsOn(tasks.named("genSourcesWithQuiltflower").get()) - doLast { - checkFile.parentFile.mkdirs() - checkFile.createNewFile() - } - } - - if (!checkFile.exists()) { - logger.error("--------------") - logger.error("PLEASE RUN THE `setupGradle` TASK, OR ELSE UNEXPECTED THING MAY HAPPEN!") - logger.error("`setupGradle` is in the loom category of your gradle project.") - logger.error("--------------") - } -} - -publishing { - publications { - register("oneconfig-$platform") { - groupId = "cc.polyfrost" - artifactId = base.archivesName.get() - - artifact(tasks["jar"]) - artifact(tasks["remapJar"]) - artifact(tasks["sourcesJar"]) - artifact(tasks["dokkaJar"]) - } - } - - repositories { - maven { - name = "releases" - url = uri("https://repo.polyfrost.cc/releases") - credentials(PasswordCredentials::class) - authentication { - create("basic") - } - } - maven { - name = "snapshots" - url = uri("https://repo.polyfrost.cc/snapshots") - credentials(PasswordCredentials::class) - authentication { - create("basic") - } - } - maven { - name = "private" - url = uri("https://repo.polyfrost.cc/private") - credentials(PasswordCredentials::class) - authentication { - create("basic") - } - } - } } \ No newline at end of file diff --git a/root.gradle.kts b/root.gradle.kts deleted file mode 100644 index 73e3461..0000000 --- a/root.gradle.kts +++ /dev/null @@ -1,10 +0,0 @@ -plugins { - kotlin("jvm") version "1.6.21" apply false - id("gg.essential.multi-version.root") - id("com.github.johnrengelman.shadow") version "7.1.2" apply false - id("io.github.juuxel.loom-quiltflower-mini") version "171a6e2e49" apply false -} - -preprocess { - "1.8.9-forge"(10809, "srg") {} -} \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts index 69f48d4..859b472 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -8,6 +8,8 @@ pluginManagement { plugins { val egtVersion = "0.1.10" id("gg.essential.multi-version.root") version egtVersion + id("gg.essential.defaults.repo") version egtVersion + id("gg.essential.defaults.java") version egtVersion } resolutionStrategy { eachPlugin { @@ -21,15 +23,21 @@ pluginManagement { val mod_name: String by settings rootProject.name = mod_name -rootProject.buildFileName = "root.gradle.kts" + +include(":lwjgl") + +include(":platform") +project(":platform").apply { + projectDir = file("versions/") + buildFileName = "root.gradle.kts" +} listOf( "1.8.9-forge" ).forEach { version -> - include(":$version") - project(":$version").apply { + include(":platform:$version") + project(":platform:$version").apply { projectDir = file("versions/$version") - buildFileName = "../../build.gradle.kts" + buildFileName = "../build.gradle.kts" } } -include(":lwjgl") \ No newline at end of file diff --git a/src/main/java/cc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig.java b/src/main/java/cc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig.java index 1948e0a..97dd0cb 100644 --- a/src/main/java/cc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig.java +++ b/src/main/java/cc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig.java @@ -8,11 +8,11 @@ import cc.polyfrost.oneconfig.config.elements.OptionPage; import cc.polyfrost.oneconfig.config.elements.BasicOption; import cc.polyfrost.oneconfig.config.Config; import cc.polyfrost.oneconfig.gui.elements.config.*; +import cc.polyfrost.oneconfig.platform.Platform; import gg.essential.vigilance.Vigilant; import gg.essential.vigilance.data.*; import kotlin.reflect.KMutableProperty0; import kotlin.reflect.jvm.ReflectJvmMapping; -import net.minecraft.client.resources.I18n; import java.awt.*; import java.lang.reflect.Field; @@ -131,7 +131,7 @@ public class VigilanceConfig extends Config { private String getName(PropertyAttributesExt ext) { try { PropertyAttributesExt.class.getDeclaredField("i18nName").setAccessible(true); - return I18n.format((String) PropertyAttributesExt.class.getDeclaredField("i18nName").get(ext)); + return Platform.getI18nPlatform().format((String) PropertyAttributesExt.class.getDeclaredField("i18nName").get(ext)); } catch (IllegalAccessException | NoSuchFieldException e) { return ext.getName(); } @@ -140,7 +140,7 @@ public class VigilanceConfig extends Config { private String getCategory(PropertyAttributesExt ext) { try { PropertyAttributesExt.class.getDeclaredField("i18nCategory").setAccessible(true); - return I18n.format((String) PropertyAttributesExt.class.getDeclaredField("i18nCategory").get(ext)); + return Platform.getI18nPlatform().format((String) PropertyAttributesExt.class.getDeclaredField("i18nCategory").get(ext)); } catch (IllegalAccessException | NoSuchFieldException e) { return ext.getCategory(); } @@ -149,7 +149,7 @@ public class VigilanceConfig extends Config { private String getSubcategory(PropertyAttributesExt ext) { try { PropertyAttributesExt.class.getDeclaredField("i18nSubcategory").setAccessible(true); - return I18n.format((String) PropertyAttributesExt.class.getDeclaredField("i18nSubcategory").get(ext)); + return Platform.getI18nPlatform().format((String) PropertyAttributesExt.class.getDeclaredField("i18nSubcategory").get(ext)); } catch (IllegalAccessException | NoSuchFieldException e) { return ext.getSubcategory(); } diff --git a/src/main/java/cc/polyfrost/oneconfig/config/profiles/Profiles.java b/src/main/java/cc/polyfrost/oneconfig/config/profiles/Profiles.java index 0f5ce09..29a9daa 100644 --- a/src/main/java/cc/polyfrost/oneconfig/config/profiles/Profiles.java +++ b/src/main/java/cc/polyfrost/oneconfig/config/profiles/Profiles.java @@ -1,9 +1,10 @@ package cc.polyfrost.oneconfig.config.profiles; -import cc.polyfrost.oneconfig.internal.OneConfig; import cc.polyfrost.oneconfig.internal.config.OneConfigConfig; import cc.polyfrost.oneconfig.internal.config.core.ConfigCore; import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; @@ -11,13 +12,14 @@ import java.util.ArrayList; import java.util.Arrays; public class Profiles { + private static final Logger LOGGER = LogManager.getLogger("OneConfig Profiles"); public static final File nonProfileSpecificDir = new File("OneConfig/config"); public static final File profileDir = new File("OneConfig/profiles"); public static ArrayList profiles; public static String getCurrentProfile() { if (!profileDir.exists() && !profileDir.mkdir()) { - OneConfig.LOGGER.fatal("Could not create profiles folder"); + LOGGER.fatal("Could not create profiles folder"); return null; } if (profiles == null) { @@ -33,7 +35,7 @@ public class Profiles { public static void createProfile(String name) { File folder = new File(profileDir, name); if (!folder.exists() && !folder.mkdir()) { - OneConfig.LOGGER.fatal("Could not create profile folder"); + LOGGER.fatal("Could not create profile folder"); return; } profiles.add(name); @@ -58,7 +60,7 @@ public class Profiles { public static void loadProfile(String profile) { ConfigCore.saveAll(); OneConfigConfig.currentProfile = profile; - OneConfig.config.save(); + //OneConfig.config.save(); todo do we actually need this ConfigCore.reInitAll(); } @@ -70,14 +72,14 @@ public class Profiles { profiles.remove(name); profiles.add(newName); } catch (IOException e) { - OneConfig.LOGGER.error("Failed to rename profile"); + LOGGER.error("Failed to rename profile"); } } public static void deleteProfile(String name) { if (name.equals(getCurrentProfile())) { if (profiles.size() == 1) { - OneConfig.LOGGER.error("Cannot delete only profile!"); + LOGGER.error("Cannot delete only profile!"); return; } loadProfile(profiles.stream().filter(entry -> !entry.equals(name)).findFirst().get()); @@ -86,7 +88,7 @@ public class Profiles { FileUtils.deleteDirectory(getProfileDir(name)); profiles.remove(name); } catch (IOException e) { - OneConfig.LOGGER.error("Failed to delete profile"); + LOGGER.error("Failed to delete profile"); } } } diff --git a/src/main/java/cc/polyfrost/oneconfig/events/event/ChatReceiveEvent.java b/src/main/java/cc/polyfrost/oneconfig/events/event/ChatReceiveEvent.java index 616479e..299ce12 100644 --- a/src/main/java/cc/polyfrost/oneconfig/events/event/ChatReceiveEvent.java +++ b/src/main/java/cc/polyfrost/oneconfig/events/event/ChatReceiveEvent.java @@ -1,8 +1,5 @@ package cc.polyfrost.oneconfig.events.event; - -import net.minecraft.util.IChatComponent; - /** * Called when a chat message is received. */ @@ -10,9 +7,13 @@ public class ChatReceiveEvent extends CancellableEvent { /** * The message that was received. */ - public final IChatComponent message; + public final Object message; - public ChatReceiveEvent(IChatComponent message) { + public ChatReceiveEvent(Object message) { this.message = message; } + + public String getFullyUnformattedMessage() { + return ""; + } } diff --git a/src/main/java/cc/polyfrost/oneconfig/events/event/ReceivePacketEvent.java b/src/main/java/cc/polyfrost/oneconfig/events/event/ReceivePacketEvent.java index 17bc16d..f35bd0c 100644 --- a/src/main/java/cc/polyfrost/oneconfig/events/event/ReceivePacketEvent.java +++ b/src/main/java/cc/polyfrost/oneconfig/events/event/ReceivePacketEvent.java @@ -1,11 +1,9 @@ package cc.polyfrost.oneconfig.events.event; -import net.minecraft.network.Packet; - public class ReceivePacketEvent extends CancellableEvent { - public final Packet packet; + public final Object packet; - public ReceivePacketEvent(Packet packet) { + public ReceivePacketEvent(Object packet) { this.packet = packet; } } diff --git a/src/main/java/cc/polyfrost/oneconfig/events/event/ScreenOpenEvent.java b/src/main/java/cc/polyfrost/oneconfig/events/event/ScreenOpenEvent.java index 4593638..daee38b 100644 --- a/src/main/java/cc/polyfrost/oneconfig/events/event/ScreenOpenEvent.java +++ b/src/main/java/cc/polyfrost/oneconfig/events/event/ScreenOpenEvent.java @@ -1,6 +1,5 @@ package cc.polyfrost.oneconfig.events.event; -import net.minecraft.client.gui.GuiScreen; import org.jetbrains.annotations.Nullable; /** @@ -9,9 +8,9 @@ import org.jetbrains.annotations.Nullable; */ public class ScreenOpenEvent extends CancellableEvent { @Nullable - public final GuiScreen screen; + public final Object screen; - public ScreenOpenEvent(@Nullable GuiScreen screen) { + public ScreenOpenEvent(@Nullable Object screen) { this.screen = screen; } } diff --git a/src/main/java/cc/polyfrost/oneconfig/events/event/SendPacketEvent.java b/src/main/java/cc/polyfrost/oneconfig/events/event/SendPacketEvent.java index 3cee784..791f8d6 100644 --- a/src/main/java/cc/polyfrost/oneconfig/events/event/SendPacketEvent.java +++ b/src/main/java/cc/polyfrost/oneconfig/events/event/SendPacketEvent.java @@ -1,11 +1,10 @@ package cc.polyfrost.oneconfig.events.event; -import net.minecraft.network.Packet; public class SendPacketEvent extends CancellableEvent { - public final Packet packet; + public final Object packet; - public SendPacketEvent(Packet packet) { + public SendPacketEvent(Object packet) { this.packet = packet; } } diff --git a/src/main/java/cc/polyfrost/oneconfig/events/event/TimerUpdateEvent.java b/src/main/java/cc/polyfrost/oneconfig/events/event/TimerUpdateEvent.java index a8b88dc..c5f863c 100644 --- a/src/main/java/cc/polyfrost/oneconfig/events/event/TimerUpdateEvent.java +++ b/src/main/java/cc/polyfrost/oneconfig/events/event/TimerUpdateEvent.java @@ -1,23 +1,12 @@ package cc.polyfrost.oneconfig.events.event; -import net.minecraft.util.Timer; - -/** - * Called when the {@link Timer} is updated. - * Can be used as an alternative to getting instances of {@link Timer} - * via Mixin or Access Wideners / Transformers - */ public class TimerUpdateEvent { - /** - * Whether the deltaTicks / renderPartialTicks was updated - */ + public final boolean updatedDeltaTicks; - /** - * The {@link Timer} instance - */ - public final Timer timer; - public TimerUpdateEvent(Timer timer, boolean updatedDeltaTicks) { + public final Object timer; + + public TimerUpdateEvent(Object timer, boolean updatedDeltaTicks) { this.timer = timer; this.updatedDeltaTicks = updatedDeltaTicks; } diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/GuiPause.java b/src/main/java/cc/polyfrost/oneconfig/gui/GuiPause.java new file mode 100644 index 0000000..44b2b5c --- /dev/null +++ b/src/main/java/cc/polyfrost/oneconfig/gui/GuiPause.java @@ -0,0 +1,9 @@ +package cc.polyfrost.oneconfig.gui; + +/** + * Hack that allows GUIs to set whether the game should pause when the GUI is displayed without depending on + * Minecraft itself. + */ +public interface GuiPause { + boolean doesGuiPauseGame(); +} diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/HudGui.java b/src/main/java/cc/polyfrost/oneconfig/gui/HudGui.java index b13170a..2c3e681 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/HudGui.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/HudGui.java @@ -3,6 +3,7 @@ package cc.polyfrost.oneconfig.gui; import cc.polyfrost.oneconfig.internal.config.core.ConfigCore; import cc.polyfrost.oneconfig.hud.Hud; import cc.polyfrost.oneconfig.internal.hud.HudCore; +import cc.polyfrost.oneconfig.libs.universal.UResolution; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.libs.universal.UKeyboard; import cc.polyfrost.oneconfig.libs.universal.UMatrixStack; @@ -13,7 +14,7 @@ import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.ArrayList; -public class HudGui extends UScreen { +public class HudGui extends UScreen implements GuiPause { private Hud editingHud; private boolean isDragging; private boolean isScaling; @@ -29,7 +30,7 @@ public class HudGui extends UScreen { @Override public void onDrawScreen(@NotNull UMatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { - RenderManager.drawGlRect(0, 0, this.width, this.height, new Color(80, 80, 80, 50).getRGB()); + RenderManager.drawGlRect(0, 0, UResolution.getScaledWidth(), UResolution.getScaledHeight(), new Color(80, 80, 80, 50).getRGB()); if (isDragging) { setPosition(mouseX - xOffset, mouseY - yOffset, true); @@ -42,8 +43,8 @@ public class HudGui extends UScreen { private void processHud(Hud hud, int mouseX) { if (hud == editingHud && isScaling) { - float xFloat = hud.getXScaled(this.width); - float yFloat = hud.getYScaled(this.height); + float xFloat = hud.getXScaled(UResolution.getScaledWidth()); + float yFloat = hud.getYScaled(UResolution.getScaledHeight()); float pos = getXSnapping(mouseX, true); float newWidth = pos - xFloat; float newScale = newWidth / ((hud.getWidth(hud.scale) + hud.paddingX * hud.scale) / hud.scale); @@ -53,16 +54,16 @@ public class HudGui extends UScreen { newScale = 0.3f; hud.scale = newScale; - if (xFloat / this.width > 0.5) - editingHud.xUnscaled = (xFloat + (hud.getWidth(hud.scale) + hud.paddingX * hud.scale)) / (double) this.width; - if (yFloat / this.height > 0.5) - editingHud.yUnscaled = (yFloat + (hud.getHeight(hud.scale) + hud.paddingY * hud.scale)) / (double) this.height; + if (xFloat / UResolution.getScaledWidth() > 0.5) + editingHud.xUnscaled = (xFloat + (hud.getWidth(hud.scale) + hud.paddingX * hud.scale)) / (double) UResolution.getScaledWidth(); + if (yFloat / UResolution.getScaledHeight() > 0.5) + editingHud.yUnscaled = (yFloat + (hud.getHeight(hud.scale) + hud.paddingY * hud.scale)) / (double) UResolution.getScaledHeight(); } int width = (int) (hud.getExampleWidth(hud.scale) + hud.paddingX * hud.scale); int height = (int) (hud.getExampleHeight(hud.scale) + hud.paddingY * hud.scale); - int x = (int) hud.getXScaled(this.width); - int y = (int) hud.getYScaled(this.height); + int x = (int) hud.getXScaled(UResolution.getScaledWidth()); + int y = (int) hud.getYScaled(UResolution.getScaledHeight()); hud.drawExampleAll(x, y, hud.scale, true); int color = new Color(215, 224, 235).getRGB(); @@ -90,12 +91,12 @@ public class HudGui extends UScreen { if (newX < 0) newX = 0; - else if (newX + width > this.width) - newX = this.width - width; + else if (newX + width > UResolution.getScaledWidth()) + newX = UResolution.getScaledWidth() - width; if (newY < 0) newY = 0; - else if (newY + height > this.height) - newY = this.height - height; + else if (newY + height > UResolution.getScaledHeight()) + newY = UResolution.getScaledHeight() - height; if (snap) { float snapX = getXSnapping(newX, false); @@ -106,14 +107,14 @@ public class HudGui extends UScreen { } } - if (newX / this.width <= 0.5) - editingHud.xUnscaled = newX / (double) this.width; + if (newX / UResolution.getScaledWidth() <= 0.5) + editingHud.xUnscaled = newX / (double) UResolution.getScaledWidth(); else - editingHud.xUnscaled = (newX + width) / (double) this.width; - if (newY / this.height <= 0.5) - editingHud.yUnscaled = newY / (double) this.height; + editingHud.xUnscaled = (newX + width) / (double) UResolution.getScaledWidth(); + if (newY / UResolution.getScaledHeight() <= 0.5) + editingHud.yUnscaled = newY / (double) UResolution.getScaledHeight(); else - editingHud.yUnscaled = (newY + height) / (double) this.height; + editingHud.yUnscaled = (newY + height) / (double) UResolution.getScaledHeight(); } private float getXSnapping(float pos, boolean rightOnly) { @@ -124,7 +125,7 @@ public class HudGui extends UScreen { verticalLines.addAll(getXSnappingHud(hud)); } getSpaceSnapping(verticalLines); - verticalLines.add(this.width / 2f); + verticalLines.add(UResolution.getScaledWidth() / 2f); float smallestDiff = -1; float smallestLine = 0; float smallestOffset = 0; @@ -139,7 +140,7 @@ public class HudGui extends UScreen { } if (smallestDiff != -1) { float finalSmallestLine = smallestLine; - RenderManager.setupAndDraw(true, (vg) -> RenderManager.drawLine(vg, finalSmallestLine, 0, finalSmallestLine, this.height, 1, new Color(255, 255, 255).getRGB())); + RenderManager.setupAndDraw(true, (vg) -> RenderManager.drawLine(vg, finalSmallestLine, 0, finalSmallestLine, UResolution.getScaledHeight(), 1, new Color(255, 255, 255).getRGB())); return smallestLine - smallestOffset; } return pos; @@ -149,7 +150,7 @@ public class HudGui extends UScreen { ArrayList verticalLines = new ArrayList<>(); if (hud == editingHud) return verticalLines; int hudWidth = (int) (hud.getWidth(hud.scale) + hud.paddingX * hud.scale); - int hudX = (int) hud.getXScaled(this.width); + int hudX = (int) hud.getXScaled(UResolution.getScaledWidth()); verticalLines.add((float) hudX); verticalLines.add((float) (hudX + hudWidth)); return verticalLines; @@ -163,7 +164,7 @@ public class HudGui extends UScreen { horizontalLines.addAll(getYSnappingHud(hud)); } getSpaceSnapping(horizontalLines); - horizontalLines.add(this.height / 2f); + horizontalLines.add(UResolution.getScaledHeight() / 2f); float smallestDiff = -1; float smallestLine = 0; float smallestOffset = 0; @@ -178,7 +179,7 @@ public class HudGui extends UScreen { } if (smallestDiff != -1) { float finalSmallestLine = smallestLine; - RenderManager.setupAndDraw(true, (vg) -> RenderManager.drawLine(vg, 0, finalSmallestLine, this.width, finalSmallestLine, 1, new Color(255, 255, 255).getRGB())); + RenderManager.setupAndDraw(true, (vg) -> RenderManager.drawLine(vg, 0, finalSmallestLine, UResolution.getScaledWidth(), finalSmallestLine, 1, new Color(255, 255, 255).getRGB())); return smallestLine - smallestOffset; } return pos; @@ -188,7 +189,7 @@ public class HudGui extends UScreen { ArrayList horizontalLines = new ArrayList<>(); if (hud == editingHud) return horizontalLines; int hudHeight = (int) (hud.getHeight(hud.scale) + hud.paddingY * hud.scale); - int hudY = (int) hud.getYScaled(this.height); + int hudY = (int) hud.getYScaled(UResolution.getScaledHeight()); horizontalLines.add((float) hudY); horizontalLines.add((float) (hudY + hudHeight)); return horizontalLines; @@ -212,8 +213,8 @@ public class HudGui extends UScreen { if (editingHud != null) { int width = (int) (editingHud.getWidth(editingHud.scale) + editingHud.paddingX * editingHud.scale); int height = (int) (editingHud.getHeight(editingHud.scale) + editingHud.paddingY * editingHud.scale); - float x = editingHud.getXScaled(this.width); - float y = editingHud.getYScaled(this.height); + float x = editingHud.getXScaled(UResolution.getScaledWidth()); + float y = editingHud.getYScaled(UResolution.getScaledHeight()); if (mouseX >= x + width - 3 && mouseX <= x + width + 3 && mouseY >= y + height - 3 && mouseY <= y + height + 3) { isScaling = true; return; @@ -231,8 +232,8 @@ public class HudGui extends UScreen { private boolean mouseClickedHud(Hud hud, int mouseX, int mouseY) { int width = (int) (hud.getWidth(hud.scale) + hud.paddingX * hud.scale); int height = (int) (hud.getHeight(hud.scale) + hud.paddingY * hud.scale); - float x = hud.getXScaled(this.width); - float y = hud.getYScaled(this.height); + float x = hud.getXScaled(UResolution.getScaledWidth()); + float y = hud.getYScaled(UResolution.getScaledHeight()); if (mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height) { editingHud = hud; xOffset = (int) (mouseX - x); @@ -253,8 +254,8 @@ public class HudGui extends UScreen { @Override public void onKeyPressed(int keyCode, char typedChar, @Nullable UKeyboard.Modifiers modifiers) { if (editingHud != null) { - float x = editingHud.getXScaled(this.width); - float y = editingHud.getYScaled(this.height); + float x = editingHud.getXScaled(UResolution.getScaledWidth()); + float y = editingHud.getYScaled(UResolution.getScaledHeight()); if (keyCode == UKeyboard.KEY_UP) { setPosition(x, y - 1, false); } else if (keyCode == UKeyboard.KEY_DOWN) { diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/OneConfigGui.java b/src/main/java/cc/polyfrost/oneconfig/gui/OneConfigGui.java index fd3c86b..35946e0 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/OneConfigGui.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/OneConfigGui.java @@ -8,7 +8,6 @@ import cc.polyfrost.oneconfig.gui.elements.ColorSelector; import cc.polyfrost.oneconfig.gui.elements.text.TextInputField; import cc.polyfrost.oneconfig.gui.pages.ModsPage; import cc.polyfrost.oneconfig.gui.pages.Page; -import cc.polyfrost.oneconfig.internal.OneConfig; import cc.polyfrost.oneconfig.internal.assets.Colors; import cc.polyfrost.oneconfig.internal.assets.SVGs; import cc.polyfrost.oneconfig.internal.config.OneConfigConfig; @@ -17,6 +16,7 @@ import cc.polyfrost.oneconfig.libs.universal.UKeyboard; import cc.polyfrost.oneconfig.libs.universal.UMatrixStack; import cc.polyfrost.oneconfig.libs.universal.UResolution; import cc.polyfrost.oneconfig.libs.universal.UScreen; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; import cc.polyfrost.oneconfig.renderer.scissor.Scissor; @@ -26,12 +26,11 @@ import cc.polyfrost.oneconfig.utils.color.ColorPalette; import cc.polyfrost.oneconfig.utils.gui.GuiUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.lwjgl.input.Mouse; import org.lwjgl.nanovg.NanoVG; import java.util.ArrayList; -public class OneConfigGui extends UScreen { +public class OneConfigGui extends UScreen implements GuiPause { public static OneConfigGui INSTANCE; public static OneConfigGui instanceToRestore = null; private final SideBar sideBar = new SideBar(); @@ -110,7 +109,7 @@ public class OneConfigGui extends UScreen { RenderManager.setAlpha(vg, 0.5f); } else { backArrow.disable(false); - if (!backArrow.isHovered() || Mouse.isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); + if (!backArrow.isHovered() || Platform.getMousePlatform().isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); } RenderManager.drawSvg(vg, SVGs.CARET_LEFT, x + 246, y + 22, 28, 28); RenderManager.setAlpha(vg, 1f); @@ -119,7 +118,7 @@ public class OneConfigGui extends UScreen { RenderManager.setAlpha(vg, 0.5f); } else { forwardArrow.disable(false); - if (!forwardArrow.isHovered() || Mouse.isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); + if (!forwardArrow.isHovered() || Platform.getMousePlatform().isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); } RenderManager.drawSvg(vg, SVGs.CARET_RIGHT, x + 294, y + 22, 28, 28); RenderManager.setAlpha(vg, 1f); @@ -167,7 +166,7 @@ public class OneConfigGui extends UScreen { boolean hovered = InputUtils.isAreaHovered((int) breadcrumbX, y + 24, (int) width, 36); int color = Colors.WHITE_60; if (i == currentPage.parents.size() - 1) color = Colors.WHITE; - else if (hovered && !Mouse.isButtonDown(0)) color = Colors.WHITE_80; + else if (hovered && !Platform.getMousePlatform().isButtonDown(0)) color = Colors.WHITE_80; RenderManager.drawText(vg, title, breadcrumbX, y + 38, color, 24f, Fonts.SEMIBOLD); if (i != 0) RenderManager.drawSvg(vg, SVGs.CARET_RIGHT, breadcrumbX - 28, y + 25, 24, 24, color); @@ -182,7 +181,7 @@ public class OneConfigGui extends UScreen { currentColorSelector.draw(vg); } }); - mouseDown = Mouse.isButtonDown(0); + mouseDown = Platform.getMousePlatform().isButtonDown(0); } @Override @@ -194,7 +193,7 @@ public class OneConfigGui extends UScreen { if (currentColorSelector != null) currentColorSelector.keyTyped(typedChar, keyCode); currentPage.keyTyped(typedChar, keyCode); } catch (Exception e) { - OneConfig.LOGGER.error("Error while processing keyboard input; ignoring!"); + e.printStackTrace(); } } @@ -273,11 +272,6 @@ public class OneConfigGui extends UScreen { return textInputField.getInput(); } - @Override - public boolean doesGuiPauseGame() { - return false; - } - @Override public void onScreenClose() { currentPage.finishUpAndClose(); @@ -285,4 +279,9 @@ public class OneConfigGui extends UScreen { INSTANCE = null; super.onScreenClose(); } + + @Override + public boolean doesGuiPauseGame() { + return false; + } } diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/SideBar.java b/src/main/java/cc/polyfrost/oneconfig/gui/SideBar.java index f6ce543..df3330d 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/SideBar.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/SideBar.java @@ -7,13 +7,13 @@ import cc.polyfrost.oneconfig.gui.elements.BasicButton; import cc.polyfrost.oneconfig.gui.pages.CreditsPage; import cc.polyfrost.oneconfig.gui.pages.ModConfigPage; import cc.polyfrost.oneconfig.gui.pages.ModsPage; -import cc.polyfrost.oneconfig.internal.OneConfig; import cc.polyfrost.oneconfig.internal.assets.Colors; +import cc.polyfrost.oneconfig.internal.assets.SVGs; +import cc.polyfrost.oneconfig.internal.config.Preferences; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; -import cc.polyfrost.oneconfig.internal.assets.SVGs; -import cc.polyfrost.oneconfig.utils.gui.GuiUtils; import cc.polyfrost.oneconfig.utils.color.ColorPalette; +import cc.polyfrost.oneconfig.utils.gui.GuiUtils; import java.util.ArrayList; @@ -42,7 +42,7 @@ public class SideBar { public SideBar() { buttons.get(0).setClickAction(new CreditsPage()); buttons.get(2).setClickAction(new ModsPage()); - buttons.get(8).setClickAction(new ModConfigPage(OneConfig.preferences.mod.defaultPage, true)); + buttons.get(8).setClickAction(new ModConfigPage(Preferences.getInstance().mod.defaultPage, true)); HUDButton.setClickAction(() -> GuiUtils.displayScreen(new HudGui())); CloseButton.setClickAction(GuiUtils::closeScreen); for (BasicButton button : buttons) { diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/elements/BasicElement.java b/src/main/java/cc/polyfrost/oneconfig/gui/elements/BasicElement.java index 56eac2d..6f203c4 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/elements/BasicElement.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/elements/BasicElement.java @@ -1,11 +1,11 @@ package cc.polyfrost.oneconfig.gui.elements; import cc.polyfrost.oneconfig.gui.animations.ColorAnimation; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.utils.InputUtils; import cc.polyfrost.oneconfig.utils.color.ColorPalette; import org.jetbrains.annotations.NotNull; -import org.lwjgl.input.Mouse; public class BasicElement { protected int width, height; @@ -93,7 +93,7 @@ public class BasicElement { clicked = false; } else { hovered = InputUtils.isAreaHovered(x - hitBoxX, y - hitBoxY, width + hitBoxX, height + hitBoxY); - pressed = hovered && Mouse.isButtonDown(0); + pressed = hovered && Platform.getMousePlatform().isButtonDown(0); clicked = InputUtils.isClicked(block) && hovered; if (clicked) { diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/elements/ColorSelector.java b/src/main/java/cc/polyfrost/oneconfig/gui/elements/ColorSelector.java index 668fdb3..1fed640 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/elements/ColorSelector.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/elements/ColorSelector.java @@ -12,6 +12,7 @@ import cc.polyfrost.oneconfig.internal.assets.Colors; import cc.polyfrost.oneconfig.internal.assets.Images; import cc.polyfrost.oneconfig.internal.assets.SVGs; import cc.polyfrost.oneconfig.internal.config.OneConfigConfig; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; import cc.polyfrost.oneconfig.renderer.scissor.Scissor; @@ -20,7 +21,6 @@ import cc.polyfrost.oneconfig.utils.IOUtils; import cc.polyfrost.oneconfig.utils.InputUtils; import cc.polyfrost.oneconfig.utils.NetworkUtils; import cc.polyfrost.oneconfig.utils.color.ColorPalette; -import org.lwjgl.input.Mouse; import java.awt.*; import java.util.ArrayList; @@ -203,7 +203,7 @@ public class ColorSelector { inputScissor = InputUtils.blockInputArea(x - 3, y - 3, width + 6, height + 6); ScissorManager.resetScissor(vg, scissor); - mouseWasDown = Mouse.isButtonDown(0); + mouseWasDown = Platform.getMousePlatform().isButtonDown(0); if (closeBtn.isClicked()) { OneConfigGui.INSTANCE.closeColorSelector(); } @@ -241,9 +241,9 @@ public class ColorSelector { } private void doDrag() { - if (InputUtils.isAreaHovered(x, y, 368, 64) && Mouse.isButtonDown(0) && !dragging) { - int dx = (int) (Mouse.getDX() / (OneConfigGui.INSTANCE == null ? 1 : OneConfigGui.INSTANCE.getScaleFactor())); - int dy = (int) (Mouse.getDY() / (OneConfigGui.INSTANCE == null ? 1 : OneConfigGui.INSTANCE.getScaleFactor())); + if (InputUtils.isAreaHovered(x, y, 368, 64) && Platform.getMousePlatform().isButtonDown(0) && !dragging) { + int dx = (int) (Platform.getMousePlatform().getMouseDX() / (OneConfigGui.INSTANCE == null ? 1 : OneConfigGui.INSTANCE.getScaleFactor())); + int dy = (int) (Platform.getMousePlatform().getMouseDY() / (OneConfigGui.INSTANCE == null ? 1 : OneConfigGui.INSTANCE.getScaleFactor())); x += dx; mouseX += dx; y -= dy; @@ -252,8 +252,8 @@ public class ColorSelector { } private void setColorFromXY() { - boolean isMouseDown = Mouse.isButtonDown(0); - boolean hovered = Mouse.isButtonDown(0) && InputUtils.isAreaHovered(x + 16, y + 120, 384, 288); + boolean isMouseDown = Platform.getMousePlatform().isButtonDown(0); + boolean hovered = Platform.getMousePlatform().isButtonDown(0) && InputUtils.isAreaHovered(x + 16, y + 120, 384, 288); if (hovered && isMouseDown && !mouseWasDown) dragging = true; switch (mode) { case 0: @@ -282,8 +282,8 @@ public class ColorSelector { int circleCenterX = x + 208; int circleCenterY = y + 264; double squareDist = Math.pow((circleCenterX - InputUtils.mouseX()), 2) + Math.pow((circleCenterY - InputUtils.mouseY()), 2); - hovered = squareDist < 144 * 144 && Mouse.isButtonDown(0); - isMouseDown = Mouse.isButtonDown(0); + hovered = squareDist < 144 * 144 && Platform.getMousePlatform().isButtonDown(0); + isMouseDown = Platform.getMousePlatform().isButtonDown(0); if (hovered && isMouseDown && !mouseWasDown) dragging = true; int angle = 0; diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/elements/ModCard.java b/src/main/java/cc/polyfrost/oneconfig/gui/elements/ModCard.java index 2938c41..eebdba1 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/elements/ModCard.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/elements/ModCard.java @@ -5,11 +5,11 @@ import cc.polyfrost.oneconfig.gui.OneConfigGui; import cc.polyfrost.oneconfig.gui.animations.ColorAnimation; import cc.polyfrost.oneconfig.gui.pages.ModConfigPage; import cc.polyfrost.oneconfig.gui.pages.ModsPage; -import cc.polyfrost.oneconfig.internal.OneConfig; import cc.polyfrost.oneconfig.internal.assets.Colors; import cc.polyfrost.oneconfig.internal.assets.SVGs; import cc.polyfrost.oneconfig.internal.config.OneConfigConfig; import cc.polyfrost.oneconfig.internal.config.core.ConfigCore; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; import cc.polyfrost.oneconfig.renderer.scissor.Scissor; @@ -18,7 +18,6 @@ import cc.polyfrost.oneconfig.utils.InputUtils; import cc.polyfrost.oneconfig.utils.color.ColorPalette; import cc.polyfrost.oneconfig.utils.color.ColorUtils; import org.jetbrains.annotations.NotNull; -import org.lwjgl.input.Mouse; public class ModCard extends BasicElement { private final Mod modData; @@ -51,8 +50,8 @@ public class ModCard extends BasicElement { isHoveredMain = InputUtils.isAreaHovered(x, y, width, 87); boolean isHoveredSecondary = InputUtils.isAreaHovered(x, y + 87, width - 32, 32) && !disabled; if (disabled) RenderManager.setAlpha(vg, 0.5f); - RenderManager.drawRoundedRectVaried(vg, x, y, width, 87, colorFrame.getColor(isHoveredMain, isHoveredMain && Mouse.isButtonDown(0)), 12f, 12f, 0f, 0f); - RenderManager.drawRoundedRectVaried(vg, x, y + 87, width, 32, colorToggle.getColor(isHoveredSecondary, isHoveredSecondary && Mouse.isButtonDown(0)), 0f, 0f, 12f, 12f); + RenderManager.drawRoundedRectVaried(vg, x, y, width, 87, colorFrame.getColor(isHoveredMain, isHoveredMain && Platform.getMousePlatform().isButtonDown(0)), 12f, 12f, 0f, 0f); + RenderManager.drawRoundedRectVaried(vg, x, y + 87, width, 32, colorToggle.getColor(isHoveredSecondary, isHoveredSecondary && Platform.getMousePlatform().isButtonDown(0)), 0f, 0f, 12f, 12f); RenderManager.drawLine(vg, x, y + 86, x + width, y + 86, 2, Colors.GRAY_300); if (modData.modIcon != null) { if (modData.modIcon.toLowerCase().endsWith(".svg")) @@ -68,7 +67,6 @@ public class ModCard extends BasicElement { else OneConfigConfig.favoriteMods.remove(modData.name); ConfigCore.sortMods(); page.reloadMods(); - OneConfig.config.save(); } Scissor scissor2 = ScissorManager.scissor(vg, x, y + 87, width - 32, 32); RenderManager.drawText(vg, cleanName, x + 12, y + 103, ColorUtils.setAlpha(Colors.WHITE, (int) (colorToggle.getAlpha() * 255)), 14f, Fonts.MEDIUM); diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/elements/Slider.java b/src/main/java/cc/polyfrost/oneconfig/gui/elements/Slider.java index 8c9dfb6..dda5621 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/elements/Slider.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/elements/Slider.java @@ -1,9 +1,9 @@ package cc.polyfrost.oneconfig.gui.elements; import cc.polyfrost.oneconfig.internal.assets.Colors; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.utils.InputUtils; -import org.lwjgl.input.Mouse; public class Slider extends BasicElement { private final float min, max; @@ -34,7 +34,7 @@ public class Slider extends BasicElement { public void update(int x, int y) { super.update(x, y); - boolean isMouseDown = Mouse.isButtonDown(0); + boolean isMouseDown = Platform.getMousePlatform().isButtonDown(0); boolean hovered = InputUtils.isAreaHovered(x - 6, y - 3, width + 12, height + 6); if (hovered && isMouseDown && !mouseWasDown) dragging = true; mouseWasDown = isMouseDown; diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigCheckbox.java b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigCheckbox.java index 0ff7d8f..51303c6 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigCheckbox.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigCheckbox.java @@ -7,13 +7,13 @@ import cc.polyfrost.oneconfig.gui.animations.Animation; import cc.polyfrost.oneconfig.gui.animations.ColorAnimation; import cc.polyfrost.oneconfig.gui.animations.DummyAnimation; import cc.polyfrost.oneconfig.gui.animations.EaseInOutQuad; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; import cc.polyfrost.oneconfig.internal.assets.SVGs; import cc.polyfrost.oneconfig.utils.InputUtils; import cc.polyfrost.oneconfig.utils.color.ColorPalette; import cc.polyfrost.oneconfig.utils.color.ColorUtils; -import org.lwjgl.input.Mouse; import java.awt.*; import java.lang.reflect.Field; @@ -57,7 +57,7 @@ public class ConfigCheckbox extends BasicOption { RenderManager.drawText(vg, name, x + 32, y + 17, Colors.WHITE_90, 14f, Fonts.MEDIUM); - RenderManager.drawRoundedRect(vg, x, y + 4, 24, 24, color.getColor(hover, hover && Mouse.isButtonDown(0)), 6f); + RenderManager.drawRoundedRect(vg, x, y + 4, 24, 24, color.getColor(hover, hover && Platform.getMousePlatform().isButtonDown(0)), 6f); RenderManager.drawHollowRoundRect(vg, x, y + 4, 23.5f, 23.5f, Colors.GRAY_300, 6f, 1f); // the 0.5f is to make it look better ok RenderManager.drawRoundedRect(vg, x, y + 4, 24, 24, ColorUtils.setAlpha(Colors.PRIMARY_500, (int) (percentOn * 255)), 6f); diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigDropdown.java b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigDropdown.java index 26d7348..ddcf6eb 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigDropdown.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigDropdown.java @@ -4,13 +4,13 @@ import cc.polyfrost.oneconfig.config.annotations.Dropdown; import cc.polyfrost.oneconfig.internal.assets.Colors; import cc.polyfrost.oneconfig.config.elements.BasicOption; import cc.polyfrost.oneconfig.gui.animations.ColorAnimation; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; import cc.polyfrost.oneconfig.internal.assets.SVGs; import cc.polyfrost.oneconfig.renderer.scissor.Scissor; import cc.polyfrost.oneconfig.utils.InputUtils; import cc.polyfrost.oneconfig.utils.color.ColorPalette; -import org.lwjgl.input.Mouse; import java.awt.*; import java.lang.reflect.Field; @@ -58,14 +58,14 @@ public class ConfigDropdown extends BasicOption { } catch (IllegalAccessException ignored) { } - if (hovered && Mouse.isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); + if (hovered && Platform.getMousePlatform().isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); if (size == 1) { - RenderManager.drawRoundedRect(vg, x + 224, y, 256, 32, backgroundColor.getColor(hovered, hovered && Mouse.isButtonDown(0)), 12); + RenderManager.drawRoundedRect(vg, x + 224, y, 256, 32, backgroundColor.getColor(hovered, hovered && Platform.getMousePlatform().isButtonDown(0)), 12); RenderManager.drawText(vg, options[selected], x + 236, y + 16, Colors.WHITE_80, 14f, Fonts.MEDIUM); RenderManager.drawRoundedRect(vg, x + 452, y + 4, 24, 24, atomColor.getColor(hovered, false), 8); RenderManager.drawSvg(vg, SVGs.DROPDOWN_LIST, x + 452, y + 4, 24, 24); } else { - RenderManager.drawRoundedRect(vg, x + 352, y, 640, 32, backgroundColor.getColor(hovered, hovered && Mouse.isButtonDown(0)), 12); + RenderManager.drawRoundedRect(vg, x + 352, y, 640, 32, backgroundColor.getColor(hovered, hovered && Platform.getMousePlatform().isButtonDown(0)), 12); RenderManager.drawText(vg, options[selected], x + 364, y + 16, Colors.WHITE_80, 14f, Fonts.MEDIUM); RenderManager.drawRoundedRect(vg, x + 964, y + 4, 24, 24, atomColor.getColor(hovered, false), 8); RenderManager.drawSvg(vg, SVGs.DROPDOWN_LIST, x + 964, y + 4, 24, 24); @@ -87,11 +87,11 @@ public class ConfigDropdown extends BasicOption { } catch (IllegalAccessException ignored) { } - if (hovered && Mouse.isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); + if (hovered && Platform.getMousePlatform().isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); if (size == 1) { - RenderManager.drawRoundedRect(vg, x + 224, y, 256, 32, backgroundColor.getColor(hovered, hovered && Mouse.isButtonDown(0)), 12); + RenderManager.drawRoundedRect(vg, x + 224, y, 256, 32, backgroundColor.getColor(hovered, hovered && Platform.getMousePlatform().isButtonDown(0)), 12); RenderManager.drawText(vg, options[selected], x + 236, y + 16, Colors.WHITE_80, 14f, Fonts.MEDIUM); - if (hovered && Mouse.isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); + if (hovered && Platform.getMousePlatform().isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); RenderManager.drawRoundedRect(vg, x + 452, y + 4, 24, 24, atomColor.getColor(hovered, false), 8); RenderManager.drawSvg(vg, SVGs.DROPDOWN_LIST, x + 452, y + 4, 24, 24); @@ -102,7 +102,7 @@ public class ConfigDropdown extends BasicOption { for (String option : options) { int color = Colors.WHITE_80; boolean optionHovered = InputUtils.isAreaHovered(x + 224, optionY, 252, 32, true); - if (optionHovered && Mouse.isButtonDown(0)) { + if (optionHovered && Platform.getMousePlatform().isButtonDown(0)) { RenderManager.drawRoundedRect(vg, x + 228, optionY + 2, 248, 28, Colors.PRIMARY_700_80, 8); } else if (optionHovered) { RenderManager.drawRoundedRect(vg, x + 228, optionY + 2, 248, 28, Colors.PRIMARY_700, 8); @@ -122,9 +122,9 @@ public class ConfigDropdown extends BasicOption { optionY += 32; } } else { - RenderManager.drawRoundedRect(vg, x + 352, y, 640, 32, backgroundColor.getColor(hovered, hovered && Mouse.isButtonDown(0)), 12); + RenderManager.drawRoundedRect(vg, x + 352, y, 640, 32, backgroundColor.getColor(hovered, hovered && Platform.getMousePlatform().isButtonDown(0)), 12); RenderManager.drawText(vg, options[selected], x + 364, y + 16, Colors.WHITE_80, 14f, Fonts.MEDIUM); - if (hovered && Mouse.isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); + if (hovered && Platform.getMousePlatform().isButtonDown(0)) RenderManager.setAlpha(vg, 0.8f); RenderManager.drawRoundedRect(vg, x + 964, y + 4, 24, 24, atomColor.getColor(hovered, false), 8); RenderManager.drawSvg(vg, SVGs.DROPDOWN_LIST, x + 964, y + 4, 24, 24); @@ -135,7 +135,7 @@ public class ConfigDropdown extends BasicOption { for (String option : options) { int color = Colors.WHITE_80; boolean optionHovered = InputUtils.isAreaHovered(x + 352, optionY, 640, 36, true); - if (optionHovered && Mouse.isButtonDown(0)) { + if (optionHovered && Platform.getMousePlatform().isButtonDown(0)) { RenderManager.drawRoundedRect(vg, x + 356, optionY + 2, 632, 28, Colors.PRIMARY_700_80, 8); } else if (optionHovered) { RenderManager.drawRoundedRect(vg, x + 356, optionY + 2, 632, 28, Colors.PRIMARY_700, 8); diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigPageButton.java b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigPageButton.java index b85d113..ece2888 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigPageButton.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigPageButton.java @@ -6,12 +6,12 @@ import cc.polyfrost.oneconfig.config.elements.BasicOption; import cc.polyfrost.oneconfig.gui.OneConfigGui; import cc.polyfrost.oneconfig.gui.animations.ColorAnimation; import cc.polyfrost.oneconfig.gui.pages.ModConfigPage; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; import cc.polyfrost.oneconfig.internal.assets.SVGs; import cc.polyfrost.oneconfig.utils.InputUtils; import cc.polyfrost.oneconfig.utils.color.ColorPalette; -import org.lwjgl.input.Mouse; import java.lang.reflect.Field; @@ -34,7 +34,7 @@ public class ConfigPageButton extends BasicOption { if (!isEnabled()) RenderManager.setAlpha(vg, 0.5f); - RenderManager.drawRoundedRect(vg, x - 16, y, 1024, height, backgroundColor.getColor(hovered, hovered && Mouse.isButtonDown(0)), 20); + RenderManager.drawRoundedRect(vg, x - 16, y, 1024, height, backgroundColor.getColor(hovered, hovered && Platform.getMousePlatform().isButtonDown(0)), 20); RenderManager.drawText(vg, name, x + 10, y + 32, Colors.WHITE_90, 24, Fonts.MEDIUM); if (!description.equals("")) RenderManager.drawText(vg, name, x + 10, y + 70, Colors.WHITE_90, 14, Fonts.MEDIUM); diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigSlider.java b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigSlider.java index bd02d21..da10756 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigSlider.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigSlider.java @@ -4,11 +4,11 @@ import cc.polyfrost.oneconfig.config.annotations.Slider; import cc.polyfrost.oneconfig.internal.assets.Colors; import cc.polyfrost.oneconfig.config.elements.BasicOption; import cc.polyfrost.oneconfig.gui.elements.text.NumberInputField; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; import cc.polyfrost.oneconfig.utils.InputUtils; import cc.polyfrost.oneconfig.utils.MathUtils; -import org.lwjgl.input.Mouse; import java.lang.reflect.Field; @@ -40,7 +40,7 @@ public class ConfigSlider extends BasicOption { boolean hovered = InputUtils.isAreaHovered(x + 352, y, 512, 32) && isEnabled(); inputField.disable(!isEnabled()); if (!isEnabled()) RenderManager.setAlpha(vg, 0.5f); - boolean isMouseDown = Mouse.isButtonDown(0); + boolean isMouseDown = Platform.getMousePlatform().isButtonDown(0); if (hovered && isMouseDown && !mouseWasDown) dragging = true; mouseWasDown = isMouseDown; if (dragging) { diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigSwitch.java b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigSwitch.java index 68e5be3..4b0c117 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigSwitch.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigSwitch.java @@ -7,11 +7,11 @@ import cc.polyfrost.oneconfig.gui.animations.Animation; import cc.polyfrost.oneconfig.gui.animations.ColorAnimation; import cc.polyfrost.oneconfig.gui.animations.DummyAnimation; import cc.polyfrost.oneconfig.gui.animations.EaseInOutQuad; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; import cc.polyfrost.oneconfig.utils.InputUtils; import cc.polyfrost.oneconfig.utils.color.ColorPalette; -import org.lwjgl.input.Mouse; import java.lang.reflect.Field; @@ -43,7 +43,7 @@ public class ConfigSwitch extends BasicOption { int x2 = x + 3 + (int) (percentOn * 18); boolean hovered = InputUtils.isAreaHovered(x, y, 42, 32); if (!isEnabled()) RenderManager.setAlpha(vg, 0.5f); - RenderManager.drawRoundedRect(vg, x, y + 4, 42, 24, color.getColor(hovered, hovered && Mouse.isButtonDown(0)), 12f); + RenderManager.drawRoundedRect(vg, x, y + 4, 42, 24, color.getColor(hovered, hovered && Platform.getMousePlatform().isButtonDown(0)), 12f); RenderManager.drawRoundedRect(vg, x2, y + 7, 18, 18, Colors.WHITE, 9f); RenderManager.drawText(vg, name, x + 50, y + 17, Colors.WHITE, 14f, Fonts.MEDIUM); diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigTextBox.java b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigTextBox.java index 81de9ba..3d9602b 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigTextBox.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/elements/config/ConfigTextBox.java @@ -4,11 +4,11 @@ import cc.polyfrost.oneconfig.config.annotations.Text; import cc.polyfrost.oneconfig.internal.assets.Colors; import cc.polyfrost.oneconfig.config.elements.BasicOption; import cc.polyfrost.oneconfig.gui.elements.text.TextInputField; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; import cc.polyfrost.oneconfig.internal.assets.SVGs; import cc.polyfrost.oneconfig.utils.InputUtils; -import org.lwjgl.input.Mouse; import java.lang.reflect.Field; @@ -50,7 +50,7 @@ public class ConfigTextBox extends BasicOption { boolean hovered = InputUtils.isAreaHovered(x + 967, y + 7, 18, 18) && isEnabled(); int color = hovered ? Colors.WHITE : Colors.WHITE_80; if (hovered && InputUtils.isClicked()) textField.setPassword(!textField.getPassword()); - if (hovered && Mouse.isButtonDown(0)) RenderManager.setAlpha(vg, 0.5f); + if (hovered && Platform.getMousePlatform().isButtonDown(0)) RenderManager.setAlpha(vg, 0.5f); RenderManager.drawSvg(vg, icon, x + 967, y + 7, 18, 18, color); } RenderManager.setAlpha(vg, 1f); diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/elements/text/TextInputField.java b/src/main/java/cc/polyfrost/oneconfig/gui/elements/text/TextInputField.java index c164eb6..40463df 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/elements/text/TextInputField.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/elements/text/TextInputField.java @@ -4,6 +4,7 @@ import cc.polyfrost.oneconfig.gui.elements.BasicElement; import cc.polyfrost.oneconfig.internal.assets.Colors; import cc.polyfrost.oneconfig.internal.assets.SVGs; import cc.polyfrost.oneconfig.libs.universal.UKeyboard; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; import cc.polyfrost.oneconfig.renderer.scissor.Scissor; @@ -13,8 +14,6 @@ import cc.polyfrost.oneconfig.utils.InputUtils; import cc.polyfrost.oneconfig.utils.MathUtils; import cc.polyfrost.oneconfig.utils.TextUtils; import org.jetbrains.annotations.NotNull; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; import java.util.ArrayList; import java.util.Objects; @@ -112,7 +111,7 @@ public class TextInputField extends BasicElement { } Scissor scissor = ScissorManager.scissor(vg, x, y, width, height); super.update(x, y); - if (Mouse.isButtonDown(0) && !InputUtils.isAreaHovered(x - 40, y - 20, width + 90, height + 20)) { + if (Platform.getMousePlatform().isButtonDown(0) && !InputUtils.isAreaHovered(x - 40, y - 20, width + 90, height + 20)) { onClose(); toggled = false; } @@ -144,9 +143,9 @@ public class TextInputField extends BasicElement { width = RenderManager.getTextWidth(vg, s.substring(0, caretPos), 14f, Fonts.REGULAR.font); } if (hovered) { - while (Mouse.next()) { - if (Mouse.getEventButtonState()) { - if (Mouse.getEventButton() == 0) { + while (Platform.getMousePlatform().next()) { + if (Platform.getMousePlatform().getEventButtonState()) { + if (Platform.getMousePlatform().getEventButton() == 0) { if (multiLine) { int caretLine = Math.max(0, Math.min(wrappedText.size() - 1, (int) Math.floor((InputUtils.mouseY() - y - 10) / 24f))); caretPos = calculatePos(InputUtils.mouseX(), wrappedText.get(caretLine)); @@ -158,7 +157,7 @@ public class TextInputField extends BasicElement { clickTimeD1 = System.currentTimeMillis(); } } else { - if (Mouse.getEventButton() == 0) { + if (Platform.getMousePlatform().getEventButton() == 0) { long clickTimeU = System.currentTimeMillis(); if (clickTimeU - clickTimeD1 < 200) { if (!isDoubleClick) { @@ -188,7 +187,7 @@ public class TextInputField extends BasicElement { } } if (hovered) { - if (Mouse.isButtonDown(0) && !isDoubleClick) { + if (Platform.getMousePlatform().isButtonDown(0) && !isDoubleClick) { if (multiLine) { int caretLine = Math.max(0, Math.min(wrappedText.size() - 1, (int) Math.floor((InputUtils.mouseY() - y - 10) / 24f))); caretPos = calculatePos(InputUtils.mouseX(), wrappedText.get(caretLine)); @@ -265,7 +264,7 @@ public class TextInputField extends BasicElement { } return; } - if (UKeyboard.isKeyComboCtrlV(key) || key == Keyboard.KEY_INSERT) { // TODO: find the UKeyboard equivalent for insert + if (UKeyboard.isKeyComboCtrlV(key) || key == 0xD2) { // TODO: is this the same in LWJGL 3? try { String clip = IOUtils.getStringFromClipboard(); input = input.substring(0, caretPos) + clip + input.substring(caretPos); diff --git a/src/main/java/cc/polyfrost/oneconfig/gui/pages/Page.java b/src/main/java/cc/polyfrost/oneconfig/gui/pages/Page.java index b55f851..ddf6a3f 100644 --- a/src/main/java/cc/polyfrost/oneconfig/gui/pages/Page.java +++ b/src/main/java/cc/polyfrost/oneconfig/gui/pages/Page.java @@ -4,12 +4,12 @@ import cc.polyfrost.oneconfig.gui.animations.Animation; import cc.polyfrost.oneconfig.gui.animations.ColorAnimation; import cc.polyfrost.oneconfig.gui.animations.EaseOutQuad; import cc.polyfrost.oneconfig.internal.assets.Colors; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import cc.polyfrost.oneconfig.renderer.scissor.Scissor; import cc.polyfrost.oneconfig.renderer.scissor.ScissorManager; import cc.polyfrost.oneconfig.utils.InputUtils; import cc.polyfrost.oneconfig.utils.color.ColorPalette; -import org.lwjgl.input.Mouse; import java.util.ArrayList; @@ -52,7 +52,7 @@ public abstract class Page { final float scrollBarLength = (728f / maxScroll) * 728f; Scissor scissor = ScissorManager.scissor(vg, x, y + scissorOffset, x + 1056, y + 728 - scissorOffset); Scissor inputScissor = InputUtils.blockInputArea(x, y,1056, scissorOffset); - int dWheel = Mouse.getDWheel(); + int dWheel = Platform.getMousePlatform().getDWheel(); if (dWheel != 0) { scrollTarget += dWheel; @@ -77,10 +77,10 @@ public abstract class Page { InputUtils.stopBlock(inputScissor); if (!(scrollBarLength > 727f)) { final float scrollBarY = (scroll / maxScroll) * 720f; - final boolean isMouseDown = Mouse.isButtonDown(0); + final boolean isMouseDown = Platform.getMousePlatform().isButtonDown(0); final boolean scrollHover = InputUtils.isAreaHovered(x + 1042, (int) (y - scrollBarY), 12, (int) scrollBarLength); final boolean scrollTimePeriod = (System.currentTimeMillis() - scrollTime < 1000); - final boolean hovered = (scrollHover || scrollTimePeriod) && Mouse.isButtonDown(0); + final boolean hovered = (scrollHover || scrollTimePeriod) && Platform.getMousePlatform().isButtonDown(0); if (scrollHover && isMouseDown && !mouseWasDown) { yStart = InputUtils.mouseY(); dragging = true; diff --git a/src/main/java/cc/polyfrost/oneconfig/hud/Hud.java b/src/main/java/cc/polyfrost/oneconfig/hud/Hud.java index 62cfb2e..9c9a005 100644 --- a/src/main/java/cc/polyfrost/oneconfig/hud/Hud.java +++ b/src/main/java/cc/polyfrost/oneconfig/hud/Hud.java @@ -1,13 +1,11 @@ package cc.polyfrost.oneconfig.hud; +import cc.polyfrost.oneconfig.config.Config; import cc.polyfrost.oneconfig.config.annotations.Switch; import cc.polyfrost.oneconfig.config.core.OneColor; import cc.polyfrost.oneconfig.gui.OneConfigGui; -import cc.polyfrost.oneconfig.libs.universal.UMinecraft; -import cc.polyfrost.oneconfig.libs.universal.UScreen; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; -import cc.polyfrost.oneconfig.config.Config; -import net.minecraft.client.gui.GuiChat; /** * Represents a HUD element in OneConfig. @@ -175,9 +173,9 @@ public abstract class Hud { * @param background If background should be drawn or not */ public void drawAll(float x, float y, float scale, boolean background) { - if (!showInGuis && UScreen.getCurrentScreen() != null && !(UScreen.getCurrentScreen() instanceof OneConfigGui)) return; - if (!showInChat && UScreen.getCurrentScreen() instanceof GuiChat) return; - if (!showInDebug && UMinecraft.getSettings().showDebugInfo) return; + if (!showInGuis && Platform.getGuiPlatform().getCurrentScreen() != null && !(Platform.getGuiPlatform().getCurrentScreen() instanceof OneConfigGui)) return; + if (!showInChat && Platform.getGuiPlatform().isInChat()) return; + if (!showInDebug && Platform.getGuiPlatform().isInDebug()) return; if (background && drawBackground()) drawBackground(x, y, getWidth(scale), getHeight(scale), scale); draw((int) (x + paddingX * scale / 2f), (int) (y + paddingY * scale / 2f), scale); } diff --git a/src/main/java/cc/polyfrost/oneconfig/hud/TextHud.java b/src/main/java/cc/polyfrost/oneconfig/hud/TextHud.java index ab00139..3b74c4c 100644 --- a/src/main/java/cc/polyfrost/oneconfig/hud/TextHud.java +++ b/src/main/java/cc/polyfrost/oneconfig/hud/TextHud.java @@ -9,6 +9,7 @@ import cc.polyfrost.oneconfig.events.event.TickEvent; import cc.polyfrost.oneconfig.internal.hud.HudCore; import cc.polyfrost.oneconfig.libs.eventbus.Subscribe; import cc.polyfrost.oneconfig.libs.universal.UMinecraft; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.RenderManager; import java.util.ArrayList; @@ -83,7 +84,7 @@ public abstract class TextHud extends Hud { width = 0; for (String line : lines) { RenderManager.drawScaledString(line, x, textY, color.getRGB(), RenderManager.TextType.toType(textType), scale); - width = Math.max(width, UMinecraft.getFontRenderer().getStringWidth(line)); + width = Math.max(width, Platform.getGLPlatform().getStringWidth(line)); textY += 12 * scale; } height = (int) ((textY - y) / scale - 3); diff --git a/src/main/java/cc/polyfrost/oneconfig/images/Image.java b/src/main/java/cc/polyfrost/oneconfig/images/Image.java index 5e695e5..16957c1 100644 --- a/src/main/java/cc/polyfrost/oneconfig/images/Image.java +++ b/src/main/java/cc/polyfrost/oneconfig/images/Image.java @@ -1,9 +1,10 @@ package cc.polyfrost.oneconfig.images; -import cc.polyfrost.oneconfig.internal.OneConfig; import cc.polyfrost.oneconfig.utils.IOUtils; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import javax.imageio.ImageIO; import java.awt.*; @@ -20,6 +21,7 @@ import java.util.Objects; /** An Image wrapper class that is used by the OneConfig system.*/ @SuppressWarnings("unused") public class Image { + private static final Logger LOGGER = LogManager.getLogger("OneConfig Images"); private BufferedImage image; private Graphics2D graphics = null; private final int width, height; @@ -152,7 +154,7 @@ public class Image { byteOut.close(); writer.close(); if(con.getResponseCode() != 200) { - OneConfig.LOGGER.error("Error uploading image to Imgur: " + con.getResponseCode()); + LOGGER.error("Error uploading image to Imgur: " + con.getResponseCode()); return null; } @@ -163,7 +165,7 @@ public class Image { return object; } catch (Exception e) { e.printStackTrace(); - OneConfig.LOGGER.error("Error uploading image to Imgur."); + LOGGER.error("Error uploading image to Imgur."); return null; } } diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/OneConfig.java b/src/main/java/cc/polyfrost/oneconfig/internal/OneConfig.java deleted file mode 100644 index 4e531de..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/OneConfig.java +++ /dev/null @@ -1,87 +0,0 @@ -package cc.polyfrost.oneconfig.internal; - -import cc.polyfrost.oneconfig.events.EventManager; -import cc.polyfrost.oneconfig.events.event.ShutdownEvent; -import cc.polyfrost.oneconfig.gui.OneConfigGui; -import cc.polyfrost.oneconfig.internal.command.OneConfigCommand; -import cc.polyfrost.oneconfig.internal.config.OneConfigConfig; -import cc.polyfrost.oneconfig.internal.config.Preferences; -import cc.polyfrost.oneconfig.internal.config.core.ConfigCore; -import cc.polyfrost.oneconfig.internal.config.core.KeyBindHandler; -import cc.polyfrost.oneconfig.internal.gui.BlurHandler; -import cc.polyfrost.oneconfig.internal.hud.HudCore; -import cc.polyfrost.oneconfig.libs.eventbus.Subscribe; -import cc.polyfrost.oneconfig.utils.commands.CommandManager; -import cc.polyfrost.oneconfig.utils.gui.GuiUtils; -import cc.polyfrost.oneconfig.utils.hypixel.HypixelUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.File; - -/** - * The main class of OneConfig. - */ -@net.minecraftforge.fml.common.Mod(modid = "@ID@", name = "@NAME@", version = "@VER@") -public class OneConfig { - - public OneConfig() { - EventManager.INSTANCE.register(this); - } - - public static final File oneConfigDir = new File("./OneConfig"); - public static final Logger LOGGER = LogManager.getLogger("@NAME@"); - public static OneConfigConfig config; - public static Preferences preferences; - private static boolean preLaunched = false; - private static boolean initialized = false; - private static boolean isObfuscated = true; - - /** - * Called before mods are loaded. - *

SHOULD NOT BE CALLED!

- */ - public static void preLaunch() { - if (preLaunched) return; - try { - Class.forName("net.minecraft.world.World"); - LOGGER.warn("OneConfig is NOT obfuscated!"); - isObfuscated = false; - } catch (Exception ignored) { - } - oneConfigDir.mkdirs(); - new File(oneConfigDir, "profiles").mkdirs(); - config = new OneConfigConfig(); - preferences = new Preferences(); - preLaunched = true; - } - - /** - * Called after mods are loaded. - *

SHOULD NOT BE CALLED!

- */ - @SuppressWarnings("ResultOfMethodCallIgnored") - public static void init() { - if (initialized) return; - GuiUtils.getDeltaTime(); // called to make sure static initializer is called - BlurHandler.INSTANCE.load(); - CommandManager.INSTANCE.registerCommand(OneConfigCommand.class); - EventManager.INSTANCE.register(new HudCore()); - HypixelUtils.INSTANCE.initialize(); - EventManager.INSTANCE.register(KeyBindHandler.INSTANCE); - ConfigCore.sortMods(); - - initialized = true; - } - - /** Returns weather this is an obfuscated environment, using a check for obfuscated name of net.minecraft.world.World.class. - * @return true if this is an obfuscated environment, which is normal for Minecraft or false if not. */ - public static boolean isObfuscated() { - return isObfuscated; - } - - @Subscribe - private void onShutdown(ShutdownEvent event) { - ConfigCore.saveAll(); - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/config/OneConfigConfig.java b/src/main/java/cc/polyfrost/oneconfig/internal/config/OneConfigConfig.java index 0ed5dc2..c7b95d1 100644 --- a/src/main/java/cc/polyfrost/oneconfig/internal/config/OneConfigConfig.java +++ b/src/main/java/cc/polyfrost/oneconfig/internal/config/OneConfigConfig.java @@ -1,14 +1,7 @@ package cc.polyfrost.oneconfig.internal.config; -import cc.polyfrost.oneconfig.config.Config; import cc.polyfrost.oneconfig.config.core.OneColor; -import cc.polyfrost.oneconfig.config.data.Mod; -import cc.polyfrost.oneconfig.utils.JsonUtils; -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; import java.util.ArrayList; public class OneConfigConfig extends InternalConfig { @@ -24,8 +17,15 @@ public class OneConfigConfig extends InternalConfig { public static ArrayList recentColors = new ArrayList<>(); public static boolean australia = false; + private static OneConfigConfig INSTANCE; + public OneConfigConfig() { super("", "OneConfig.json"); initialize(); + INSTANCE = this; + } + + public static OneConfigConfig getInstance() { + return INSTANCE == null ? (INSTANCE = new OneConfigConfig()) : INSTANCE; } } diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/config/Preferences.java b/src/main/java/cc/polyfrost/oneconfig/internal/config/Preferences.java index fff8fed..f98a913 100644 --- a/src/main/java/cc/polyfrost/oneconfig/internal/config/Preferences.java +++ b/src/main/java/cc/polyfrost/oneconfig/internal/config/Preferences.java @@ -7,7 +7,8 @@ import cc.polyfrost.oneconfig.config.core.OneKeyBind; import cc.polyfrost.oneconfig.gui.OneConfigGui; import cc.polyfrost.oneconfig.internal.gui.BlurHandler; import cc.polyfrost.oneconfig.libs.universal.UKeyboard; -import cc.polyfrost.oneconfig.libs.universal.UMinecraft; +import cc.polyfrost.oneconfig.platform.Platform; +import cc.polyfrost.oneconfig.utils.TickDelay; import cc.polyfrost.oneconfig.utils.gui.GuiUtils; public class Preferences extends InternalConfig { @@ -37,10 +38,17 @@ public class Preferences extends InternalConfig { ) public static float customScale = 1f; + private static Preferences INSTANCE; + public Preferences() { super("Preferences", "Preferences.json"); initialize(); - addListener("enableBlur", () -> BlurHandler.INSTANCE.reloadBlur(UMinecraft.getMinecraft().currentScreen)); - registerKeyBind(oneConfigKeyBind, () -> GuiUtils.displayScreen(OneConfigGui.create())); + addListener("enableBlur", () -> BlurHandler.INSTANCE.reloadBlur(Platform.getGuiPlatform().getCurrentScreen())); + registerKeyBind(oneConfigKeyBind, () -> new TickDelay(() -> Platform.getGuiPlatform().setCurrentScreen(OneConfigGui.create()), 1)); + INSTANCE = this; + } + + public static Preferences getInstance() { + return INSTANCE == null ? (INSTANCE = new Preferences()) : INSTANCE; } } diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/config/core/ConfigCore.java b/src/main/java/cc/polyfrost/oneconfig/internal/config/core/ConfigCore.java index 4edff74..ab796c7 100644 --- a/src/main/java/cc/polyfrost/oneconfig/internal/config/core/ConfigCore.java +++ b/src/main/java/cc/polyfrost/oneconfig/internal/config/core/ConfigCore.java @@ -40,11 +40,13 @@ public class ConfigCore { } public static void sortMods() { + ArrayList mods = new ArrayList<>(ConfigCore.mods); ConfigCore.mods = mods.stream().filter((mod -> OneConfigConfig.favoriteMods.contains(mod.name))).sorted().collect(Collectors.toList()); mods.removeAll(ConfigCore.mods); ConfigCore.mods.addAll(mods.stream().filter(mod -> mod.modType != ModType.THIRD_PARTY).sorted().collect(Collectors.toList())); mods.removeAll(ConfigCore.mods); ConfigCore.mods.addAll(mods.stream().sorted().collect(Collectors.toList())); + OneConfigConfig.getInstance().save(); } } diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/gui/BlurHandler.java b/src/main/java/cc/polyfrost/oneconfig/internal/gui/BlurHandler.java index dac0202..38e8406 100644 --- a/src/main/java/cc/polyfrost/oneconfig/internal/gui/BlurHandler.java +++ b/src/main/java/cc/polyfrost/oneconfig/internal/gui/BlurHandler.java @@ -1,140 +1,8 @@ package cc.polyfrost.oneconfig.internal.gui; -import cc.polyfrost.oneconfig.events.EventManager; -import cc.polyfrost.oneconfig.events.event.RenderEvent; -import cc.polyfrost.oneconfig.events.event.ScreenOpenEvent; -import cc.polyfrost.oneconfig.events.event.Stage; -import cc.polyfrost.oneconfig.gui.OneConfigGui; -import cc.polyfrost.oneconfig.internal.config.Preferences; -import cc.polyfrost.oneconfig.internal.mixin.ShaderGroupAccessor; -import cc.polyfrost.oneconfig.libs.universal.UMinecraft; -import cc.polyfrost.oneconfig.libs.universal.UScreen; -import cc.polyfrost.oneconfig.libs.eventbus.Subscribe; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.shader.Shader; -import net.minecraft.client.shader.ShaderUniform; -import net.minecraft.util.ResourceLocation; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import java.util.ServiceLoader; -import java.util.List; - -/** - * An implementation of the BlurMC mod by tterrag1098. - *

- * For the original source see ... - * For the public license, see ... - *

- * License available under ... - * - * @author tterrag1098, boomboompower - *

- * Taken from ToggleChat - * ... - */ -public class BlurHandler { - public static BlurHandler INSTANCE = new BlurHandler(); - private final ResourceLocation blurShader = new ResourceLocation("shaders/post/fade_in_blur.json"); - private final Logger logger = LogManager.getLogger("OneConfig - Blur"); - private long start; - private float progress = 0; - - /** - * Simply initializes the blur mod so events are properly handled by forge. - */ - public void load() { - EventManager.INSTANCE.register(this); - } - - @Subscribe - private void onGuiChange(ScreenOpenEvent event) { - reloadBlur(event.screen); - } - - @Subscribe - private void onRenderTick(RenderEvent event) { - if (event.stage != Stage.END) { - return; - } - - // Only blur on our own menus - if (UScreen.getCurrentScreen() == null) { - return; - } - - // Only update the shader if one is active - if (!UMinecraft.getMinecraft().entityRenderer.isShaderActive()) { - return; - } - if (progress >= 5) return; - progress = getBlurStrengthProgress(); - - // This is hilariously bad, and could cause frame issues on low-end computers. - // Why is this being computed every tick? Surely there is a better way? - // This needs to be optimized. - try { - final List listShaders = ((ShaderGroupAccessor) Minecraft.getMinecraft().entityRenderer.getShaderGroup()).getListShaders(); - - // Should not happen. Something bad happened. - if (listShaders == null) { - return; - } - - // Iterate through the list of shaders. - for (Shader shader : listShaders) { - ShaderUniform su = shader.getShaderManager().getShaderUniform("Progress"); - - if (su == null) { - continue; - } - - // All this for this. - su.set(progress); - } - } catch (IllegalArgumentException ex) { - this.logger.error("An error.png occurred while updating OneConfig's blur. Please report this!", ex); - } - } - - /** - * Activates/deactivates the blur in the current world if - * one of many conditions are met, such as no current other shader - * is being used, we actually have the blur setting enabled - */ - public void reloadBlur(GuiScreen gui) { - // Don't do anything if no world is loaded - if (UMinecraft.getWorld() == null) { - return; - } - - // If a shader is not already active and the UI is - // a one of ours, we should load our own blur! - if (!UMinecraft.getMinecraft().entityRenderer.isShaderActive() && gui instanceof OneConfigGui && Preferences.enableBlur) { - UMinecraft.getMinecraft().entityRenderer.loadShader(this.blurShader); - - this.start = System.currentTimeMillis(); - this.progress = 0; - - // If a shader is active and the incoming UI is null or we have blur disabled, stop using the shader. - } else if (UMinecraft.getMinecraft().entityRenderer.isShaderActive() && (gui == null || !Preferences.enableBlur)) { - String name = UMinecraft.getMinecraft().entityRenderer.getShaderGroup().getShaderGroupName(); - - // Only stop our specific blur ;) - if (!name.endsWith("fade_in_blur.json")) { - return; - } - - UMinecraft.getMinecraft().entityRenderer.stopUseShader(); - } - } - - /** - * Returns the strength of the blur as determined by the duration the effect of the blur. - *

- * The strength of the blur does not go below 5.0F. - */ - private float getBlurStrengthProgress() { - return Math.min((System.currentTimeMillis() - this.start) / 50F, 5.0F); - } +public interface BlurHandler { + BlurHandler INSTANCE = ServiceLoader.load(BlurHandler.class, BlurHandler.class.getClassLoader()).iterator().next(); + void reloadBlur(Object screen); } diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/init/OneConfigInit.java b/src/main/java/cc/polyfrost/oneconfig/internal/init/OneConfigInit.java index 86fdb1f..1f70815 100644 --- a/src/main/java/cc/polyfrost/oneconfig/internal/init/OneConfigInit.java +++ b/src/main/java/cc/polyfrost/oneconfig/internal/init/OneConfigInit.java @@ -1,7 +1,5 @@ package cc.polyfrost.oneconfig.internal.init; -import net.minecraft.launchwrapper.Launch; -import org.spongepowered.asm.launch.MixinBootstrap; import org.spongepowered.asm.mixin.Mixins; @SuppressWarnings("unused") diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/FontRendererMixin.java b/src/main/java/cc/polyfrost/oneconfig/internal/mixin/FontRendererMixin.java deleted file mode 100644 index 227b99e..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/FontRendererMixin.java +++ /dev/null @@ -1,15 +0,0 @@ -package cc.polyfrost.oneconfig.internal.mixin; - - -import net.minecraft.client.gui.FontRenderer; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(FontRenderer.class) -public class FontRendererMixin { - - //@Inject(method = "renderDefaultChar", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/FontRenderer;bindTexture(Lnet/minecraft/util/ResourceLocation;)V", shift = At.Shift.AFTER)) - //public void whoAsked(int ch, boolean italic, CallbackInfoReturnable cir) { - // GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); - // GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); - //} -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/GuiIngameForgeMixin.java b/src/main/java/cc/polyfrost/oneconfig/internal/mixin/GuiIngameForgeMixin.java deleted file mode 100644 index f08d37e..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/GuiIngameForgeMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package cc.polyfrost.oneconfig.internal.mixin; - -import cc.polyfrost.oneconfig.events.EventManager; -import cc.polyfrost.oneconfig.events.event.HudRenderEvent; -import net.minecraftforge.client.GuiIngameForge; -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; - -@Mixin(value = GuiIngameForge.class, remap = false) -public class GuiIngameForgeMixin { - @Inject(method = "renderGameOverlay", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/client/GuiIngameForge;post(Lnet/minecraftforge/client/event/RenderGameOverlayEvent$ElementType;)V", shift = At.Shift.AFTER, remap = false), remap = true) - private void onRenderGameOverlay(float partialTicks, CallbackInfo ci) { - EventManager.INSTANCE.post(new HudRenderEvent(partialTicks)); - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/MinecraftMixin.java b/src/main/java/cc/polyfrost/oneconfig/internal/mixin/MinecraftMixin.java deleted file mode 100644 index 5fb40f8..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/MinecraftMixin.java +++ /dev/null @@ -1,98 +0,0 @@ -package cc.polyfrost.oneconfig.internal.mixin; - -import cc.polyfrost.oneconfig.internal.OneConfig; -import cc.polyfrost.oneconfig.events.EventManager; -import cc.polyfrost.oneconfig.events.event.*; -import net.minecraft.client.Minecraft; -import net.minecraft.util.Timer; -import net.minecraftforge.client.event.GuiOpenEvent; -import net.minecraftforge.fml.common.eventhandler.Event; -import org.objectweb.asm.Opcodes; -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; - -@Mixin(Minecraft.class) -public class MinecraftMixin { - @Shadow - private Timer timer; - - @Inject(method = "shutdownMinecraftApplet", at = @At("HEAD")) - private void onShutdown(CallbackInfo ci) { - EventManager.INSTANCE.post(new PreShutdownEvent()); - } - - @Inject(method = "startGame", at = @At("HEAD")) - private void onStart(CallbackInfo ci) { - EventManager.INSTANCE.post(new StartEvent()); - Runtime.getRuntime().addShutdownHook(new Thread(() -> EventManager.INSTANCE.post(new ShutdownEvent()))); - } - - @Inject(method = "startGame", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/client/FMLClientHandler;beginMinecraftLoading(Lnet/minecraft/client/Minecraft;Ljava/util/List;Lnet/minecraft/client/resources/IReloadableResourceManager;)V", remap = false), remap = true) - private void onPreLaunch(CallbackInfo ci) { - OneConfig.preLaunch(); - } - - @Inject(method = "startGame", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/client/FMLClientHandler;onInitializationComplete()V", shift = At.Shift.AFTER, remap = false), remap = true) - private void onInit(CallbackInfo ci) { - EventManager.INSTANCE.post(new InitializationEvent()); - OneConfig.init(); - } - - @Inject(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;onRenderTickStart(F)V", shift = At.Shift.AFTER, remap = false), remap = true) - private void onRenderTickStart(CallbackInfo ci) { - EventManager.INSTANCE.post(new RenderEvent(Stage.START, timer.renderPartialTicks)); - } - - @Inject(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;onRenderTickEnd(F)V", shift = At.Shift.AFTER, remap = false), remap = true) - private void onRenderTickEnd(CallbackInfo ci) { - EventManager.INSTANCE.post(new RenderEvent(Stage.END, timer.renderPartialTicks)); - } - - @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;onPreClientTick()V", shift = At.Shift.AFTER, remap = false), remap = true) - private void onClientTickStart(CallbackInfo ci) { - EventManager.INSTANCE.post(new TickEvent(Stage.START)); - } - - @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;onPostClientTick()V", shift = At.Shift.AFTER, remap = false), remap = true) - private void onClientTickEnd(CallbackInfo ci) { - EventManager.INSTANCE.post(new TickEvent(Stage.END)); - } - - @ModifyArg(method = "displayGuiScreen", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/eventhandler/EventBus;post(Lnet/minecraftforge/fml/common/eventhandler/Event;)Z", remap = false), remap = true) - private Event onGuiOpenEvent(Event a) { - if (a instanceof GuiOpenEvent) { - GuiOpenEvent forgeEvent = (GuiOpenEvent) a; - ScreenOpenEvent event = new ScreenOpenEvent(forgeEvent.gui); - EventManager.INSTANCE.post(event); - if (event.isCancelled) { - forgeEvent.setCanceled(true); - } - return forgeEvent; - } - return a; - } - - @Inject(method = "runGameLoop", at = @At(value = "FIELD", target = "Lnet/minecraft/util/Timer;renderPartialTicks:F", opcode = Opcodes.PUTFIELD, shift = At.Shift.AFTER)) - private void onNonDeltaTickTimerUpdate(CallbackInfo ci) { - EventManager.INSTANCE.post(new TimerUpdateEvent(timer, false)); - } - - @Inject(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/Timer;updateTimer()V", shift = At.Shift.AFTER, ordinal = 1)) - private void onDeltaTickTimerUpdate(CallbackInfo ci) { - EventManager.INSTANCE.post(new TimerUpdateEvent(timer, true)); - } - - @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;fireKeyInput()V")) - private void onKeyEvent(CallbackInfo ci) { - EventManager.INSTANCE.post(new KeyInputEvent()); - } - - @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;fireMouseInput()V")) - private void onMouseEvent(CallbackInfo ci) { - EventManager.INSTANCE.post(new MouseInputEvent()); - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetHandlerPlayClientMixin.java b/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetHandlerPlayClientMixin.java deleted file mode 100644 index 877d540..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetHandlerPlayClientMixin.java +++ /dev/null @@ -1,36 +0,0 @@ -package cc.polyfrost.oneconfig.internal.mixin; - -import cc.polyfrost.oneconfig.events.EventManager; -import cc.polyfrost.oneconfig.events.event.ChatReceiveEvent; -import cc.polyfrost.oneconfig.events.event.SendPacketEvent; -import net.minecraft.client.network.NetHandlerPlayClient; -import net.minecraft.network.Packet; -import net.minecraft.network.play.server.S02PacketChat; -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; - -@Mixin(value = NetHandlerPlayClient.class, priority = Integer.MAX_VALUE) -public class NetHandlerPlayClientMixin { - - @Inject(method = "addToSendQueue", at = @At("HEAD"), cancellable = true) - private void onSendPacket(Packet p_147297_1_, CallbackInfo ci) { - SendPacketEvent event = new SendPacketEvent(p_147297_1_); - EventManager.INSTANCE.post(event); - if (event.isCancelled) { - ci.cancel(); - } - } - - @Inject(method = "handleChat", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/event/ForgeEventFactory;onClientChat(BLnet/minecraft/util/IChatComponent;)Lnet/minecraft/util/IChatComponent;", remap = false), cancellable = true, remap = true) - private void onClientChat(S02PacketChat packetIn, CallbackInfo ci) { - if (packetIn.getType() == 0) { - ChatReceiveEvent event = new ChatReceiveEvent(packetIn.getChatComponent()); - EventManager.INSTANCE.post(event); - if (event.isCancelled) { - ci.cancel(); - } - } - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetworkManagerMixin.java b/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetworkManagerMixin.java deleted file mode 100644 index 51988f2..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetworkManagerMixin.java +++ /dev/null @@ -1,23 +0,0 @@ -package cc.polyfrost.oneconfig.internal.mixin; - -import cc.polyfrost.oneconfig.events.EventManager; -import cc.polyfrost.oneconfig.events.event.ReceivePacketEvent; -import io.netty.channel.ChannelHandlerContext; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -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; - -@Mixin(value = NetworkManager.class, priority = Integer.MAX_VALUE) -public class NetworkManagerMixin { - @Inject(method = "channelRead0(Lio/netty/channel/ChannelHandlerContext;Lnet/minecraft/network/Packet;)V", at = @At("HEAD"), cancellable = true) - private void onReceivePacket(ChannelHandlerContext p_channelRead0_1_, Packet p_channelRead0_2_, CallbackInfo ci) { - ReceivePacketEvent event = new ReceivePacketEvent(p_channelRead0_2_); - EventManager.INSTANCE.post(event); - if (event.isCancelled) { - ci.cancel(); - } - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/OptifineConfigMixin.java b/src/main/java/cc/polyfrost/oneconfig/internal/mixin/OptifineConfigMixin.java deleted file mode 100644 index fe8c203..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/OptifineConfigMixin.java +++ /dev/null @@ -1,21 +0,0 @@ -package cc.polyfrost.oneconfig.internal.mixin; - -import cc.polyfrost.oneconfig.internal.plugin.hooks.OptifineConfigHook; -import org.spongepowered.asm.mixin.Dynamic; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Pseudo; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Pseudo -@Mixin(targets = "Config", remap = false) -public class OptifineConfigMixin { - @Dynamic("OptiFine") - @Inject(method = "isFastRender", at = @At("HEAD"), cancellable = true) - private static void cancelFastRender(CallbackInfoReturnable cir) { - if (OptifineConfigHook.shouldNotApplyFastRender()) { - cir.setReturnValue(false); - } - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/ShaderGroupAccessor.java b/src/main/java/cc/polyfrost/oneconfig/internal/mixin/ShaderGroupAccessor.java deleted file mode 100644 index 8014670..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/ShaderGroupAccessor.java +++ /dev/null @@ -1,14 +0,0 @@ -package cc.polyfrost.oneconfig.internal.mixin; - -import net.minecraft.client.shader.Shader; -import net.minecraft.client.shader.ShaderGroup; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.List; - -@Mixin(ShaderGroup.class) -public interface ShaderGroupAccessor { - @Accessor("listShaders") - List getListShaders(); -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/VigilantMixin.java b/src/main/java/cc/polyfrost/oneconfig/internal/mixin/VigilantMixin.java deleted file mode 100644 index 662293c..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/VigilantMixin.java +++ /dev/null @@ -1,8 +0,0 @@ -package cc.polyfrost.oneconfig.internal.mixin; - -import gg.essential.vigilance.Vigilant; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(Vigilant.class) -public class VigilantMixin { -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/WorldClientMixin.java b/src/main/java/cc/polyfrost/oneconfig/internal/mixin/WorldClientMixin.java deleted file mode 100644 index d1fce6a..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/mixin/WorldClientMixin.java +++ /dev/null @@ -1,21 +0,0 @@ -package cc.polyfrost.oneconfig.internal.mixin; - -import cc.polyfrost.oneconfig.events.EventManager; -import cc.polyfrost.oneconfig.events.event.WorldLoadEvent; -import net.minecraft.client.multiplayer.WorldClient; -import net.minecraft.client.network.NetHandlerPlayClient; -import net.minecraft.profiler.Profiler; -import net.minecraft.world.EnumDifficulty; -import net.minecraft.world.WorldSettings; -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; - -@Mixin(WorldClient.class) -public class WorldClientMixin { - @Inject(method = "", at = @At("RETURN")) - private void onWorldLoad(NetHandlerPlayClient p_i45063_1_, WorldSettings p_i45063_2_, int p_i45063_3_, EnumDifficulty p_i45063_4_, Profiler p_i45063_5_, CallbackInfo ci) { - EventManager.INSTANCE.post(new WorldLoadEvent()); - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ClassTransformer.java b/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ClassTransformer.java deleted file mode 100644 index 52256ca..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ClassTransformer.java +++ /dev/null @@ -1,102 +0,0 @@ -package cc.polyfrost.oneconfig.internal.plugin.asm; - -import cc.polyfrost.oneconfig.internal.plugin.asm.tweakers.NanoVGGLConfigTransformer; -import cc.polyfrost.oneconfig.internal.plugin.asm.tweakers.VigilantTransformer; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Multimap; -import net.minecraft.launchwrapper.IClassTransformer; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.tree.ClassNode; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Collection; - -/** - * Taken from LWJGLTwoPointFive under The Unlicense - * https://github.com/DJtheRedstoner/LWJGLTwoPointFive/blob/master/LICENSE/ - *

also half taken from asmworkspace by asbyth ty

- */ -@SuppressWarnings("unused") -public class ClassTransformer implements IClassTransformer { - private static final Logger logger = LogManager.getLogger("OneConfig ASM"); - private final Multimap transformerMap = ArrayListMultimap.create(); - private static final boolean outputBytecode = Boolean.parseBoolean(System.getProperty("debugBytecode", "false")); - - public ClassTransformer() { - registerTransformer(new NanoVGGLConfigTransformer()); - registerTransformer(new VigilantTransformer()); - } - - private void registerTransformer(ITransformer transformer) { - // loop through names of classes - for (String cls : transformer.getClassName()) { - // put the classes into the transformer map - transformerMap.put(cls, transformer); - } - } - - @Override - public byte[] transform(String name, String transformedName, byte[] bytes) { - if (bytes == null) return null; - - Collection transformers = transformerMap.get(transformedName); - if (transformers.isEmpty()) return bytes; - - ClassReader reader = new ClassReader(bytes); - ClassNode node = new ClassNode(); - reader.accept(node, ClassReader.EXPAND_FRAMES); - - for (ITransformer transformer : transformers) { - transformer.transform(transformedName, node); - } - - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); - try { - node.accept(cw); - } catch (Throwable t) { - logger.error("Exception when transforming " + transformedName + " : " + t.getClass().getSimpleName()); - t.printStackTrace(); - } - - if (outputBytecode) { - File bytecodeDirectory = new File("bytecode"); - String transformedClassName; - - // anonymous classes - if (transformedName.contains("$")) { - transformedClassName = transformedName.replace('$', '.') + ".class"; - } else { - transformedClassName = transformedName + ".class"; - } - - if (!bytecodeDirectory.exists()) { - bytecodeDirectory.mkdirs(); - } - - File bytecodeOutput = new File(bytecodeDirectory, transformedClassName); - - try { - if (!bytecodeOutput.exists()) { - bytecodeOutput.createNewFile(); - } - } catch (Exception e) { - e.printStackTrace(); - } - - try (FileOutputStream os = new FileOutputStream(bytecodeOutput)) { - // write to the generated class to /run/bytecode/classfile.class - // with the class bytes from transforming - os.write(cw.toByteArray()); - } catch (IOException e) { - e.printStackTrace(); - } - } - - return cw.toByteArray(); - } -} \ No newline at end of file diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ITransformer.java b/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ITransformer.java deleted file mode 100644 index 1bc50d1..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ITransformer.java +++ /dev/null @@ -1,24 +0,0 @@ -package cc.polyfrost.oneconfig.internal.plugin.asm; - -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.MethodNode; - -public interface ITransformer { - String[] getClassName(); - - void transform(String transformedName, ClassNode node); - - default void clearInstructions(MethodNode methodNode) { - methodNode.instructions.clear(); - - // dont waste time clearing local variables if they're empty - if (!methodNode.localVariables.isEmpty()) { - methodNode.localVariables.clear(); - } - - // dont waste time clearing try-catches if they're empty - if (!methodNode.tryCatchBlocks.isEmpty()) { - methodNode.tryCatchBlocks.clear(); - } - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/OneConfigTweaker.java b/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/OneConfigTweaker.java deleted file mode 100644 index d302b9d..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/OneConfigTweaker.java +++ /dev/null @@ -1,117 +0,0 @@ -package cc.polyfrost.oneconfig.internal.plugin.asm; - -import cc.polyfrost.oneconfig.internal.init.OneConfigInit; -import net.minecraft.launchwrapper.ITweaker; -import net.minecraft.launchwrapper.Launch; -import net.minecraft.launchwrapper.LaunchClassLoader; -import net.minecraftforge.fml.relauncher.CoreModManager; -import org.spongepowered.asm.launch.MixinBootstrap; -import org.spongepowered.asm.launch.MixinTweaker; -import org.spongepowered.asm.mixin.Mixins; - -import java.io.File; -import java.lang.reflect.Field; -import java.net.URI; -import java.net.URL; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.jar.Attributes; -import java.util.jar.JarFile; - -public class OneConfigTweaker implements ITweaker { - - public OneConfigTweaker() { - for (URL url : Launch.classLoader.getSources()) { - doMagicMixinStuff(url); - } - } - - private void doMagicMixinStuff(URL url) { - try { - URI uri = url.toURI(); - if (Objects.equals(uri.getScheme(), "file")) { - File file = new File(uri); - if (file.exists() && file.isFile()) { - try (JarFile jarFile = new JarFile(file)) { - if (jarFile.getManifest() != null) { - Attributes attributes = jarFile.getManifest().getMainAttributes(); - String tweakerClass = attributes.getValue("TweakClass"); - if (Objects.equals(tweakerClass, "cc.polyfrost.oneconfigwrapper.OneConfigWrapper")) { - CoreModManager.getIgnoredMods().remove(file.getName()); - CoreModManager.getReparseableCoremods().add(file.getName()); - String mixinConfig = attributes.getValue("MixinConfigs"); - if (mixinConfig != null) { - try { - try { - List tweakClasses = (List) Launch.blackboard.get("TweakClasses"); // tweak classes before other mod trolling - if (tweakClasses.contains("org.spongepowered.asm.launch.MixinTweaker")) { // if there's already a mixin tweaker, we'll just load it like "usual" - new MixinTweaker(); // also we might not need to make a new mixin tweawker all the time but im just making sure - } else if (!Launch.blackboard.containsKey("mixin.initialised")) { // if there isnt, we do our own trolling - List tweaks = (List) Launch.blackboard.get("Tweaks"); - tweaks.add(new MixinTweaker()); - } - } catch (Exception ignored) { - // if it fails i *think* we can just ignore it - } - MixinBootstrap.getPlatform().addContainer(uri); - } catch (Exception ignored) { - - } - } - } - } - } - } - } - } catch (Exception ignored) { - - } - } - - @Override - public void acceptOptions(List args, File gameDir, File assetsDir, String profile) { - MixinBootstrap.init(); - boolean captureNext = false; - for (String arg : args) { - if (captureNext) { - Mixins.addConfiguration(arg); - } - captureNext = "--mixin".equals(arg); - } - } - - @Override - public void injectIntoClassLoader(LaunchClassLoader classLoader) { - removeLWJGLException(); - Launch.classLoader.registerTransformer(ClassTransformer.class.getName()); - OneConfigInit.initialize(new String[]{}); - Launch.blackboard.put("oneconfig.init.initialized", true); - Launch.classLoader.addClassLoaderExclusion("cc.polyfrost.oneconfig.internal.plugin.asm."); - } - - /** - * Taken from LWJGLTwoPointFive under The Unlicense - * https://github.com/DJtheRedstoner/LWJGLTwoPointFive/blob/master/LICENSE/ - */ - private void removeLWJGLException() { - try { - Field f_exceptions = LaunchClassLoader.class.getDeclaredField("classLoaderExceptions"); - f_exceptions.setAccessible(true); - Set exceptions = (Set) f_exceptions.get(Launch.classLoader); - exceptions.remove("org.lwjgl."); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public String getLaunchTarget() { - return null; - } - - @Override - public String[] getLaunchArguments() { - return new String[0]; - } -} \ No newline at end of file diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/NanoVGGLConfigTransformer.java b/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/NanoVGGLConfigTransformer.java deleted file mode 100644 index bbbf4a1..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/NanoVGGLConfigTransformer.java +++ /dev/null @@ -1,47 +0,0 @@ -package cc.polyfrost.oneconfig.internal.plugin.asm.tweakers; - -import cc.polyfrost.oneconfig.internal.plugin.asm.ITransformer; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.*; - -/** - * Taken from LWJGLTwoPointFive under The Unlicense - * https://github.com/DJtheRedstoner/LWJGLTwoPointFive/blob/master/LICENSE/ - */ -public class NanoVGGLConfigTransformer implements ITransformer { - @Override - public String[] getClassName() { - return new String[]{"org.lwjgl.nanovg.NanoVGGLConfig"}; - } - - @Override - public void transform(String transformedName, ClassNode node) { - for (MethodNode method : node.methods) { - if (method.name.equals("configGL")) { - InsnList list = new InsnList(); - - list.add(new VarInsnNode(Opcodes.LLOAD, 0)); - list.add(new TypeInsnNode(Opcodes.NEW, "cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider")); - list.add(new InsnNode(Opcodes.DUP)); - list.add(new MethodInsnNode( - Opcodes.INVOKESPECIAL, - "cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider", - "", - "()V", - false - )); - list.add(new MethodInsnNode( - Opcodes.INVOKESTATIC, - "org/lwjgl/nanovg/NanoVGGLConfig", - "config", - "(JLorg/lwjgl/system/FunctionProvider;)V", - false - )); - list.add(new InsnNode(Opcodes.RETURN)); - - clearInstructions(method); - method.instructions.insert(list); - } - } - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/VigilantTransformer.java b/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/VigilantTransformer.java deleted file mode 100644 index 8dd60cf..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/VigilantTransformer.java +++ /dev/null @@ -1,89 +0,0 @@ -package cc.polyfrost.oneconfig.internal.plugin.asm.tweakers; - -import cc.polyfrost.oneconfig.internal.plugin.asm.ITransformer; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; -import org.objectweb.asm.tree.*; - -import java.io.File; - -public class VigilantTransformer implements ITransformer { - - @Override - public String[] getClassName() { - return new String[]{"gg.essential.vigilance.Vigilant"}; - } - - /** - * If anything here is changed, edit the corresponding method in OneConfigMixinPlugin! - */ - @Override - public void transform(String transformedName, ClassNode node) { - if (!node.interfaces.contains("cc/polyfrost/oneconfig/config/compatibility/vigilance/VigilantAccessor")) { - node.fields.add(new FieldNode(Opcodes.ACC_PUBLIC, "oneconfig$config", "Lcc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig;", null, null)); - node.fields.add(new FieldNode(Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, "oneconfig$file", Type.getDescriptor(File.class), null, null)); - - node.interfaces.add("cc/polyfrost/oneconfig/config/compatibility/vigilance/VigilantAccessor"); - MethodNode methodNode = new MethodNode(Opcodes.ACC_PUBLIC, "getPropertyCollector", "()Lgg/essential/vigilance/data/PropertyCollector;", null, null); - LabelNode labelNode = new LabelNode(); - methodNode.instructions.add(labelNode); - methodNode.instructions.add(new LineNumberNode(421421, labelNode)); - methodNode.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); - methodNode.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "gg/essential/vigilance/Vigilant", "propertyCollector", "Lgg/essential/vigilance/data/PropertyCollector;")); - methodNode.instructions.add(new InsnNode(Opcodes.ARETURN)); - node.methods.add(methodNode); - - MethodNode methodNode2 = new MethodNode(Opcodes.ACC_PUBLIC, "handleOneConfigDependency", "(Lgg/essential/vigilance/data/PropertyData;Lgg/essential/vigilance/data/PropertyData;)V", null, null); - LabelNode labelNode2 = new LabelNode(); - LabelNode labelNode3 = new LabelNode(); - LabelNode labelNode4 = new LabelNode(); - methodNode2.instructions.add(labelNode2); - methodNode2.instructions.add(new LineNumberNode(15636436, labelNode2)); - methodNode2.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); - methodNode2.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "gg/essential/vigilance/Vigilant", "oneconfig$config", "Lcc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig;")); - - methodNode2.instructions.add(new JumpInsnNode(Opcodes.IFNULL, labelNode4)); - - methodNode2.instructions.add(labelNode3); - methodNode2.instructions.add(new LineNumberNode(15636437, labelNode3)); - methodNode2.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); - methodNode2.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "gg/essential/vigilance/Vigilant", "oneconfig$config", "Lcc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig;")); - methodNode2.instructions.add(new VarInsnNode(Opcodes.ALOAD, 1)); - methodNode2.instructions.add(new VarInsnNode(Opcodes.ALOAD, 2)); - methodNode2.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "cc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig", "addDependency", "(Lgg/essential/vigilance/data/PropertyData;Lgg/essential/vigilance/data/PropertyData;)V", false)); - - methodNode2.instructions.add(labelNode4); - methodNode2.instructions.add(new LineNumberNode(15636438, labelNode4)); - methodNode2.instructions.add(new InsnNode(Opcodes.RETURN)); - node.methods.add(methodNode2); - - for (MethodNode method : node.methods) { - if (method.name.equals("initialize")) { - InsnList list = new InsnList(); - list.add(new VarInsnNode(Opcodes.ALOAD, 0)); - list.add(new VarInsnNode(Opcodes.ALOAD, 0)); - list.add(new VarInsnNode(Opcodes.ALOAD, 0)); - list.add(new FieldInsnNode(Opcodes.GETFIELD, "gg/essential/vigilance/Vigilant", "oneconfig$file", Type.getDescriptor(File.class))); - list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "cc/polyfrost/oneconfig/internal/plugin/hooks/VigilantHook", "returnNewConfig", "(Lgg/essential/vigilance/Vigilant;Ljava/io/File;)Lcc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig;", false)); - list.add(new FieldInsnNode(Opcodes.PUTFIELD, "gg/essential/vigilance/Vigilant", "oneconfig$config", "Lcc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig;")); - method.instructions.insertBefore(method.instructions.getLast().getPrevious(), list); - } else if (method.name.equals("addDependency") && method.desc.equals("(Lgg/essential/vigilance/data/PropertyData;Lgg/essential/vigilance/data/PropertyData;)V")) { - InsnList list = new InsnList(); - - list.add(new VarInsnNode(Opcodes.ALOAD, 0)); - list.add(new VarInsnNode(Opcodes.ALOAD, 1)); - list.add(new VarInsnNode(Opcodes.ALOAD, 2)); - list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "gg/essential/vigilance/Vigilant", "handleOneConfigDependency", "(Lgg/essential/vigilance/data/PropertyData;Lgg/essential/vigilance/data/PropertyData;)V", false)); - - method.instructions.insertBefore(method.instructions.getLast().getPrevious(), list); - } else if (method.name.equals("") && method.desc.equals("(Ljava/io/File;Ljava/lang/String;Lgg/essential/vigilance/data/PropertyCollector;Lgg/essential/vigilance/data/SortingBehavior;)V")) { - InsnList list = new InsnList(); - list.add(new VarInsnNode(Opcodes.ALOAD, 0)); - list.add(new VarInsnNode(Opcodes.ALOAD, 1)); - list.add(new FieldInsnNode(Opcodes.PUTFIELD, "gg/essential/vigilance/Vigilant", "oneconfig$file", Type.getDescriptor(File.class))); - method.instructions.insertBefore(method.instructions.getLast().getPrevious(), list); - } - } - } - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider.java b/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider.java deleted file mode 100644 index cf395ed..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -package cc.polyfrost.oneconfig.internal.plugin.hooks; - -import org.lwjgl.opengl.GLContext; -import org.lwjgl.system.FunctionProvider; - -import java.lang.reflect.Method; -import java.nio.ByteBuffer; - -/** - * Taken from LWJGLTwoPointFive under The Unlicense - * https://github.com/DJtheRedstoner/LWJGLTwoPointFive/blob/master/LICENSE/ - */ -public class Lwjgl2FunctionProvider implements FunctionProvider { - - private final Method m_getFunctionAddress; - - public Lwjgl2FunctionProvider() { - try { - m_getFunctionAddress = GLContext.class.getDeclaredMethod("getFunctionAddress", String.class); - m_getFunctionAddress.setAccessible(true); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public long getFunctionAddress(CharSequence functionName) { - try { - return (long) m_getFunctionAddress.invoke(null, functionName.toString()); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public long getFunctionAddress(ByteBuffer byteBuffer) { - throw new UnsupportedOperationException(); - } -} \ No newline at end of file diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/OptifineConfigHook.java b/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/OptifineConfigHook.java deleted file mode 100644 index bf8d675..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/OptifineConfigHook.java +++ /dev/null @@ -1,23 +0,0 @@ -package cc.polyfrost.oneconfig.internal.plugin.hooks; - -import cc.polyfrost.oneconfig.gui.OneConfigGui; -import cc.polyfrost.oneconfig.libs.universal.UScreen; -import cc.polyfrost.oneconfig.utils.gui.GuiUtils; -import net.minecraft.client.gui.GuiScreen; - -import java.util.Optional; - -public class OptifineConfigHook { - - public static boolean shouldNotApplyFastRender() { - if (UScreen.getCurrentScreen() instanceof OneConfigGui) { - return true; - } - for (Optional screen : GuiUtils.getScreenQueue()) { - if (screen.isPresent() && screen.get() instanceof OneConfigGui) { - return true; - } - } - return false; - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/VigilantHook.java b/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/VigilantHook.java deleted file mode 100644 index 7b66435..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/VigilantHook.java +++ /dev/null @@ -1,27 +0,0 @@ -package cc.polyfrost.oneconfig.internal.plugin.hooks; - -import cc.polyfrost.oneconfig.config.compatibility.vigilance.VigilanceConfig; -import cc.polyfrost.oneconfig.config.data.Mod; -import cc.polyfrost.oneconfig.config.data.ModType; -import cc.polyfrost.oneconfig.internal.config.core.ConfigCore; -import gg.essential.vigilance.Vigilant; -import net.minecraft.client.Minecraft; -import net.minecraftforge.fml.common.Loader; - -import java.io.File; - -@SuppressWarnings("unused") -public class VigilantHook { - public static VigilanceConfig returnNewConfig(Vigilant vigilant, File file) { - if (vigilant != null && Minecraft.getMinecraft().isCallingFromMinecraftThread()) { - String name = !vigilant.getGuiTitle().equals("Settings") ? vigilant.getGuiTitle() : Loader.instance().activeModContainer() == null ? "Unknown" : Loader.instance().activeModContainer().getName(); - if (name.equals("OneConfig")) name = "Essential"; - String finalName = name; - // duplicate fix - if (ConfigCore.mods.stream().anyMatch(mod -> mod.name.equals(finalName))) return null; - return new VigilanceConfig(new Mod(name, ModType.THIRD_PARTY), file.getAbsolutePath(), vigilant); - } else { - return null; - } - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/platform/GLPlatform.java b/src/main/java/cc/polyfrost/oneconfig/platform/GLPlatform.java new file mode 100644 index 0000000..b572527 --- /dev/null +++ b/src/main/java/cc/polyfrost/oneconfig/platform/GLPlatform.java @@ -0,0 +1,17 @@ +package cc.polyfrost.oneconfig.platform; + +import cc.polyfrost.oneconfig.libs.universal.UMatrixStack; + +public interface GLPlatform { + void drawRect(float x, float y, float x2, float y2, int color); + + void enableStencil(); + + default float drawText(String text, float x, float y, int color, boolean shadow) { + return drawText(null, text, x, y, color, shadow); + } + + float drawText(UMatrixStack matrixStack, String text, float x, float y, int color, boolean shadow); + + int getStringWidth(String text); +} diff --git a/src/main/java/cc/polyfrost/oneconfig/platform/GuiPlatform.java b/src/main/java/cc/polyfrost/oneconfig/platform/GuiPlatform.java new file mode 100644 index 0000000..b3e7221 --- /dev/null +++ b/src/main/java/cc/polyfrost/oneconfig/platform/GuiPlatform.java @@ -0,0 +1,8 @@ +package cc.polyfrost.oneconfig.platform; + +public interface GuiPlatform { + Object getCurrentScreen(); + void setCurrentScreen(Object screen); + boolean isInChat(); + boolean isInDebug(); +} diff --git a/src/main/java/cc/polyfrost/oneconfig/platform/I18nPlatform.java b/src/main/java/cc/polyfrost/oneconfig/platform/I18nPlatform.java new file mode 100644 index 0000000..bcc87a3 --- /dev/null +++ b/src/main/java/cc/polyfrost/oneconfig/platform/I18nPlatform.java @@ -0,0 +1,5 @@ +package cc.polyfrost.oneconfig.platform; + +public interface I18nPlatform { + String format(String key, Object... args); +} diff --git a/src/main/java/cc/polyfrost/oneconfig/platform/LoaderPlatform.java b/src/main/java/cc/polyfrost/oneconfig/platform/LoaderPlatform.java new file mode 100644 index 0000000..b07efa2 --- /dev/null +++ b/src/main/java/cc/polyfrost/oneconfig/platform/LoaderPlatform.java @@ -0,0 +1,19 @@ +package cc.polyfrost.oneconfig.platform; + +public interface LoaderPlatform { + boolean isModLoaded(String id); + boolean hasActiveModContainer(); + ActiveMod getActiveModContainer(); + + class ActiveMod { + public final String name; + public final String id; + public final String version; + + public ActiveMod(String name, String id, String version) { + this.name = name; + this.id = id; + this.version = version; + } + } +} diff --git a/src/main/java/cc/polyfrost/oneconfig/platform/MousePlatform.java b/src/main/java/cc/polyfrost/oneconfig/platform/MousePlatform.java new file mode 100644 index 0000000..add5f4f --- /dev/null +++ b/src/main/java/cc/polyfrost/oneconfig/platform/MousePlatform.java @@ -0,0 +1,15 @@ +package cc.polyfrost.oneconfig.platform; + +public interface MousePlatform { + int getMouseX(); + int getMouseY(); + int getDWheel(); + int getMouseDX(); + int getMouseDY(); + + boolean next(); + boolean getEventButtonState(); + int getEventButton(); + + boolean isButtonDown(int button); +} diff --git a/src/main/java/cc/polyfrost/oneconfig/platform/Platform.java b/src/main/java/cc/polyfrost/oneconfig/platform/Platform.java new file mode 100644 index 0000000..3eea049 --- /dev/null +++ b/src/main/java/cc/polyfrost/oneconfig/platform/Platform.java @@ -0,0 +1,55 @@ +package cc.polyfrost.oneconfig.platform; + +import java.util.ServiceLoader; + +/** + * Contains various platform-specific utilities for OneConfig. + * + * This is meant for internal usage, however other mods may use these (unless otherwise stated). + */ +public interface Platform { + + static Platform getInstance() { + return PlatformHolder.INSTANCE.platform; + } + + static MousePlatform getMousePlatform() { + return PlatformHolder.INSTANCE.mousePlatform; + } + + static LoaderPlatform getLoaderPlatform() { + return PlatformHolder.INSTANCE.loaderPlatform; + } + + static ServerPlatform getServerPlatform() { + return PlatformHolder.INSTANCE.serverPlatform; + } + + static GLPlatform getGLPlatform() { + return PlatformHolder.INSTANCE.glPlatform; + } + + static GuiPlatform getGuiPlatform() { + return PlatformHolder.INSTANCE.guiPlatform; + } + + static I18nPlatform getI18nPlatform() { + return PlatformHolder.INSTANCE.i18nPlatform; + } + + boolean isCallingFromMinecraftThread(); + + class PlatformHolder { + private PlatformHolder() { + + } + static PlatformHolder INSTANCE = new PlatformHolder(); + Platform platform = ServiceLoader.load(Platform.class, Platform.class.getClassLoader()).iterator().next(); + MousePlatform mousePlatform = ServiceLoader.load(MousePlatform.class, MousePlatform.class.getClassLoader()).iterator().next(); + LoaderPlatform loaderPlatform = ServiceLoader.load(LoaderPlatform.class, LoaderPlatform.class.getClassLoader()).iterator().next(); + ServerPlatform serverPlatform = ServiceLoader.load(ServerPlatform.class, ServerPlatform.class.getClassLoader()).iterator().next(); + GLPlatform glPlatform = ServiceLoader.load(GLPlatform.class, GLPlatform.class.getClassLoader()).iterator().next(); + GuiPlatform guiPlatform = ServiceLoader.load(GuiPlatform.class, GuiPlatform.class.getClassLoader()).iterator().next(); + I18nPlatform i18nPlatform = ServiceLoader.load(I18nPlatform.class, I18nPlatform.class.getClassLoader()).iterator().next(); + } +} diff --git a/src/main/java/cc/polyfrost/oneconfig/platform/ServerPlatform.java b/src/main/java/cc/polyfrost/oneconfig/platform/ServerPlatform.java new file mode 100644 index 0000000..01ab55d --- /dev/null +++ b/src/main/java/cc/polyfrost/oneconfig/platform/ServerPlatform.java @@ -0,0 +1,7 @@ +package cc.polyfrost.oneconfig.platform; + +public interface ServerPlatform { + boolean inMultiplayer(); + + String getServerBrand(); +} diff --git a/src/main/java/cc/polyfrost/oneconfig/renderer/RenderManager.java b/src/main/java/cc/polyfrost/oneconfig/renderer/RenderManager.java index b62d752..5869ffb 100644 --- a/src/main/java/cc/polyfrost/oneconfig/renderer/RenderManager.java +++ b/src/main/java/cc/polyfrost/oneconfig/renderer/RenderManager.java @@ -6,15 +6,13 @@ import cc.polyfrost.oneconfig.internal.assets.Colors; import cc.polyfrost.oneconfig.internal.assets.Images; import cc.polyfrost.oneconfig.internal.assets.SVGs; import cc.polyfrost.oneconfig.libs.universal.UGraphics; -import cc.polyfrost.oneconfig.libs.universal.UMinecraft; import cc.polyfrost.oneconfig.libs.universal.UResolution; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.font.Font; import cc.polyfrost.oneconfig.renderer.font.FontManager; import cc.polyfrost.oneconfig.renderer.font.Fonts; import cc.polyfrost.oneconfig.utils.InputUtils; import cc.polyfrost.oneconfig.utils.NetworkUtils; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.shader.Framebuffer; import org.lwjgl.nanovg.NVGColor; import org.lwjgl.nanovg.NVGPaint; import org.lwjgl.opengl.GL11; @@ -63,10 +61,7 @@ public final class RenderManager { FontManager.INSTANCE.initialize(vg); } - Framebuffer fb = UMinecraft.getMinecraft().getFramebuffer(); - if (!fb.isStencilEnabled()) { - fb.enableStencil(); - } + Platform.getGLPlatform().enableStencil(); GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); GL11.glDisable(GL11.GL_ALPHA_TEST); @@ -755,25 +750,15 @@ public final class RenderManager { yOff++; if (xOff * xOff != yOff * yOff) { yes += - //#if MODERN==0 - UMinecraft.getFontRenderer().drawString( + Platform.getGLPlatform().drawText( noColors, (xOff / 2f) + x, (yOff / 2f) + y, (opacity) << 24, false ); - //#else - //$$ draw( - //$$ matrix.toMC(), noColors, (xOff / 2f) + x, (yOff / 2f) + y, (opacity) shl 24 - //$$ ) - //#endif } } } } yes += - //#if MODERN==0 - UMinecraft.getFontRenderer().drawString(text, x, y, color, false); - //#else - //$$ draw(matrix.toMC(), text, x.toFloat(), y.toFloat(), color) - //#endif + Platform.getGLPlatform().drawText(text, x, y, color, false); return yes; } @@ -782,10 +767,10 @@ public final class RenderManager { UGraphics.GL.scale(scale, scale, 1); switch (type) { case NONE: - UMinecraft.getFontRenderer().drawString(text, x * (1 / scale), y * (1 / scale), color, false); + Platform.getGLPlatform().drawText(text, x * (1 / scale), y * (1 / scale), color, false); break; case SHADOW: - UMinecraft.getFontRenderer().drawString(text, x * (1 / scale), y * (1 / scale), color, true); + Platform.getGLPlatform().drawText(text, x * (1 / scale), y * (1 / scale), color, true); break; case FULL: drawBorderedText(text, x, y, color, 100); @@ -795,7 +780,7 @@ public final class RenderManager { } public static void drawGlRect(int x, int y, int width, int height, int color) { - Gui.drawRect(x, y, x + width, y + height, color); + Platform.getGLPlatform().drawRect(x, y, x + width, y + height, color); } public enum TextType { diff --git a/src/main/java/cc/polyfrost/oneconfig/test/TestConfig_Test.java b/src/main/java/cc/polyfrost/oneconfig/test/TestConfig_Test.java index a7ad2ac..772bba7 100644 --- a/src/main/java/cc/polyfrost/oneconfig/test/TestConfig_Test.java +++ b/src/main/java/cc/polyfrost/oneconfig/test/TestConfig_Test.java @@ -7,8 +7,8 @@ import cc.polyfrost.oneconfig.config.data.*; import cc.polyfrost.oneconfig.config.Config; import cc.polyfrost.oneconfig.config.data.ModType; import cc.polyfrost.oneconfig.config.migration.VigilanceMigrator; +import cc.polyfrost.oneconfig.libs.universal.UChat; import cc.polyfrost.oneconfig.libs.universal.UKeyboard; -import net.minecraftforge.fml.common.FMLCommonHandler; public class TestConfig_Test extends Config { @@ -59,9 +59,9 @@ public class TestConfig_Test extends Config { @Button( name = "Test Button", - text = "Crash game" + text = "Say hi" ) - Runnable runnable = () -> FMLCommonHandler.instance().exitJava(69, false); + Runnable runnable = () -> UChat.chat("HI!!!!"); @Slider( name = "Test Slider", diff --git a/src/main/java/cc/polyfrost/oneconfig/test/TestMod_Test.java b/src/main/java/cc/polyfrost/oneconfig/test/TestMod_Test.java deleted file mode 100644 index 98537f7..0000000 --- a/src/main/java/cc/polyfrost/oneconfig/test/TestMod_Test.java +++ /dev/null @@ -1,14 +0,0 @@ -package cc.polyfrost.oneconfig.test; - -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.common.event.FMLInitializationEvent; - -@net.minecraftforge.fml.common.Mod(modid = "oneconfig-test-mod", name = "Test Mod", version = "0") -public class TestMod_Test { - TestConfig_Test config; - - @Mod.EventHandler - public void init(FMLInitializationEvent event) { - config = new TestConfig_Test(); - } -} diff --git a/src/main/java/cc/polyfrost/oneconfig/test/TestMultilineHud_Test.java b/src/main/java/cc/polyfrost/oneconfig/test/TestMultilineHud_Test.java index 9055862..1665062 100644 --- a/src/main/java/cc/polyfrost/oneconfig/test/TestMultilineHud_Test.java +++ b/src/main/java/cc/polyfrost/oneconfig/test/TestMultilineHud_Test.java @@ -1,7 +1,6 @@ package cc.polyfrost.oneconfig.test; import cc.polyfrost.oneconfig.hud.TextHud; -import net.minecraft.client.Minecraft; import java.util.List; @@ -12,8 +11,6 @@ public class TestMultilineHud_Test extends TextHud { @Override protected void getLines(List lines) { - lines.clear(); lines.add(String.valueOf(System.currentTimeMillis())); - lines.add(String.valueOf(Minecraft.getSystemTime())); } } diff --git a/src/main/java/cc/polyfrost/oneconfig/test/TestNanoVGGui_Test.java b/src/main/java/cc/polyfrost/oneconfig/test/TestNanoVGGui_Test.java index 12a8735..e8b6b91 100644 --- a/src/main/java/cc/polyfrost/oneconfig/test/TestNanoVGGui_Test.java +++ b/src/main/java/cc/polyfrost/oneconfig/test/TestNanoVGGui_Test.java @@ -13,7 +13,6 @@ public class TestNanoVGGui_Test extends UScreen { @Override public void onDrawScreen(@NotNull UMatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { super.onDrawScreen(matrixStack, mouseX, mouseY, partialTicks); - drawRect(0, 0, width, height, Color.BLACK.getRGB()); long startTime = System.nanoTime(); RenderManager.setupAndDraw((vg) -> { RenderManager.drawRect(vg, 0, 0, 100, 100, Color.BLUE.getRGB()); diff --git a/src/main/java/cc/polyfrost/oneconfig/utils/InputUtils.java b/src/main/java/cc/polyfrost/oneconfig/utils/InputUtils.java index b7e620b..a48d369 100644 --- a/src/main/java/cc/polyfrost/oneconfig/utils/InputUtils.java +++ b/src/main/java/cc/polyfrost/oneconfig/utils/InputUtils.java @@ -2,9 +2,8 @@ package cc.polyfrost.oneconfig.utils; import cc.polyfrost.oneconfig.gui.OneConfigGui; import cc.polyfrost.oneconfig.libs.universal.UResolution; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.renderer.scissor.Scissor; -import cc.polyfrost.oneconfig.renderer.scissor.ScissorManager; -import org.lwjgl.input.Mouse; import java.util.ArrayList; @@ -74,7 +73,7 @@ public final class InputUtils { * @return true if the mouse is clicked, false if not */ public static boolean isClicked(boolean ignoreBlock) { - return OneConfigGui.INSTANCE != null && OneConfigGui.INSTANCE.mouseDown && !Mouse.isButtonDown(0) && (ignoreBlock || blockScissors.size() == 0 || !shouldBlock(mouseX(), mouseY())); + return OneConfigGui.INSTANCE != null && OneConfigGui.INSTANCE.mouseDown && !Platform.getMousePlatform().isButtonDown(0) && (ignoreBlock || blockScissors.size() == 0 || !shouldBlock(mouseX(), mouseY())); } /** @@ -97,8 +96,8 @@ public final class InputUtils { * @return the current mouse X position */ public static int mouseX() { - if (OneConfigGui.INSTANCE == null) return Mouse.getX(); - return (int) (Mouse.getX() / OneConfigGui.INSTANCE.getScaleFactor()); + if (OneConfigGui.INSTANCE == null) return Platform.getMousePlatform().getMouseX(); + return (int) (Platform.getMousePlatform().getMouseX() / OneConfigGui.INSTANCE.getScaleFactor()); } /** @@ -111,8 +110,8 @@ public final class InputUtils { * @return the current mouse Y position */ public static int mouseY() { - if (OneConfigGui.INSTANCE == null) return UResolution.getWindowHeight() - Math.abs(Mouse.getY()); - return (int) ((UResolution.getWindowHeight() - Math.abs(Mouse.getY())) / OneConfigGui.INSTANCE.getScaleFactor()); + if (OneConfigGui.INSTANCE == null) return UResolution.getWindowHeight() - Math.abs(Platform.getMousePlatform().getMouseY()); + return (int) ((UResolution.getWindowHeight() - Math.abs(Platform.getMousePlatform().getMouseY())) / OneConfigGui.INSTANCE.getScaleFactor()); } /** diff --git a/src/main/java/cc/polyfrost/oneconfig/utils/commands/CommandManager.java b/src/main/java/cc/polyfrost/oneconfig/utils/commands/CommandManager.java index 004f427..16a2f8d 100644 --- a/src/main/java/cc/polyfrost/oneconfig/utils/commands/CommandManager.java +++ b/src/main/java/cc/polyfrost/oneconfig/utils/commands/CommandManager.java @@ -1,19 +1,10 @@ package cc.polyfrost.oneconfig.utils.commands; -import cc.polyfrost.oneconfig.utils.commands.annotations.*; +import cc.polyfrost.oneconfig.utils.commands.annotations.Command; +import cc.polyfrost.oneconfig.utils.commands.annotations.Main; +import cc.polyfrost.oneconfig.utils.commands.annotations.SubCommand; import cc.polyfrost.oneconfig.utils.commands.arguments.*; -import cc.polyfrost.oneconfig.libs.universal.ChatColor; -import cc.polyfrost.oneconfig.libs.universal.UChat; -import net.minecraft.command.CommandBase; -import net.minecraft.command.ICommandSender; -import net.minecraft.util.BlockPos; -import net.minecraftforge.client.ClientCommandHandler; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.ImmutableTriple; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.commons.lang3.tuple.Triple; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; @@ -25,11 +16,12 @@ import java.util.*; * @see Command */ public class CommandManager { + private static final PlatformCommandManager platform = ServiceLoader.load(PlatformCommandManager.class, PlatformCommandManager.class.getClassLoader()).iterator().next(); public static final CommandManager INSTANCE = new CommandManager(); - private static final String NOT_FOUND_TEXT = "Command not found! Type /@ROOT_COMMAND@ help for help."; - private static final String TOO_MANY_PARAMETERS = "There were too many / little parameters for this command! Type /@ROOT_COMMAND@ help for help."; - private static final String METHOD_RUN_ERROR = "Error while running @ROOT_COMMAND@ method! Please report this to the developer."; - private final HashMap, ArgumentParser> parsers = new HashMap<>(); + static final String NOT_FOUND_TEXT = "Command not found! Type /@ROOT_COMMAND@ help for help."; + static final String TOO_MANY_PARAMETERS = "There were too many / little parameters for this command! Type /@ROOT_COMMAND@ help for help."; + static final String METHOD_RUN_ERROR = "Error while running @ROOT_COMMAND@ method! Please report this to the developer."; + final HashMap, ArgumentParser> parsers = new HashMap<>(); private CommandManager() { addParser(new StringParser()); @@ -79,305 +71,7 @@ public class CommandManager { } } addToInvokers(clazz.getDeclaredClasses(), root); - ClientCommandHandler.instance.registerCommand(new CommandBase() { - @Override - public String getCommandName() { - return annotation.value(); - } - - @Override - public String getCommandUsage(ICommandSender sender) { - return "/" + annotation.value(); - } - - @Override - public void processCommand(ICommandSender sender, String[] args) { - handleCommand(root, annotation, args); - } - - @Override - public int getRequiredPermissionLevel() { - return -1; - } - - @Override - public List addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) { - return handleTabCompletion(root, annotation, args); - } - }); - } - } - - private void handleCommand(InternalCommand root, Command annotation, String[] args) { - if (args.length == 0) { - if (!root.invokers.isEmpty()) { - try { - root.invokers.get(0).method.invoke(null); - } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException | - ExceptionInInitializerError e) { - e.printStackTrace(); - UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + METHOD_RUN_ERROR); - } - } - } else { - if (annotation.helpCommand() && args[0].equalsIgnoreCase("help")) { - UChat.chat(sendHelpCommand(root)); - } else { - List commands = new ArrayList<>(); - int depth = 0; - for (InternalCommand command : root.children) { - int newDepth = loopThroughCommands(commands, 0, command, args); - if (newDepth != -1) { - depth = newDepth; - break; - } - } - if (commands.isEmpty()) { - if (depth == -2) { - UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + TOO_MANY_PARAMETERS.replace("@ROOT_COMMAND@", annotation.value())); - } else { - UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + NOT_FOUND_TEXT.replace("@ROOT_COMMAND@", annotation.value())); - } - } else { - List errors = new ArrayList<>(); - for (InternalCommand.InternalCommandInvoker invoker : commands) { - try { - List params = getParametersForInvoker(invoker, depth, args); - if (params.size() == 1) { - Object first = params.get(0); - if (first instanceof CustomError) { - errors.add((CustomError) first); - continue; - } - } - invoker.method.invoke(null, params.toArray()); - return; - } catch (Exception e) { - e.printStackTrace(); - UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + METHOD_RUN_ERROR); - return; - } - } - //noinspection ConstantConditions - if (!errors.isEmpty()) { - UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + "Multiple errors occurred:"); - for (CustomError error : errors) { - UChat.chat(" " + ChatColor.RED + ChatColor.BOLD + error.message); - } - } - } - } - } - } - - private List handleTabCompletion(InternalCommand root, Command annotation, String[] args) { - try { - Set> commands = new HashSet<>(); - for (InternalCommand command : root.children) { - loopThroughCommandsTab(commands, 0, command, args); - } - if (!commands.isEmpty() || annotation.helpCommand()) { - List> validCommands = new ArrayList<>(); // command, depth, and all processed params - for (Pair pair : commands) { - InternalCommand.InternalCommandInvoker invoker = pair.getLeft(); - int depth = pair.getRight(); - int currentParam = 0; - boolean failed = false; - while (args.length - depth > 1) { - Parameter param = invoker.method.getParameters()[currentParam]; - if (param.isAnnotationPresent(Greedy.class) && currentParam + 1 != invoker.parameterTypes.length) { - failed = true; - break; - } - ArgumentParser parser = parsers.get(param.getType()); - if (parser == null) { - failed = true; - break; - } - try { - Arguments arguments = new Arguments(Arrays.copyOfRange(args, depth, args.length), param.isAnnotationPresent(Greedy.class)); - if (parser.parse(arguments) != null) { - depth += arguments.getPosition(); - currentParam++; - } else { - failed = true; - break; - } - } catch (Exception e) { - failed = true; - break; - } - } - if (!failed) { - validCommands.add(new ImmutableTriple<>(pair.getLeft(), depth, currentParam)); - } - } - if (!validCommands.isEmpty() || annotation.helpCommand()) { - Set completions = new HashSet<>(); - for (Triple valid : validCommands) { - if (valid.getMiddle() == args.length) { - completions.add(valid.getLeft().name); - completions.addAll(Arrays.asList(valid.getLeft().aliases)); - continue; - } - if (valid.getRight() + 1 > valid.getLeft().parameterTypes.length) continue; - Parameter param = valid.getLeft().method.getParameters()[valid.getRight()]; - if (param.isAnnotationPresent(Greedy.class) && valid.getRight() + 1 != valid.getLeft().parameterTypes.length) { - continue; - } - ArgumentParser parser = parsers.get(param.getType()); - if (parser == null) { - continue; - } - try { - Arguments arguments = new Arguments(Arrays.copyOfRange(args, valid.getMiddle(), args.length), param.isAnnotationPresent(Greedy.class)); - List possibleCompletions = parser.complete(arguments, param); - if (possibleCompletions != null) { - completions.addAll(possibleCompletions); - } - } catch (Exception ignored) { - - } - } - if (args.length == 1 && annotation.helpCommand()) { - if ("help".startsWith(args[0].toLowerCase(Locale.ENGLISH))) { - completions.add("help"); - } - } - return new ArrayList<>(completions); - } - } - } catch (Exception ignored) { - - } - return null; - } - - private List getParametersForInvoker(InternalCommand.InternalCommandInvoker invoker, int depth, String[] args) { - List parameters = new ArrayList<>(); - int processed = depth; - int currentParam = 0; - while (processed < args.length) { - Parameter param = invoker.method.getParameters()[currentParam]; - if (param.isAnnotationPresent(Greedy.class) && currentParam + 1 != invoker.parameterTypes.length) { - return Collections.singletonList(new CustomError("Parsing failed: Greedy parameter must be the last one.")); - } - ArgumentParser parser = parsers.get(param.getType()); - if (parser == null) { - return Collections.singletonList(new CustomError("No parser for " + invoker.method.getParameterTypes()[currentParam].getSimpleName() + "! Please report this to the mod author.")); - } - try { - Arguments arguments = new Arguments(Arrays.copyOfRange(args, processed, args.length), param.isAnnotationPresent(Greedy.class)); - try { - Object a = parser.parse(arguments); - if (a != null) { - parameters.add(a); - processed += arguments.getPosition(); - currentParam++; - } else { - return Collections.singletonList(new CustomError("Failed to parse " + param.getType().getSimpleName() + "! Please report this to the mod author.")); - } - } catch (Exception e) { - return Collections.singletonList(new CustomError("A " + e.getClass().getSimpleName() + " has occured while try to parse " + param.getType().getSimpleName() + "! Please report this to the mod author.")); - } - } catch (Exception e) { - return Collections.singletonList(new CustomError("A " + e.getClass().getSimpleName() + " has occured while try to parse " + param.getType().getSimpleName() + "! Please report this to the mod author.")); - } - } - return parameters; - } - - private int loopThroughCommands(List commands, int depth, InternalCommand command, String[] args) { - int nextDepth = depth + 1; - boolean thatOneSpecialError = false; - if (command.isValid(args[depth], false)) { - for (InternalCommand child : command.children) { - if (args.length > nextDepth && child.isValid(args[nextDepth], false)) { - int result = loopThroughCommands(commands, nextDepth, child, args); - if (result > -1) { - return result; - } else if (result == -2) { - thatOneSpecialError = true; - } - } - } - boolean added = false; - for (InternalCommand.InternalCommandInvoker invoker : command.invokers) { - if (args.length - nextDepth == invoker.parameterTypes.length) { - commands.add(invoker); - added = true; - } else { - thatOneSpecialError = true; - } - } - if (added) { - return nextDepth; - } - } - return thatOneSpecialError ? -2 : -1; - } - - private void loopThroughCommandsTab(Set> commands, int depth, InternalCommand command, String[] args) { - int nextDepth = depth + 1; - if (command.isValid(args[depth], args.length == nextDepth)) { - if (args.length != nextDepth) { - for (InternalCommand child : command.children) { - if (child.isValid(args[nextDepth], args.length == nextDepth + 1)) { - loopThroughCommandsTab(commands, nextDepth, child, args); - } - } - } - for (InternalCommand.InternalCommandInvoker invoker : command.invokers) { - commands.add(new ImmutablePair<>(invoker, nextDepth)); - } - } - } - - //TODO: someone make the help command actually look nice lmao - private String sendHelpCommand(InternalCommand root) { - StringBuilder builder = new StringBuilder(); - builder.append(ChatColor.GOLD).append("Help for ").append(ChatColor.BOLD).append(root.name).append(ChatColor.RESET).append(ChatColor.GOLD).append(":\n"); - if (!root.description.isEmpty()) { - builder.append("\n").append(ChatColor.GOLD).append("Description: ").append(ChatColor.BOLD).append(root.description); - } - for (InternalCommand command : root.children) { - runThroughCommandsHelp(root.name, command, builder); - } - builder.append("\n").append(ChatColor.GOLD).append("Aliases: ").append(ChatColor.BOLD); - int index = 0; - for (String alias : root.aliases) { - ++index; - builder.append(alias).append(index < root.aliases.length ? ", " : ""); - } - builder.append("\n"); - return builder.toString(); - } - - private void runThroughCommandsHelp(String append, InternalCommand command, StringBuilder builder) { - if (!command.invokers.isEmpty()) { - Class declaringClass = command.invokers.get(0).method.getDeclaringClass(); - if (declaringClass.isAnnotationPresent(SubCommand.class)) { - String description = declaringClass.getAnnotation(SubCommand.class).description(); - if (!description.isEmpty()) { - builder.append("\n").append(ChatColor.GOLD).append("Description: ").append(ChatColor.BOLD).append(description); - } - } - } - for (InternalCommand.InternalCommandInvoker invoker : command.invokers) { - builder.append("\n").append(ChatColor.GOLD).append("/").append(append).append(" ").append(command.name); - for (Parameter parameter : invoker.method.getParameters()) { - String name = parameter.getName(); - if (parameter.isAnnotationPresent(Name.class)) { - name = parameter.getAnnotation(Name.class).value(); - } - builder.append(" <").append(name).append(">"); - } - if (!command.description.trim().isEmpty()) { - builder.append(": ").append(ChatColor.BOLD).append(command.description); - } - } - for (InternalCommand subCommand : command.children) { - runThroughCommandsHelp(append + " " + command.name, subCommand, builder); + platform.createCommand(root, annotation); } } @@ -397,7 +91,7 @@ public class CommandManager { } } - private static class CustomError { + static class CustomError { public String message; public CustomError(String message) { @@ -405,7 +99,7 @@ public class CommandManager { } } - private static class InternalCommand { + static class InternalCommand { public final String name; public final String[] aliases; public final String description; diff --git a/src/main/java/cc/polyfrost/oneconfig/utils/commands/PlatformCommandManager.java b/src/main/java/cc/polyfrost/oneconfig/utils/commands/PlatformCommandManager.java new file mode 100644 index 0000000..a02f4ff --- /dev/null +++ b/src/main/java/cc/polyfrost/oneconfig/utils/commands/PlatformCommandManager.java @@ -0,0 +1,7 @@ +package cc.polyfrost.oneconfig.utils.commands; + +import cc.polyfrost.oneconfig.utils.commands.annotations.Command; + +public interface PlatformCommandManager { + void createCommand(CommandManager.InternalCommand root, Command annotation); +} diff --git a/src/main/java/cc/polyfrost/oneconfig/utils/gui/GuiUtils.java b/src/main/java/cc/polyfrost/oneconfig/utils/gui/GuiUtils.java index 6ff0254..63203e4 100644 --- a/src/main/java/cc/polyfrost/oneconfig/utils/gui/GuiUtils.java +++ b/src/main/java/cc/polyfrost/oneconfig/utils/gui/GuiUtils.java @@ -6,13 +6,8 @@ import cc.polyfrost.oneconfig.events.event.Stage; import cc.polyfrost.oneconfig.gui.OneConfigGui; import cc.polyfrost.oneconfig.libs.eventbus.Subscribe; import cc.polyfrost.oneconfig.libs.universal.UMinecraft; -import cc.polyfrost.oneconfig.libs.universal.UScreen; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.utils.TickDelay; -import net.minecraft.client.gui.GuiScreen; - -import java.util.Deque; -import java.util.Optional; -import java.util.concurrent.ConcurrentLinkedDeque; /** * A class containing utility methods for working with GuiScreens. @@ -20,7 +15,6 @@ import java.util.concurrent.ConcurrentLinkedDeque; public final class GuiUtils { private static long time = -1L; private static long deltaTime = 17L; - private static final Deque> screenQueue = new ConcurrentLinkedDeque<>(); static { EventManager.INSTANCE.register(new GuiUtils()); @@ -30,8 +24,10 @@ public final class GuiUtils { * Displays a screen after a tick, preventing mouse sync issues. * * @param screen the screen to display. + * @deprecated Not actually deprecated, but should not be used. */ - public static void displayScreen(GuiScreen screen) { + @Deprecated + public static void displayScreen(Object screen) { displayScreen(screen, screen instanceof OneConfigGui ? 2 : 1); } @@ -41,24 +37,15 @@ public final class GuiUtils { * @param screen the screen to display. * @param ticks the amount of ticks to wait for before displaying the screen. */ - public static void displayScreen(GuiScreen screen, int ticks) { - Optional optional = Optional.of(screen); - screenQueue.add(optional); - new TickDelay(() -> { - UScreen.displayScreen(screen); - screenQueue.remove(optional); - }, ticks); - } - - public static Deque> getScreenQueue() { - return screenQueue; + public static void displayScreen(Object screen, int ticks) { + new TickDelay(() -> Platform.getGuiPlatform().setCurrentScreen(screen), ticks); } /** * Close the current open GUI screen. */ public static void closeScreen() { - UScreen.displayScreen(null); + Platform.getGuiPlatform().setCurrentScreen(null); } /** diff --git a/src/main/java/cc/polyfrost/oneconfig/utils/gui/OneUIScreen.java b/src/main/java/cc/polyfrost/oneconfig/utils/gui/OneUIScreen.java index 7459224..2dd961e 100644 --- a/src/main/java/cc/polyfrost/oneconfig/utils/gui/OneUIScreen.java +++ b/src/main/java/cc/polyfrost/oneconfig/utils/gui/OneUIScreen.java @@ -1,12 +1,12 @@ package cc.polyfrost.oneconfig.utils.gui; -import cc.polyfrost.oneconfig.renderer.RenderManager; -import cc.polyfrost.oneconfig.utils.InputUtils; +import cc.polyfrost.oneconfig.gui.GuiPause; import cc.polyfrost.oneconfig.libs.universal.UMatrixStack; import cc.polyfrost.oneconfig.libs.universal.UScreen; -import net.minecraft.client.gui.GuiScreen; +import cc.polyfrost.oneconfig.platform.Platform; +import cc.polyfrost.oneconfig.renderer.RenderManager; +import cc.polyfrost.oneconfig.utils.InputUtils; import org.jetbrains.annotations.NotNull; -import org.lwjgl.input.Mouse; /** *

OneUIScreen

@@ -14,9 +14,9 @@ import org.lwjgl.input.Mouse; * It contains many handy methods for rendering, including {@link #draw(long, float)} for drawing using OneConfig's {@link RenderManager}. *

It also contains methods for mouse input. (see {@link InputUtils} for more utils). *

- * Use {@link GuiUtils#displayScreen(GuiScreen)} to display a screen; and {@link GuiUtils#closeScreen()} to close it. + * Use GuiUtils to display a screen; and GuiUtils.closeScreen to close it. */ -public abstract class OneUIScreen extends UScreen { +public abstract class OneUIScreen extends UScreen implements GuiPause { private boolean mouseDown; private boolean blockClicks; @@ -40,7 +40,7 @@ public abstract class OneUIScreen extends UScreen { public void onDrawScreen(@NotNull UMatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { super.onDrawScreen(matrixStack, mouseX, mouseY, partialTicks); RenderManager.setupAndDraw(ignoreMinecraftScale(), vg -> draw(vg, partialTicks)); - mouseDown = Mouse.isButtonDown(0); + mouseDown = Platform.getMousePlatform().isButtonDown(0); } /** @@ -76,19 +76,6 @@ public abstract class OneUIScreen extends UScreen { return true; } - /** - * Use this method to declare weather or not this Screen pauses the game when it is open. (Single-player only) Its default is false. - */ - public boolean doesScreenPauseGame() { - return false; - } - - @Override - public boolean doesGuiPauseGame() { - return doesScreenPauseGame(); - } - - /** * Get the current x position of the mouse. */ @@ -114,7 +101,7 @@ public abstract class OneUIScreen extends UScreen { * @param ignoreBlockClicks whether to ignore the current click blocker. */ public boolean isClicked(boolean ignoreBlockClicks) { - return mouseDown && !Mouse.isButtonDown(0) && (!blockClicks || ignoreBlockClicks); + return mouseDown && !Platform.getMousePlatform().isButtonDown(0) && (!blockClicks || ignoreBlockClicks); } /** @@ -128,7 +115,7 @@ public abstract class OneUIScreen extends UScreen { * Retrieve weather or not the mouse is currently down. Will constantly return true if its clicked. See {@link #isClicked()} for a method that only executes once per tick. */ public boolean isMouseDown() { - return Mouse.isButtonDown(0); + return Platform.getMousePlatform().isButtonDown(0); } /** diff --git a/src/main/java/cc/polyfrost/oneconfig/utils/hypixel/HypixelUtils.java b/src/main/java/cc/polyfrost/oneconfig/utils/hypixel/HypixelUtils.java index 5489946..3e719de 100644 --- a/src/main/java/cc/polyfrost/oneconfig/utils/hypixel/HypixelUtils.java +++ b/src/main/java/cc/polyfrost/oneconfig/utils/hypixel/HypixelUtils.java @@ -2,18 +2,15 @@ package cc.polyfrost.oneconfig.utils.hypixel; import cc.polyfrost.oneconfig.events.EventManager; import cc.polyfrost.oneconfig.events.event.*; +import cc.polyfrost.oneconfig.libs.eventbus.Subscribe; +import cc.polyfrost.oneconfig.libs.universal.UChat; +import cc.polyfrost.oneconfig.platform.Platform; import cc.polyfrost.oneconfig.utils.JsonUtils; import cc.polyfrost.oneconfig.utils.Multithreading; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import cc.polyfrost.oneconfig.libs.universal.UChat; -import cc.polyfrost.oneconfig.libs.universal.UMinecraft; -import cc.polyfrost.oneconfig.libs.universal.wrappers.UPlayer; -import cc.polyfrost.oneconfig.libs.universal.wrappers.message.UTextComponent; -import cc.polyfrost.oneconfig.libs.eventbus.Subscribe; -import net.minecraftforge.fml.common.Loader; import java.util.Locale; import java.util.concurrent.TimeUnit; @@ -46,7 +43,7 @@ public class HypixelUtils { return; } EventManager.INSTANCE.register(this); - isSeraph = Loader.isModLoaded("seraph"); + isSeraph = Platform.getLoaderPlatform().isModLoaded("seraph"); initialized = true; } @@ -57,11 +54,9 @@ public class HypixelUtils { * @see this discord link from jade / asbyth */ public boolean isHypixel() { - if (UMinecraft.getWorld() == null || UMinecraft.getMinecraft().isSingleplayer()) return false; + if (!Platform.getServerPlatform().inMultiplayer()) return false; - net.minecraft.client.entity.EntityPlayerSP player = UPlayer.getPlayer(); - if (player == null) return false; - String serverBrand = player.getClientBrand(); + String serverBrand = Platform.getServerPlatform().getServerBrand(); if (serverBrand == null) return false; @@ -108,7 +103,7 @@ public class HypixelUtils { @Subscribe private void onMessageReceived(ChatReceiveEvent event) { try { - final String msg = UTextComponent.Companion.stripFormatting(event.message.getUnformattedText()); + final String msg = event.getFullyUnformattedMessage(); // Checking for rate limitation. if (!(msg.startsWith("{") && msg.endsWith("}"))) { if (sentCommand && msg.contains("You are sending too many commands! Please try again in a few seconds.")) // if you're being rate limited, the /locraw command will be resent in 5 seconds. diff --git a/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/DSLs.kt b/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/DSLs.kt deleted file mode 100644 index c8c18e4..0000000 --- a/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/DSLs.kt +++ /dev/null @@ -1,9 +0,0 @@ -package cc.polyfrost.oneconfig.utils.dsl - -import cc.polyfrost.oneconfig.libs.universal.UMinecraft - -/** - * Gets the current [net.minecraft.client.Minecraft] instance. - */ -val mc - get() = UMinecraft.getMinecraft() \ No newline at end of file diff --git a/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/GuiUtilsDSL.kt b/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/GuiUtilsDSL.kt deleted file mode 100644 index c70f686..0000000 --- a/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/GuiUtilsDSL.kt +++ /dev/null @@ -1,11 +0,0 @@ -package cc.polyfrost.oneconfig.utils.dsl - -import cc.polyfrost.oneconfig.utils.gui.GuiUtils -import net.minecraft.client.gui.GuiScreen - -/** - * Displays a screen after the specified amount of ticks. - * - * @param ticks the amount of ticks to wait for before displaying the screen. - */ -fun GuiScreen.openScreen(ticks: Int = 1) = GuiUtils.displayScreen(this, ticks) \ No newline at end of file diff --git a/src/main/resources/mixins.oneconfig.json b/src/main/resources/mixins.oneconfig.json deleted file mode 100644 index e1e0449..0000000 --- a/src/main/resources/mixins.oneconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "compatibilityLevel": "JAVA_8", - "minVersion": "0.7", - "package": "cc.polyfrost.oneconfig.internal.mixin", - "refmap": "mixins.oneconfig.refmap.json", - "plugin": "cc.polyfrost.oneconfig.internal.plugin.OneConfigMixinPlugin", - "injectors": { - "maxShiftBy": 5 - }, - "verbose": true, - "client": [ - "FontRendererMixin", - "GuiIngameForgeMixin", - "MinecraftMixin", - "NetHandlerPlayClientMixin", - "NetworkManagerMixin", - "OptifineConfigMixin", - "ShaderGroupAccessor", - "VigilantMixin", - "WorldClientMixin" - ] -} \ No newline at end of file diff --git a/versions/build.gradle.kts b/versions/build.gradle.kts new file mode 100644 index 0000000..939e61b --- /dev/null +++ b/versions/build.gradle.kts @@ -0,0 +1,306 @@ +import gg.essential.gradle.util.RelocationTransform.Companion.registerRelocationAttribute +import gg.essential.gradle.util.noServerRunConfigs +import gg.essential.gradle.util.prebundle +import net.fabricmc.loom.task.RemapSourcesJarTask + + +plugins { + kotlin("jvm") + id("gg.essential.multi-version") + id("gg.essential.defaults.repo") + id("gg.essential.defaults.java") + id("gg.essential.defaults.loom") + id("net.kyori.blossom") version "1.3.0" + id("org.jetbrains.dokka") version "1.6.21" + id("maven-publish") + id("signing") + java +} + +kotlin.jvmToolchain { + (this as JavaToolchainSpec).languageVersion.set(JavaLanguageVersion.of(8)) +} + +java { + withSourcesJar() +} + +val mod_name: String by project +val mod_version: String by project +val mod_id: String by project + +preprocess { + vars.put("MODERN", if (project.platform.mcMinor >= 16) 1 else 0) +} + +blossom { + replaceToken("@VER@", mod_version) + replaceToken("@NAME@", mod_name) + replaceToken("@ID@", mod_id) +} + +version = mod_version +group = "cc.polyfrost" +base { + archivesName.set("$mod_id-$platform") +} +loom { + noServerRunConfigs() + if (project.platform.isLegacyForge) { + launchConfigs.named("client") { + arg("--tweakClass", "cc.polyfrost.oneconfig.internal.plugin.asm.OneConfigTweaker") + property("mixin.debug.export", "true") + property("debugBytecode", "true") + } + } + if (project.platform.isForge) { + forge { + mixinConfig("mixins.${mod_id}.json") + } + } + mixin.defaultRefmapName.set("mixins.${mod_id}.refmap.json") +} + +repositories { + maven("https://repo.polyfrost.cc/releases") +} + +val relocated = registerRelocationAttribute("relocate") { + relocate("gg.essential", "cc.polyfrost.oneconfig.libs") + relocate("me.kbrewster", "cc.polyfrost.oneconfig.libs") + relocate("com.github.benmanes", "cc.polyfrost.oneconfig.libs") + relocate("com.google", "cc.polyfrost.oneconfig.libs") + relocate("org.checkerframework", "cc.polyfrost.oneconfig.libs") + remapStringsIn("com.github.benmanes.caffeine.cache.LocalCacheFactory") + remapStringsIn("com.github.benmanes.caffeine.cache.NodeFactory") +} + +val shadeRelocated: Configuration by configurations.creating { + attributes { attribute(relocated, true) } +} + +val shade: Configuration by configurations.creating { + configurations.api.get().extendsFrom(this) +} + +val shadeNoPom: Configuration by configurations.creating + +sourceSets { + main { + output.setResourcesDir(java.classesDirectory) + } +} + +dependencies { + compileOnly("gg.essential:vigilance-$platform:222") { + isTransitive = false + } + + shadeRelocated("gg.essential:universalcraft-$platform:211") { + isTransitive = false + } + + shadeRelocated("com.github.KevinPriv:keventbus:c52e0a2ea0") { + isTransitive = false + } + + @Suppress("GradlePackageUpdate") + shadeRelocated("com.github.ben-manes.caffeine:caffeine:2.9.3") + + // for other mods and universalcraft + val kotlinVersion: String by project + val coroutinesVersion: String by project + val serializationVersion: String by project + val atomicfuVersion: String by project + shade("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion") + shade("org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion") + shade("org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion") + shade("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion") + + shade("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion") + shade("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:$coroutinesVersion") + shade("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:$coroutinesVersion") + shade("org.jetbrains.kotlinx:kotlinx-serialization-core-jvm:$serializationVersion") + shade("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:$serializationVersion") + shade("org.jetbrains.kotlinx:kotlinx-serialization-cbor-jvm:$serializationVersion") + shade("org.jetbrains.kotlinx:atomicfu-jvm:$atomicfuVersion") + + shade("org.spongepowered:mixin:0.7.11-SNAPSHOT") { + isTransitive = false + } + shadeNoPom(project(":")) { + isTransitive = false + } + shade("cc.polyfrost:lwjgl:1.0.0-alpha1") + shadeNoPom(prebundle(shadeRelocated)) + + dokkaHtmlPlugin("org.jetbrains.dokka:kotlin-as-java-plugin:1.6.21") + + configurations.named(JavaPlugin.COMPILE_CLASSPATH_CONFIGURATION_NAME) { extendsFrom(shadeNoPom) } + configurations.named(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME) { extendsFrom(shadeNoPom) } +} + +tasks { + processResources { + inputs.property("id", mod_id) + inputs.property("name", mod_name) + val java = if (project.platform.mcMinor >= 18) { + 17 + } else { + if (project.platform.mcMinor == 17) 16 else 8 + } + val compatLevel = "JAVA_${java}" + inputs.property("java", java) + inputs.property("java_level", compatLevel) + inputs.property("version", mod_version) + inputs.property("mcVersionStr", project.platform.mcVersionStr) + filesMatching(listOf("mcmod.info", "mixins.${mod_id}.json", "mods.toml")) { + expand( + mapOf( + "id" to mod_id, + "name" to mod_name, + "java" to java, + "java_level" to compatLevel, + "version" to mod_version, + "mcVersionStr" to project.platform.mcVersionStr + ) + ) + } + filesMatching("fabric.mod.json") { + expand( + mapOf( + "id" to mod_id, + "name" to mod_name, + "java" to java, + "java_level" to compatLevel, + "version" to mod_version, + "mcVersionStr" to project.platform.mcVersionStr.substringBeforeLast(".") + ".x" + ) + ) + } + } + + withType(Jar::class.java) { + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + if (project.platform.isFabric) { + exclude("mcmod.info", "mods.toml") + } else { + exclude("fabric.mod.json") + if (project.platform.isLegacyForge) { + exclude("mods.toml") + exclude("META-INF/versions/**") + exclude("**/module-info.class") + exclude("**/package-info.class") + } else { + exclude("mcmod.info") + } + } + if (!name.contains("sourcesjar", ignoreCase = true) || !name.contains("dokka", ignoreCase = true)) { + exclude("**/**_Test.**") + exclude("**/**_Test$**.**") + } + } + + remapJar { + archiveClassifier.set("full") + } + + fun Jar.excludeInternal() { + exclude("**/internal/**") + } + jar { + dependsOn(shadeNoPom, shade) + from({ ArrayList().also { it.addAll(shadeNoPom); it.addAll(shade) }.map { if (it.isDirectory) it else zipTree(it) } }) + manifest { + attributes( + mapOf( + "ModSide" to "CLIENT", + "ForceLoadAsMod" to true, + "TweakOrder" to "0", + "MixinConfigs" to "mixins.oneconfig.json", + "TweakClass" to "cc.polyfrost.oneconfig.internal.plugin.asm.OneConfigTweaker" + ) + ) + } + excludeInternal() + archiveClassifier.set("") + } + dokkaHtml.configure { + outputDirectory.set(buildDir.resolve("dokka")) + moduleName.set("OneConfig $platform") + moduleVersion.set(mod_version) + dokkaSourceSets { + configureEach { + jdkVersion.set(8) + //reportUndocumented.set(true) + } + } + doLast { + val outputFile = outputDirectory.get().resolve("images/logo-icon.svg") + if (outputFile.exists()) { + outputFile.delete() + } + val inputFile = project.rootDir.resolve("src/main/resources/assets/oneconfig/icons/OneConfig.svg") + inputFile.copyTo(outputFile) + } + } + val dokkaJar = create("dokkaJar", Jar::class.java) { + archiveClassifier.set("dokka") + group = "build" + dependsOn(dokkaHtml) + from(layout.buildDirectory.dir("dokka")) + } + named("sourcesJar") { + from(project(":").sourceSets.main.map { it.allSource }) + dependsOn(dokkaJar) + excludeInternal() + archiveClassifier.set("sources") + doFirst { + archiveClassifier.set("sources") + } + } + withType { + enabled = false + } +} + +publishing { + publications { + register("oneconfig-$platform") { + groupId = "cc.polyfrost" + artifactId = base.archivesName.get() + + artifact(tasks["jar"]) + artifact(tasks["remapJar"]) + artifact(tasks["sourcesJar"]) + artifact(tasks["dokkaJar"]) + } + } + + repositories { + maven { + name = "releases" + url = uri("https://repo.polyfrost.cc/releases") + credentials(PasswordCredentials::class) + authentication { + create("basic") + } + } + maven { + name = "snapshots" + url = uri("https://repo.polyfrost.cc/snapshots") + credentials(PasswordCredentials::class) + authentication { + create("basic") + } + } + maven { + name = "private" + url = uri("https://repo.polyfrost.cc/private") + credentials(PasswordCredentials::class) + authentication { + create("basic") + } + } + } +} \ No newline at end of file diff --git a/versions/root.gradle.kts b/versions/root.gradle.kts new file mode 100644 index 0000000..f23a159 --- /dev/null +++ b/versions/root.gradle.kts @@ -0,0 +1,9 @@ +plugins { + kotlin("jvm") version "1.6.21" apply false + id("gg.essential.multi-version.root") + id("io.github.juuxel.loom-quiltflower-mini") version "171a6e2e49" apply false +} + +preprocess { + "1.8.9-forge"(10809, "srg") {} +} \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/events/event/ChatReceiveEvent.java b/versions/src/main/java/cc/polyfrost/oneconfig/events/event/ChatReceiveEvent.java new file mode 100644 index 0000000..6585729 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/events/event/ChatReceiveEvent.java @@ -0,0 +1,22 @@ +package cc.polyfrost.oneconfig.events.event; + +import cc.polyfrost.oneconfig.libs.universal.wrappers.message.UTextComponent; +import net.minecraft.util.IChatComponent; + +/** + * Called when a chat message is received. + */ +public class ChatReceiveEvent extends CancellableEvent { + /** + * The message that was received. + */ + public final IChatComponent message; + + public ChatReceiveEvent(IChatComponent message) { + this.message = message; + } + + public String getFullyUnformattedMessage() { + return UTextComponent.Companion.stripFormatting(message.getUnformattedText()); + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/events/event/ReceivePacketEvent.java b/versions/src/main/java/cc/polyfrost/oneconfig/events/event/ReceivePacketEvent.java new file mode 100644 index 0000000..17bc16d --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/events/event/ReceivePacketEvent.java @@ -0,0 +1,11 @@ +package cc.polyfrost.oneconfig.events.event; + +import net.minecraft.network.Packet; + +public class ReceivePacketEvent extends CancellableEvent { + public final Packet packet; + + public ReceivePacketEvent(Packet packet) { + this.packet = packet; + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/events/event/ScreenOpenEvent.java b/versions/src/main/java/cc/polyfrost/oneconfig/events/event/ScreenOpenEvent.java new file mode 100644 index 0000000..4593638 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/events/event/ScreenOpenEvent.java @@ -0,0 +1,17 @@ +package cc.polyfrost.oneconfig.events.event; + +import net.minecraft.client.gui.GuiScreen; +import org.jetbrains.annotations.Nullable; + +/** + * Called when a screen is opened or closed. + * If the screen is closed, {@link ScreenOpenEvent#screen} will be null. + */ +public class ScreenOpenEvent extends CancellableEvent { + @Nullable + public final GuiScreen screen; + + public ScreenOpenEvent(@Nullable GuiScreen screen) { + this.screen = screen; + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/events/event/SendPacketEvent.java b/versions/src/main/java/cc/polyfrost/oneconfig/events/event/SendPacketEvent.java new file mode 100644 index 0000000..3cee784 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/events/event/SendPacketEvent.java @@ -0,0 +1,11 @@ +package cc.polyfrost.oneconfig.events.event; + +import net.minecraft.network.Packet; + +public class SendPacketEvent extends CancellableEvent { + public final Packet packet; + + public SendPacketEvent(Packet packet) { + this.packet = packet; + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/events/event/TimerUpdateEvent.java b/versions/src/main/java/cc/polyfrost/oneconfig/events/event/TimerUpdateEvent.java new file mode 100644 index 0000000..a8b88dc --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/events/event/TimerUpdateEvent.java @@ -0,0 +1,24 @@ +package cc.polyfrost.oneconfig.events.event; + +import net.minecraft.util.Timer; + +/** + * Called when the {@link Timer} is updated. + * Can be used as an alternative to getting instances of {@link Timer} + * via Mixin or Access Wideners / Transformers + */ +public class TimerUpdateEvent { + /** + * Whether the deltaTicks / renderPartialTicks was updated + */ + public final boolean updatedDeltaTicks; + /** + * The {@link Timer} instance + */ + public final Timer timer; + + public TimerUpdateEvent(Timer timer, boolean updatedDeltaTicks) { + this.timer = timer; + this.updatedDeltaTicks = updatedDeltaTicks; + } +} \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/OneConfig.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/OneConfig.java new file mode 100644 index 0000000..7ecfe98 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/OneConfig.java @@ -0,0 +1,93 @@ +package cc.polyfrost.oneconfig.internal; + +import cc.polyfrost.oneconfig.events.EventManager; +import cc.polyfrost.oneconfig.events.event.ShutdownEvent; +import cc.polyfrost.oneconfig.internal.command.OneConfigCommand; +import cc.polyfrost.oneconfig.internal.config.OneConfigConfig; +import cc.polyfrost.oneconfig.internal.config.Preferences; +import cc.polyfrost.oneconfig.internal.config.core.ConfigCore; +import cc.polyfrost.oneconfig.internal.config.core.KeyBindHandler; +import cc.polyfrost.oneconfig.internal.gui.BlurHandler; +import cc.polyfrost.oneconfig.internal.hud.HudCore; +import cc.polyfrost.oneconfig.libs.eventbus.Subscribe; +import cc.polyfrost.oneconfig.utils.commands.CommandManager; +import cc.polyfrost.oneconfig.utils.gui.GuiUtils; +import cc.polyfrost.oneconfig.utils.hypixel.HypixelUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.util.ServiceLoader; + +/** + * The main class of OneConfig. + */ +@net.minecraftforge.fml.common.Mod(modid = "@ID@", name = "@NAME@", version = "@VER@") +public class OneConfig { + + public OneConfig() { + EventManager.INSTANCE.register(this); + } + + public static final File oneConfigDir = new File("./OneConfig"); + public static final Logger LOGGER = LogManager.getLogger("@NAME@"); + private static boolean preLaunched = false; + private static boolean initialized = false; + private static boolean isObfuscated = true; + + /** + * Called before mods are loaded. + *

SHOULD NOT BE CALLED!

+ */ + public static void preLaunch() { + if (preLaunched) return; + try { + Class.forName("net.minecraft.world.World"); + LOGGER.warn("OneConfig is NOT obfuscated!"); + isObfuscated = false; + } catch (Exception ignored) { + } + oneConfigDir.mkdirs(); + new File(oneConfigDir, "profiles").mkdirs(); + if (OneConfigConfig.getInstance() == null) { + OneConfigConfig.getInstance(); + } + if (Preferences.getInstance() == null) { + Preferences.getInstance(); + } + preLaunched = true; + } + + /** + * Called after mods are loaded. + *

SHOULD NOT BE CALLED!

+ */ + @SuppressWarnings("ResultOfMethodCallIgnored") + public static void init() { + if (initialized) return; + GuiUtils.getDeltaTime(); // called to make sure static initializer is called + try { + EventManager.INSTANCE.register(BlurHandler.INSTANCE); + } catch (Exception e) { + e.printStackTrace(); + } + CommandManager.INSTANCE.registerCommand(OneConfigCommand.class); + EventManager.INSTANCE.register(new HudCore()); + HypixelUtils.INSTANCE.initialize(); + EventManager.INSTANCE.register(KeyBindHandler.INSTANCE); + ConfigCore.sortMods(); + + initialized = true; + } + + /** Returns weather this is an obfuscated environment, using a check for obfuscated name of net.minecraft.world.World.class. + * @return true if this is an obfuscated environment, which is normal for Minecraft or false if not. */ + public static boolean isObfuscated() { + return isObfuscated; + } + + @Subscribe + private void onShutdown(ShutdownEvent event) { + ConfigCore.saveAll(); + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/gui/impl/BlurHandlerImpl.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/gui/impl/BlurHandlerImpl.java new file mode 100644 index 0000000..0ef5f2b --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/gui/impl/BlurHandlerImpl.java @@ -0,0 +1,132 @@ +package cc.polyfrost.oneconfig.internal.gui.impl; + +import cc.polyfrost.oneconfig.events.event.RenderEvent; +import cc.polyfrost.oneconfig.events.event.ScreenOpenEvent; +import cc.polyfrost.oneconfig.events.event.Stage; +import cc.polyfrost.oneconfig.gui.OneConfigGui; +import cc.polyfrost.oneconfig.internal.config.Preferences; +import cc.polyfrost.oneconfig.internal.gui.BlurHandler; +import cc.polyfrost.oneconfig.internal.mixin.ShaderGroupAccessor; +import cc.polyfrost.oneconfig.libs.eventbus.Subscribe; +import cc.polyfrost.oneconfig.libs.universal.UMinecraft; +import cc.polyfrost.oneconfig.libs.universal.UScreen; +import net.minecraft.client.Minecraft; +import net.minecraft.client.shader.Shader; +import net.minecraft.client.shader.ShaderUniform; +import net.minecraft.util.ResourceLocation; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.List; + +/** + * An implementation of the BlurMC mod by tterrag1098. + *

+ * For the original source see ... + * For the public license, see ... + *

+ * License available under ... + * + * @author tterrag1098, boomboompower + *

+ * Taken from ToggleChat + * ... + */ +public class BlurHandlerImpl implements BlurHandler { + private final ResourceLocation blurShader = new ResourceLocation("shaders/post/fade_in_blur.json"); + private final Logger logger = LogManager.getLogger("OneConfig - Blur"); + private long start; + private float progress = 0; + + @Subscribe + private void onGuiChange(ScreenOpenEvent event) { + reloadBlur(event.screen); + } + + @Subscribe + private void onRenderTick(RenderEvent event) { + if (event.stage != Stage.END) { + return; + } + + // Only blur on our own menus + if (UScreen.getCurrentScreen() == null) { + return; + } + + // Only update the shader if one is active + if (!UMinecraft.getMinecraft().entityRenderer.isShaderActive()) { + return; + } + if (progress >= 5) return; + progress = getBlurStrengthProgress(); + + // This is hilariously bad, and could cause frame issues on low-end computers. + // Why is this being computed every tick? Surely there is a better way? + // This needs to be optimized. + try { + final List listShaders = ((ShaderGroupAccessor) Minecraft.getMinecraft().entityRenderer.getShaderGroup()).getListShaders(); + + // Should not happen. Something bad happened. + if (listShaders == null) { + return; + } + + // Iterate through the list of shaders. + for (Shader shader : listShaders) { + ShaderUniform su = shader.getShaderManager().getShaderUniform("Progress"); + + if (su == null) { + continue; + } + + // All this for this. + su.set(progress); + } + } catch (IllegalArgumentException ex) { + this.logger.error("An error.png occurred while updating OneConfig's blur. Please report this!", ex); + } + } + + /** + * Activates/deactivates the blur in the current world if + * one of many conditions are met, such as no current other shader + * is being used, we actually have the blur setting enabled + */ + public void reloadBlur(Object gui) { + // Don't do anything if no world is loaded + if (UMinecraft.getWorld() == null) { + return; + } + + // If a shader is not already active and the UI is + // a one of ours, we should load our own blur! + + if (!UMinecraft.getMinecraft().entityRenderer.isShaderActive() && gui instanceof OneConfigGui && Preferences.enableBlur) { + UMinecraft.getMinecraft().entityRenderer.loadShader(this.blurShader); + + this.start = System.currentTimeMillis(); + this.progress = 0; + + // If a shader is active and the incoming UI is null or we have blur disabled, stop using the shader. + } else if (UMinecraft.getMinecraft().entityRenderer.isShaderActive() && (gui == null || !Preferences.enableBlur)) { + String name = UMinecraft.getMinecraft().entityRenderer.getShaderGroup().getShaderGroupName(); + + // Only stop our specific blur ;) + if (!name.endsWith("fade_in_blur.json")) { + return; + } + + UMinecraft.getMinecraft().entityRenderer.stopUseShader(); + } + } + + /** + * Returns the strength of the blur as determined by the duration the effect of the blur. + *

+ * The strength of the blur does not go below 5.0F. + */ + private float getBlurStrengthProgress() { + return Math.min((System.currentTimeMillis() - this.start) / 50F, 5.0F); + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/GuiIngameForgeMixin.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/GuiIngameForgeMixin.java new file mode 100644 index 0000000..2a89972 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/GuiIngameForgeMixin.java @@ -0,0 +1,19 @@ +//#if MC==10809 +package cc.polyfrost.oneconfig.internal.mixin; + +import cc.polyfrost.oneconfig.events.EventManager; +import cc.polyfrost.oneconfig.events.event.HudRenderEvent; +import net.minecraftforge.client.GuiIngameForge; +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; + +@Mixin(value = GuiIngameForge.class, remap = false) +public class GuiIngameForgeMixin { + @Inject(method = "renderGameOverlay", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/client/GuiIngameForge;post(Lnet/minecraftforge/client/event/RenderGameOverlayEvent$ElementType;)V", shift = At.Shift.AFTER, remap = false), remap = true) + private void onRenderGameOverlay(float partialTicks, CallbackInfo ci) { + EventManager.INSTANCE.post(new HudRenderEvent(partialTicks)); + } +} +//#endif \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/MinecraftMixin.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/MinecraftMixin.java new file mode 100644 index 0000000..0603d12 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/MinecraftMixin.java @@ -0,0 +1,100 @@ +//#if MC==10809 +package cc.polyfrost.oneconfig.internal.mixin; + +import cc.polyfrost.oneconfig.internal.OneConfig; +import cc.polyfrost.oneconfig.events.EventManager; +import cc.polyfrost.oneconfig.events.event.*; +import net.minecraft.client.Minecraft; +import net.minecraft.util.Timer; +import net.minecraftforge.client.event.GuiOpenEvent; +import net.minecraftforge.fml.common.eventhandler.Event; +import org.objectweb.asm.Opcodes; +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; + +@Mixin(Minecraft.class) +public class MinecraftMixin { + @Shadow + private Timer timer; + + @Inject(method = "shutdownMinecraftApplet", at = @At("HEAD")) + private void onShutdown(CallbackInfo ci) { + EventManager.INSTANCE.post(new PreShutdownEvent()); + } + + @Inject(method = "startGame", at = @At("HEAD")) + private void onStart(CallbackInfo ci) { + EventManager.INSTANCE.post(new StartEvent()); + Runtime.getRuntime().addShutdownHook(new Thread(() -> EventManager.INSTANCE.post(new ShutdownEvent()))); + } + + @Inject(method = "startGame", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/client/FMLClientHandler;beginMinecraftLoading(Lnet/minecraft/client/Minecraft;Ljava/util/List;Lnet/minecraft/client/resources/IReloadableResourceManager;)V", remap = false), remap = true) + private void onPreLaunch(CallbackInfo ci) { + OneConfig.preLaunch(); + } + + @Inject(method = "startGame", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/client/FMLClientHandler;onInitializationComplete()V", shift = At.Shift.AFTER, remap = false), remap = true) + private void onInit(CallbackInfo ci) { + EventManager.INSTANCE.post(new InitializationEvent()); + OneConfig.init(); + } + + @Inject(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;onRenderTickStart(F)V", shift = At.Shift.AFTER, remap = false), remap = true) + private void onRenderTickStart(CallbackInfo ci) { + EventManager.INSTANCE.post(new RenderEvent(Stage.START, timer.renderPartialTicks)); + } + + @Inject(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;onRenderTickEnd(F)V", shift = At.Shift.AFTER, remap = false), remap = true) + private void onRenderTickEnd(CallbackInfo ci) { + EventManager.INSTANCE.post(new RenderEvent(Stage.END, timer.renderPartialTicks)); + } + + @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;onPreClientTick()V", shift = At.Shift.AFTER, remap = false), remap = true) + private void onClientTickStart(CallbackInfo ci) { + EventManager.INSTANCE.post(new TickEvent(Stage.START)); + } + + @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;onPostClientTick()V", shift = At.Shift.AFTER, remap = false), remap = true) + private void onClientTickEnd(CallbackInfo ci) { + EventManager.INSTANCE.post(new TickEvent(Stage.END)); + } + + @ModifyArg(method = "displayGuiScreen", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/eventhandler/EventBus;post(Lnet/minecraftforge/fml/common/eventhandler/Event;)Z", remap = false), remap = true) + private Event onGuiOpenEvent(Event a) { + if (a instanceof GuiOpenEvent) { + GuiOpenEvent forgeEvent = (GuiOpenEvent) a; + ScreenOpenEvent event = new ScreenOpenEvent(forgeEvent.gui); + EventManager.INSTANCE.post(event); + if (event.isCancelled) { + forgeEvent.setCanceled(true); + } + return forgeEvent; + } + return a; + } + + @Inject(method = "runGameLoop", at = @At(value = "FIELD", target = "Lnet/minecraft/util/Timer;renderPartialTicks:F", opcode = Opcodes.PUTFIELD, shift = At.Shift.AFTER)) + private void onNonDeltaTickTimerUpdate(CallbackInfo ci) { + EventManager.INSTANCE.post(new TimerUpdateEvent(timer, false)); + } + + @Inject(method = "runGameLoop", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/Timer;updateTimer()V", shift = At.Shift.AFTER, ordinal = 1)) + private void onDeltaTickTimerUpdate(CallbackInfo ci) { + EventManager.INSTANCE.post(new TimerUpdateEvent(timer, true)); + } + + @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;fireKeyInput()V")) + private void onKeyEvent(CallbackInfo ci) { + EventManager.INSTANCE.post(new KeyInputEvent()); + } + + @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;fireMouseInput()V")) + private void onMouseEvent(CallbackInfo ci) { + EventManager.INSTANCE.post(new MouseInputEvent()); + } +} +//#endif \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetHandlerPlayClientMixin.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetHandlerPlayClientMixin.java new file mode 100644 index 0000000..7a446c7 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetHandlerPlayClientMixin.java @@ -0,0 +1,38 @@ +//#if MC==10809 +package cc.polyfrost.oneconfig.internal.mixin; + +import cc.polyfrost.oneconfig.events.EventManager; +import cc.polyfrost.oneconfig.events.event.ChatReceiveEvent; +import cc.polyfrost.oneconfig.events.event.SendPacketEvent; +import net.minecraft.client.network.NetHandlerPlayClient; +import net.minecraft.network.Packet; +import net.minecraft.network.play.server.S02PacketChat; +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; + +@Mixin(value = NetHandlerPlayClient.class, priority = Integer.MAX_VALUE) +public class NetHandlerPlayClientMixin { + + @Inject(method = "addToSendQueue", at = @At("HEAD"), cancellable = true) + private void onSendPacket(Packet p_147297_1_, CallbackInfo ci) { + SendPacketEvent event = new SendPacketEvent(p_147297_1_); + EventManager.INSTANCE.post(event); + if (event.isCancelled) { + ci.cancel(); + } + } + + @Inject(method = "handleChat", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/event/ForgeEventFactory;onClientChat(BLnet/minecraft/util/IChatComponent;)Lnet/minecraft/util/IChatComponent;", remap = false), cancellable = true, remap = true) + private void onClientChat(S02PacketChat packetIn, CallbackInfo ci) { + if (packetIn.getType() == 0) { + ChatReceiveEvent event = new ChatReceiveEvent(packetIn.getChatComponent()); + EventManager.INSTANCE.post(event); + if (event.isCancelled) { + ci.cancel(); + } + } + } +} +//#endif \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetworkManagerMixin.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetworkManagerMixin.java new file mode 100644 index 0000000..3da0c91 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/NetworkManagerMixin.java @@ -0,0 +1,25 @@ +//#if MC==10809 +package cc.polyfrost.oneconfig.internal.mixin; + +import cc.polyfrost.oneconfig.events.EventManager; +import cc.polyfrost.oneconfig.events.event.ReceivePacketEvent; +import io.netty.channel.ChannelHandlerContext; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.Packet; +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; + +@Mixin(value = NetworkManager.class, priority = Integer.MAX_VALUE) +public class NetworkManagerMixin { + @Inject(method = "channelRead0(Lio/netty/channel/ChannelHandlerContext;Lnet/minecraft/network/Packet;)V", at = @At("HEAD"), cancellable = true) + private void onReceivePacket(ChannelHandlerContext p_channelRead0_1_, Packet p_channelRead0_2_, CallbackInfo ci) { + ReceivePacketEvent event = new ReceivePacketEvent(p_channelRead0_2_); + EventManager.INSTANCE.post(event); + if (event.isCancelled) { + ci.cancel(); + } + } +} +//#endif \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/OptifineConfigMixin.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/OptifineConfigMixin.java new file mode 100644 index 0000000..9012091 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/OptifineConfigMixin.java @@ -0,0 +1,23 @@ +//#if MC==10809 +package cc.polyfrost.oneconfig.internal.mixin; + +import cc.polyfrost.oneconfig.internal.plugin.hooks.OptifineConfigHook; +import org.spongepowered.asm.mixin.Dynamic; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Pseudo +@Mixin(targets = "Config", remap = false) +public class OptifineConfigMixin { + @Dynamic("OptiFine") + @Inject(method = "isFastRender", at = @At("HEAD"), cancellable = true) + private static void cancelFastRender(CallbackInfoReturnable cir) { + if (OptifineConfigHook.shouldNotApplyFastRender()) { + cir.setReturnValue(false); + } + } +} +//#endif \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/ShaderGroupAccessor.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/ShaderGroupAccessor.java new file mode 100644 index 0000000..588da19 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/ShaderGroupAccessor.java @@ -0,0 +1,16 @@ +//#if MC==10809 +package cc.polyfrost.oneconfig.internal.mixin; + +import net.minecraft.client.shader.Shader; +import net.minecraft.client.shader.ShaderGroup; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +import java.util.List; + +@Mixin(ShaderGroup.class) +public interface ShaderGroupAccessor { + @Accessor("listShaders") + List getListShaders(); +} +//#endif \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/VigilantMixin.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/VigilantMixin.java new file mode 100644 index 0000000..6b474ab --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/VigilantMixin.java @@ -0,0 +1,10 @@ +//#if MC==10809 +package cc.polyfrost.oneconfig.internal.mixin; + +import gg.essential.vigilance.Vigilant; +import org.spongepowered.asm.mixin.Mixin; + +@Mixin(Vigilant.class) +public class VigilantMixin { +} +//#endif \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/WorldClientMixin.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/WorldClientMixin.java new file mode 100644 index 0000000..05c6920 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/mixin/WorldClientMixin.java @@ -0,0 +1,23 @@ +//#if MC==10809 +package cc.polyfrost.oneconfig.internal.mixin; + +import cc.polyfrost.oneconfig.events.EventManager; +import cc.polyfrost.oneconfig.events.event.WorldLoadEvent; +import net.minecraft.client.multiplayer.WorldClient; +import net.minecraft.client.network.NetHandlerPlayClient; +import net.minecraft.profiler.Profiler; +import net.minecraft.world.EnumDifficulty; +import net.minecraft.world.WorldSettings; +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; + +@Mixin(WorldClient.class) +public class WorldClientMixin { + @Inject(method = "", at = @At("RETURN")) + private void onWorldLoad(NetHandlerPlayClient p_i45063_1_, WorldSettings p_i45063_2_, int p_i45063_3_, EnumDifficulty p_i45063_4_, Profiler p_i45063_5_, CallbackInfo ci) { + EventManager.INSTANCE.post(new WorldLoadEvent()); + } +} +//#endif \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ClassTransformer.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ClassTransformer.java new file mode 100644 index 0000000..52256ca --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ClassTransformer.java @@ -0,0 +1,102 @@ +package cc.polyfrost.oneconfig.internal.plugin.asm; + +import cc.polyfrost.oneconfig.internal.plugin.asm.tweakers.NanoVGGLConfigTransformer; +import cc.polyfrost.oneconfig.internal.plugin.asm.tweakers.VigilantTransformer; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimap; +import net.minecraft.launchwrapper.IClassTransformer; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.tree.ClassNode; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Collection; + +/** + * Taken from LWJGLTwoPointFive under The Unlicense + * https://github.com/DJtheRedstoner/LWJGLTwoPointFive/blob/master/LICENSE/ + *

also half taken from asmworkspace by asbyth ty

+ */ +@SuppressWarnings("unused") +public class ClassTransformer implements IClassTransformer { + private static final Logger logger = LogManager.getLogger("OneConfig ASM"); + private final Multimap transformerMap = ArrayListMultimap.create(); + private static final boolean outputBytecode = Boolean.parseBoolean(System.getProperty("debugBytecode", "false")); + + public ClassTransformer() { + registerTransformer(new NanoVGGLConfigTransformer()); + registerTransformer(new VigilantTransformer()); + } + + private void registerTransformer(ITransformer transformer) { + // loop through names of classes + for (String cls : transformer.getClassName()) { + // put the classes into the transformer map + transformerMap.put(cls, transformer); + } + } + + @Override + public byte[] transform(String name, String transformedName, byte[] bytes) { + if (bytes == null) return null; + + Collection transformers = transformerMap.get(transformedName); + if (transformers.isEmpty()) return bytes; + + ClassReader reader = new ClassReader(bytes); + ClassNode node = new ClassNode(); + reader.accept(node, ClassReader.EXPAND_FRAMES); + + for (ITransformer transformer : transformers) { + transformer.transform(transformedName, node); + } + + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + try { + node.accept(cw); + } catch (Throwable t) { + logger.error("Exception when transforming " + transformedName + " : " + t.getClass().getSimpleName()); + t.printStackTrace(); + } + + if (outputBytecode) { + File bytecodeDirectory = new File("bytecode"); + String transformedClassName; + + // anonymous classes + if (transformedName.contains("$")) { + transformedClassName = transformedName.replace('$', '.') + ".class"; + } else { + transformedClassName = transformedName + ".class"; + } + + if (!bytecodeDirectory.exists()) { + bytecodeDirectory.mkdirs(); + } + + File bytecodeOutput = new File(bytecodeDirectory, transformedClassName); + + try { + if (!bytecodeOutput.exists()) { + bytecodeOutput.createNewFile(); + } + } catch (Exception e) { + e.printStackTrace(); + } + + try (FileOutputStream os = new FileOutputStream(bytecodeOutput)) { + // write to the generated class to /run/bytecode/classfile.class + // with the class bytes from transforming + os.write(cw.toByteArray()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + return cw.toByteArray(); + } +} \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ITransformer.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ITransformer.java new file mode 100644 index 0000000..1bc50d1 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/ITransformer.java @@ -0,0 +1,24 @@ +package cc.polyfrost.oneconfig.internal.plugin.asm; + +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; + +public interface ITransformer { + String[] getClassName(); + + void transform(String transformedName, ClassNode node); + + default void clearInstructions(MethodNode methodNode) { + methodNode.instructions.clear(); + + // dont waste time clearing local variables if they're empty + if (!methodNode.localVariables.isEmpty()) { + methodNode.localVariables.clear(); + } + + // dont waste time clearing try-catches if they're empty + if (!methodNode.tryCatchBlocks.isEmpty()) { + methodNode.tryCatchBlocks.clear(); + } + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/OneConfigTweaker.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/OneConfigTweaker.java new file mode 100644 index 0000000..d302b9d --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/OneConfigTweaker.java @@ -0,0 +1,117 @@ +package cc.polyfrost.oneconfig.internal.plugin.asm; + +import cc.polyfrost.oneconfig.internal.init.OneConfigInit; +import net.minecraft.launchwrapper.ITweaker; +import net.minecraft.launchwrapper.Launch; +import net.minecraft.launchwrapper.LaunchClassLoader; +import net.minecraftforge.fml.relauncher.CoreModManager; +import org.spongepowered.asm.launch.MixinBootstrap; +import org.spongepowered.asm.launch.MixinTweaker; +import org.spongepowered.asm.mixin.Mixins; + +import java.io.File; +import java.lang.reflect.Field; +import java.net.URI; +import java.net.URL; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.jar.Attributes; +import java.util.jar.JarFile; + +public class OneConfigTweaker implements ITweaker { + + public OneConfigTweaker() { + for (URL url : Launch.classLoader.getSources()) { + doMagicMixinStuff(url); + } + } + + private void doMagicMixinStuff(URL url) { + try { + URI uri = url.toURI(); + if (Objects.equals(uri.getScheme(), "file")) { + File file = new File(uri); + if (file.exists() && file.isFile()) { + try (JarFile jarFile = new JarFile(file)) { + if (jarFile.getManifest() != null) { + Attributes attributes = jarFile.getManifest().getMainAttributes(); + String tweakerClass = attributes.getValue("TweakClass"); + if (Objects.equals(tweakerClass, "cc.polyfrost.oneconfigwrapper.OneConfigWrapper")) { + CoreModManager.getIgnoredMods().remove(file.getName()); + CoreModManager.getReparseableCoremods().add(file.getName()); + String mixinConfig = attributes.getValue("MixinConfigs"); + if (mixinConfig != null) { + try { + try { + List tweakClasses = (List) Launch.blackboard.get("TweakClasses"); // tweak classes before other mod trolling + if (tweakClasses.contains("org.spongepowered.asm.launch.MixinTweaker")) { // if there's already a mixin tweaker, we'll just load it like "usual" + new MixinTweaker(); // also we might not need to make a new mixin tweawker all the time but im just making sure + } else if (!Launch.blackboard.containsKey("mixin.initialised")) { // if there isnt, we do our own trolling + List tweaks = (List) Launch.blackboard.get("Tweaks"); + tweaks.add(new MixinTweaker()); + } + } catch (Exception ignored) { + // if it fails i *think* we can just ignore it + } + MixinBootstrap.getPlatform().addContainer(uri); + } catch (Exception ignored) { + + } + } + } + } + } + } + } + } catch (Exception ignored) { + + } + } + + @Override + public void acceptOptions(List args, File gameDir, File assetsDir, String profile) { + MixinBootstrap.init(); + boolean captureNext = false; + for (String arg : args) { + if (captureNext) { + Mixins.addConfiguration(arg); + } + captureNext = "--mixin".equals(arg); + } + } + + @Override + public void injectIntoClassLoader(LaunchClassLoader classLoader) { + removeLWJGLException(); + Launch.classLoader.registerTransformer(ClassTransformer.class.getName()); + OneConfigInit.initialize(new String[]{}); + Launch.blackboard.put("oneconfig.init.initialized", true); + Launch.classLoader.addClassLoaderExclusion("cc.polyfrost.oneconfig.internal.plugin.asm."); + } + + /** + * Taken from LWJGLTwoPointFive under The Unlicense + * https://github.com/DJtheRedstoner/LWJGLTwoPointFive/blob/master/LICENSE/ + */ + private void removeLWJGLException() { + try { + Field f_exceptions = LaunchClassLoader.class.getDeclaredField("classLoaderExceptions"); + f_exceptions.setAccessible(true); + Set exceptions = (Set) f_exceptions.get(Launch.classLoader); + exceptions.remove("org.lwjgl."); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public String getLaunchTarget() { + return null; + } + + @Override + public String[] getLaunchArguments() { + return new String[0]; + } +} \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/NanoVGGLConfigTransformer.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/NanoVGGLConfigTransformer.java new file mode 100644 index 0000000..bbbf4a1 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/NanoVGGLConfigTransformer.java @@ -0,0 +1,47 @@ +package cc.polyfrost.oneconfig.internal.plugin.asm.tweakers; + +import cc.polyfrost.oneconfig.internal.plugin.asm.ITransformer; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.*; + +/** + * Taken from LWJGLTwoPointFive under The Unlicense + * https://github.com/DJtheRedstoner/LWJGLTwoPointFive/blob/master/LICENSE/ + */ +public class NanoVGGLConfigTransformer implements ITransformer { + @Override + public String[] getClassName() { + return new String[]{"org.lwjgl.nanovg.NanoVGGLConfig"}; + } + + @Override + public void transform(String transformedName, ClassNode node) { + for (MethodNode method : node.methods) { + if (method.name.equals("configGL")) { + InsnList list = new InsnList(); + + list.add(new VarInsnNode(Opcodes.LLOAD, 0)); + list.add(new TypeInsnNode(Opcodes.NEW, "cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider")); + list.add(new InsnNode(Opcodes.DUP)); + list.add(new MethodInsnNode( + Opcodes.INVOKESPECIAL, + "cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider", + "", + "()V", + false + )); + list.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + "org/lwjgl/nanovg/NanoVGGLConfig", + "config", + "(JLorg/lwjgl/system/FunctionProvider;)V", + false + )); + list.add(new InsnNode(Opcodes.RETURN)); + + clearInstructions(method); + method.instructions.insert(list); + } + } + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/VigilantTransformer.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/VigilantTransformer.java new file mode 100644 index 0000000..8dd60cf --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/asm/tweakers/VigilantTransformer.java @@ -0,0 +1,89 @@ +package cc.polyfrost.oneconfig.internal.plugin.asm.tweakers; + +import cc.polyfrost.oneconfig.internal.plugin.asm.ITransformer; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.*; + +import java.io.File; + +public class VigilantTransformer implements ITransformer { + + @Override + public String[] getClassName() { + return new String[]{"gg.essential.vigilance.Vigilant"}; + } + + /** + * If anything here is changed, edit the corresponding method in OneConfigMixinPlugin! + */ + @Override + public void transform(String transformedName, ClassNode node) { + if (!node.interfaces.contains("cc/polyfrost/oneconfig/config/compatibility/vigilance/VigilantAccessor")) { + node.fields.add(new FieldNode(Opcodes.ACC_PUBLIC, "oneconfig$config", "Lcc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig;", null, null)); + node.fields.add(new FieldNode(Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, "oneconfig$file", Type.getDescriptor(File.class), null, null)); + + node.interfaces.add("cc/polyfrost/oneconfig/config/compatibility/vigilance/VigilantAccessor"); + MethodNode methodNode = new MethodNode(Opcodes.ACC_PUBLIC, "getPropertyCollector", "()Lgg/essential/vigilance/data/PropertyCollector;", null, null); + LabelNode labelNode = new LabelNode(); + methodNode.instructions.add(labelNode); + methodNode.instructions.add(new LineNumberNode(421421, labelNode)); + methodNode.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); + methodNode.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "gg/essential/vigilance/Vigilant", "propertyCollector", "Lgg/essential/vigilance/data/PropertyCollector;")); + methodNode.instructions.add(new InsnNode(Opcodes.ARETURN)); + node.methods.add(methodNode); + + MethodNode methodNode2 = new MethodNode(Opcodes.ACC_PUBLIC, "handleOneConfigDependency", "(Lgg/essential/vigilance/data/PropertyData;Lgg/essential/vigilance/data/PropertyData;)V", null, null); + LabelNode labelNode2 = new LabelNode(); + LabelNode labelNode3 = new LabelNode(); + LabelNode labelNode4 = new LabelNode(); + methodNode2.instructions.add(labelNode2); + methodNode2.instructions.add(new LineNumberNode(15636436, labelNode2)); + methodNode2.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); + methodNode2.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "gg/essential/vigilance/Vigilant", "oneconfig$config", "Lcc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig;")); + + methodNode2.instructions.add(new JumpInsnNode(Opcodes.IFNULL, labelNode4)); + + methodNode2.instructions.add(labelNode3); + methodNode2.instructions.add(new LineNumberNode(15636437, labelNode3)); + methodNode2.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); + methodNode2.instructions.add(new FieldInsnNode(Opcodes.GETFIELD, "gg/essential/vigilance/Vigilant", "oneconfig$config", "Lcc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig;")); + methodNode2.instructions.add(new VarInsnNode(Opcodes.ALOAD, 1)); + methodNode2.instructions.add(new VarInsnNode(Opcodes.ALOAD, 2)); + methodNode2.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "cc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig", "addDependency", "(Lgg/essential/vigilance/data/PropertyData;Lgg/essential/vigilance/data/PropertyData;)V", false)); + + methodNode2.instructions.add(labelNode4); + methodNode2.instructions.add(new LineNumberNode(15636438, labelNode4)); + methodNode2.instructions.add(new InsnNode(Opcodes.RETURN)); + node.methods.add(methodNode2); + + for (MethodNode method : node.methods) { + if (method.name.equals("initialize")) { + InsnList list = new InsnList(); + list.add(new VarInsnNode(Opcodes.ALOAD, 0)); + list.add(new VarInsnNode(Opcodes.ALOAD, 0)); + list.add(new VarInsnNode(Opcodes.ALOAD, 0)); + list.add(new FieldInsnNode(Opcodes.GETFIELD, "gg/essential/vigilance/Vigilant", "oneconfig$file", Type.getDescriptor(File.class))); + list.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "cc/polyfrost/oneconfig/internal/plugin/hooks/VigilantHook", "returnNewConfig", "(Lgg/essential/vigilance/Vigilant;Ljava/io/File;)Lcc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig;", false)); + list.add(new FieldInsnNode(Opcodes.PUTFIELD, "gg/essential/vigilance/Vigilant", "oneconfig$config", "Lcc/polyfrost/oneconfig/config/compatibility/vigilance/VigilanceConfig;")); + method.instructions.insertBefore(method.instructions.getLast().getPrevious(), list); + } else if (method.name.equals("addDependency") && method.desc.equals("(Lgg/essential/vigilance/data/PropertyData;Lgg/essential/vigilance/data/PropertyData;)V")) { + InsnList list = new InsnList(); + + list.add(new VarInsnNode(Opcodes.ALOAD, 0)); + list.add(new VarInsnNode(Opcodes.ALOAD, 1)); + list.add(new VarInsnNode(Opcodes.ALOAD, 2)); + list.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "gg/essential/vigilance/Vigilant", "handleOneConfigDependency", "(Lgg/essential/vigilance/data/PropertyData;Lgg/essential/vigilance/data/PropertyData;)V", false)); + + method.instructions.insertBefore(method.instructions.getLast().getPrevious(), list); + } else if (method.name.equals("") && method.desc.equals("(Ljava/io/File;Ljava/lang/String;Lgg/essential/vigilance/data/PropertyCollector;Lgg/essential/vigilance/data/SortingBehavior;)V")) { + InsnList list = new InsnList(); + list.add(new VarInsnNode(Opcodes.ALOAD, 0)); + list.add(new VarInsnNode(Opcodes.ALOAD, 1)); + list.add(new FieldInsnNode(Opcodes.PUTFIELD, "gg/essential/vigilance/Vigilant", "oneconfig$file", Type.getDescriptor(File.class))); + method.instructions.insertBefore(method.instructions.getLast().getPrevious(), list); + } + } + } + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider.java new file mode 100644 index 0000000..297c84d --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/Lwjgl2FunctionProvider.java @@ -0,0 +1,47 @@ +package cc.polyfrost.oneconfig.internal.plugin.hooks; + +import org.lwjgl.system.FunctionProvider; + +import java.lang.reflect.Method; +import java.nio.ByteBuffer; + +/** + * Taken from LWJGLTwoPointFive under The Unlicense + * https://github.com/DJtheRedstoner/LWJGLTwoPointFive/blob/master/LICENSE/ + */ +public class Lwjgl2FunctionProvider implements FunctionProvider { + + private static final Class GLContext; + private final Method m_getFunctionAddress; + + static { + try { + GLContext = Class.forName("org.lwjgl.opengl.GLContext"); + } catch (Throwable t) { + throw new RuntimeException("Unable to initialize LWJGL2FunctionProvider", t); + } + } + + public Lwjgl2FunctionProvider() { + try { + m_getFunctionAddress = GLContext.getDeclaredMethod("getFunctionAddress", String.class); + m_getFunctionAddress.setAccessible(true); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public long getFunctionAddress(CharSequence functionName) { + try { + return (long) m_getFunctionAddress.invoke(null, functionName.toString()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public long getFunctionAddress(ByteBuffer byteBuffer) { + throw new UnsupportedOperationException(); + } +} \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/OptifineConfigHook.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/OptifineConfigHook.java new file mode 100644 index 0000000..dea68cf --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/OptifineConfigHook.java @@ -0,0 +1,22 @@ +package cc.polyfrost.oneconfig.internal.plugin.hooks; + +import cc.polyfrost.oneconfig.gui.OneConfigGui; +import cc.polyfrost.oneconfig.platform.Platform; +import cc.polyfrost.oneconfig.utils.gui.GuiUtils; + +import java.util.Optional; + +public class OptifineConfigHook { + + public static boolean shouldNotApplyFastRender() { + if (Platform.getGuiPlatform().getCurrentScreen() instanceof OneConfigGui) { + return true; + } + for (Optional screen : GuiUtils.getScreenQueue()) { + if (screen.isPresent() && screen.get() instanceof OneConfigGui) { + return true; + } + } + return false; + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/VigilantHook.java b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/VigilantHook.java new file mode 100644 index 0000000..a012773 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/internal/plugin/hooks/VigilantHook.java @@ -0,0 +1,26 @@ +package cc.polyfrost.oneconfig.internal.plugin.hooks; + +import cc.polyfrost.oneconfig.config.compatibility.vigilance.VigilanceConfig; +import cc.polyfrost.oneconfig.config.data.Mod; +import cc.polyfrost.oneconfig.config.data.ModType; +import cc.polyfrost.oneconfig.internal.config.core.ConfigCore; +import cc.polyfrost.oneconfig.platform.Platform; +import gg.essential.vigilance.Vigilant; + +import java.io.File; + +@SuppressWarnings("unused") +public class VigilantHook { + public static VigilanceConfig returnNewConfig(Vigilant vigilant, File file) { + if (vigilant != null && Platform.getInstance().isCallingFromMinecraftThread()) { + String name = !vigilant.getGuiTitle().equals("Settings") ? vigilant.getGuiTitle() : !Platform.getLoaderPlatform().hasActiveModContainer() ? "Unknown" : Platform.getLoaderPlatform().getActiveModContainer().name; + if (name.equals("OneConfig")) name = "Essential"; + String finalName = name; + // duplicate fix + if (ConfigCore.mods.stream().anyMatch(mod -> mod.name.equals(finalName))) return null; + return new VigilanceConfig(new Mod(name, ModType.THIRD_PARTY), file.getAbsolutePath(), vigilant); + } else { + return null; + } + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/GLPlatformImpl.java b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/GLPlatformImpl.java new file mode 100644 index 0000000..3ee962b --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/GLPlatformImpl.java @@ -0,0 +1,67 @@ +package cc.polyfrost.oneconfig.platform.impl; + +import cc.polyfrost.oneconfig.libs.universal.UMatrixStack; +import cc.polyfrost.oneconfig.libs.universal.UMinecraft; +import cc.polyfrost.oneconfig.platform.GLPlatform; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.WorldRenderer; +import net.minecraft.client.renderer.vertex.DefaultVertexFormats; +import net.minecraft.client.shader.Framebuffer; + +@SuppressWarnings("unused") +public class GLPlatformImpl implements GLPlatform { + + @Override + public void drawRect(float x, float y, float x2, float y2, int color) { + if (x < x2) { + float i = x; + x = x2; + x2 = i; + } + + if (y < y2) { + float i = y; + y = y2; + y2 = i; + } + + float f = (float)(color >> 24 & 0xFF) / 255.0F; + float g = (float)(color >> 16 & 0xFF) / 255.0F; + float h = (float)(color >> 8 & 0xFF) / 255.0F; + float j = (float)(color & 0xFF) / 255.0F; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldRenderer = tessellator.getWorldRenderer(); + GlStateManager.enableBlend(); + GlStateManager.disableTexture2D(); + GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); + GlStateManager.color(g, h, j, f); + worldRenderer.begin(7, DefaultVertexFormats.POSITION); + worldRenderer.pos(x, y2, 0.0).endVertex(); + worldRenderer.pos(x2, y2, 0.0).endVertex(); + worldRenderer.pos(x2, y, 0.0).endVertex(); + worldRenderer.pos(x, y, 0.0).endVertex(); + tessellator.draw(); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + } + + @Override + public void enableStencil() { + Framebuffer framebuffer = Minecraft.getMinecraft().getFramebuffer(); + if (!framebuffer.isStencilEnabled()) { + framebuffer.enableStencil(); + } + } + + @Override + public float drawText(UMatrixStack matrixStack, String text, float x, float y, int color, boolean shadow) { + return UMinecraft.getFontRenderer().drawString(text, x, y, color, shadow); + } + + @Override + public int getStringWidth(String text) { + return UMinecraft.getFontRenderer().getStringWidth(text); + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/GuiPlatformImpl.java b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/GuiPlatformImpl.java new file mode 100644 index 0000000..6ea3c03 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/GuiPlatformImpl.java @@ -0,0 +1,31 @@ +package cc.polyfrost.oneconfig.platform.impl; + +import cc.polyfrost.oneconfig.libs.universal.UMinecraft; +import cc.polyfrost.oneconfig.libs.universal.UScreen; +import cc.polyfrost.oneconfig.platform.GuiPlatform; +import net.minecraft.client.gui.GuiChat; +import net.minecraft.client.gui.GuiScreen; + +@SuppressWarnings("unused") +public class GuiPlatformImpl implements GuiPlatform { + + @Override + public Object getCurrentScreen() { + return UScreen.getCurrentScreen(); + } + + @Override + public void setCurrentScreen(Object screen) { + UScreen.displayScreen((GuiScreen) screen); + } + + @Override + public boolean isInChat() { + return getCurrentScreen() instanceof GuiChat; + } + + @Override + public boolean isInDebug() { + return UMinecraft.getSettings().showDebugInfo; + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/I18nPlatformImpl.java b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/I18nPlatformImpl.java new file mode 100644 index 0000000..1913238 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/I18nPlatformImpl.java @@ -0,0 +1,13 @@ +package cc.polyfrost.oneconfig.platform.impl; + +import cc.polyfrost.oneconfig.platform.I18nPlatform; +import net.minecraft.client.resources.I18n; + +@SuppressWarnings("unused") +public class I18nPlatformImpl implements I18nPlatform { + + @Override + public String format(String key, Object... args) { + return I18n.format(key, args); + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/LoaderPlatformImpl.java b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/LoaderPlatformImpl.java new file mode 100644 index 0000000..01269cd --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/LoaderPlatformImpl.java @@ -0,0 +1,26 @@ +package cc.polyfrost.oneconfig.platform.impl; + +import cc.polyfrost.oneconfig.platform.LoaderPlatform; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.ModContainer; + +@SuppressWarnings("unused") +public class LoaderPlatformImpl implements LoaderPlatform { + @Override + public boolean isModLoaded(String id) { + return Loader.isModLoaded(id); + } + + @Override + public boolean hasActiveModContainer() { + return Loader.instance().activeModContainer() != null; + } + + @Override + public ActiveMod getActiveModContainer() { + ModContainer container = Loader.instance().activeModContainer(); + if (container == null) + return null; + return new ActiveMod(container.getName(), container.getModId(), container.getVersion()); + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/MousePlatformImpl.java b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/MousePlatformImpl.java new file mode 100644 index 0000000..1276000 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/MousePlatformImpl.java @@ -0,0 +1,53 @@ +package cc.polyfrost.oneconfig.platform.impl; + +import cc.polyfrost.oneconfig.platform.MousePlatform; +import org.lwjgl.input.Mouse; + +@SuppressWarnings("unused") +public class MousePlatformImpl implements MousePlatform { + + @Override + public int getMouseX() { + return Mouse.getX(); + } + + @Override + public int getMouseY() { + return Mouse.getY(); + } + + @Override + public int getDWheel() { + return Mouse.getDWheel(); + } + + @Override + public int getMouseDX() { + return Mouse.getDX(); + } + + @Override + public int getMouseDY() { + return Mouse.getDY(); + } + + @Override + public boolean next() { + return Mouse.next(); + } + + @Override + public boolean getEventButtonState() { + return Mouse.getEventButtonState(); + } + + @Override + public int getEventButton() { + return Mouse.getEventButton(); + } + + @Override + public boolean isButtonDown(int button) { + return Mouse.isButtonDown(button); + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/PlatformImpl.java b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/PlatformImpl.java new file mode 100644 index 0000000..7ad639c --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/PlatformImpl.java @@ -0,0 +1,12 @@ +package cc.polyfrost.oneconfig.platform.impl; + +import cc.polyfrost.oneconfig.platform.Platform; +import net.minecraft.client.Minecraft; + +@SuppressWarnings("unused") +public class PlatformImpl implements Platform { + @Override + public boolean isCallingFromMinecraftThread() { + return Minecraft.getMinecraft().isCallingFromMinecraftThread(); + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/ServerPlatformImpl.java b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/ServerPlatformImpl.java new file mode 100644 index 0000000..81454b0 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/platform/impl/ServerPlatformImpl.java @@ -0,0 +1,22 @@ +package cc.polyfrost.oneconfig.platform.impl; + +import cc.polyfrost.oneconfig.libs.universal.UMinecraft; +import cc.polyfrost.oneconfig.platform.ServerPlatform; +import net.minecraft.client.entity.EntityPlayerSP; + +@SuppressWarnings("unused") +public class ServerPlatformImpl implements ServerPlatform { + + @Override + public boolean inMultiplayer() { + return UMinecraft.getWorld() != null && !UMinecraft.getMinecraft().isSingleplayer(); + } + + @Override + public String getServerBrand() { + EntityPlayerSP player = UMinecraft.getPlayer(); + if (player == null) + return null; + return player.getClientBrand(); + } +} diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/utils/commands/PlatformCommandManagerImpl.java b/versions/src/main/java/cc/polyfrost/oneconfig/utils/commands/PlatformCommandManagerImpl.java new file mode 100644 index 0000000..8b6edcc --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/utils/commands/PlatformCommandManagerImpl.java @@ -0,0 +1,330 @@ +package cc.polyfrost.oneconfig.utils.commands; + +import cc.polyfrost.oneconfig.libs.universal.ChatColor; +import cc.polyfrost.oneconfig.libs.universal.UChat; +import cc.polyfrost.oneconfig.utils.commands.annotations.Command; +import cc.polyfrost.oneconfig.utils.commands.annotations.Greedy; +import cc.polyfrost.oneconfig.utils.commands.annotations.Name; +import cc.polyfrost.oneconfig.utils.commands.annotations.SubCommand; +import cc.polyfrost.oneconfig.utils.commands.arguments.ArgumentParser; +import cc.polyfrost.oneconfig.utils.commands.arguments.Arguments; +import net.minecraft.command.CommandBase; +import net.minecraft.command.ICommandSender; +import net.minecraft.util.BlockPos; +import net.minecraftforge.client.ClientCommandHandler; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.ImmutableTriple; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.lang3.tuple.Triple; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Parameter; +import java.util.*; + +import static cc.polyfrost.oneconfig.utils.commands.CommandManager.*; + +public class PlatformCommandManagerImpl implements PlatformCommandManager { + + @Override + public void createCommand(CommandManager.InternalCommand root, Command annotation) { + ClientCommandHandler.instance.registerCommand(new CommandBase() { + @Override + public String getCommandName() { + return annotation.value(); + } + + @Override + public String getCommandUsage(ICommandSender sender) { + return "/" + annotation.value(); + } + + @Override + public void processCommand(ICommandSender sender, String[] args) { + handleCommand(root, annotation, args); + } + + @Override + public int getRequiredPermissionLevel() { + return -1; + } + + @Override + public List addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) { + return handleTabCompletion(root, annotation, args); + } + }); + } + + private void handleCommand(CommandManager.InternalCommand root, Command annotation, String[] args) { + if (args.length == 0) { + if (!root.invokers.isEmpty()) { + try { + root.invokers.get(0).method.invoke(null); + } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException | + ExceptionInInitializerError e) { + e.printStackTrace(); + UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + METHOD_RUN_ERROR); + } + } + } else { + if (annotation.helpCommand() && args[0].equalsIgnoreCase("help")) { + UChat.chat(sendHelpCommand(root)); + } else { + List commands = new ArrayList<>(); + int depth = 0; + for (CommandManager.InternalCommand command : root.children) { + int newDepth = loopThroughCommands(commands, 0, command, args); + if (newDepth != -1) { + depth = newDepth; + break; + } + } + if (commands.isEmpty()) { + if (depth == -2) { + UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + TOO_MANY_PARAMETERS.replace("@ROOT_COMMAND@", annotation.value())); + } else { + UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + NOT_FOUND_TEXT.replace("@ROOT_COMMAND@", annotation.value())); + } + } else { + List errors = new ArrayList<>(); + for (CommandManager.InternalCommand.InternalCommandInvoker invoker : commands) { + try { + List params = getParametersForInvoker(invoker, depth, args); + if (params.size() == 1) { + Object first = params.get(0); + if (first instanceof CommandManager.CustomError) { + errors.add((CommandManager.CustomError) first); + continue; + } + } + invoker.method.invoke(null, params.toArray()); + return; + } catch (Exception e) { + e.printStackTrace(); + UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + METHOD_RUN_ERROR); + return; + } + } + //noinspection ConstantConditions + if (!errors.isEmpty()) { + UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + "Multiple errors occurred:"); + for (CommandManager.CustomError error : errors) { + UChat.chat(" " + ChatColor.RED + ChatColor.BOLD + error.message); + } + } + } + } + } + } + + private List handleTabCompletion(CommandManager.InternalCommand root, Command annotation, String[] args) { + try { + Set> commands = new HashSet<>(); + for (CommandManager.InternalCommand command : root.children) { + loopThroughCommandsTab(commands, 0, command, args); + } + if (!commands.isEmpty() || annotation.helpCommand()) { + List> validCommands = new ArrayList<>(); // command, depth, and all processed params + for (Pair pair : commands) { + CommandManager.InternalCommand.InternalCommandInvoker invoker = pair.getLeft(); + int depth = pair.getRight(); + int currentParam = 0; + boolean failed = false; + while (args.length - depth > 1) { + Parameter param = invoker.method.getParameters()[currentParam]; + if (param.isAnnotationPresent(Greedy.class) && currentParam + 1 != invoker.parameterTypes.length) { + failed = true; + break; + } + ArgumentParser parser = INSTANCE.parsers.get(param.getType()); + if (parser == null) { + failed = true; + break; + } + try { + Arguments arguments = new Arguments(Arrays.copyOfRange(args, depth, args.length), param.isAnnotationPresent(Greedy.class)); + if (parser.parse(arguments) != null) { + depth += arguments.getPosition(); + currentParam++; + } else { + failed = true; + break; + } + } catch (Exception e) { + failed = true; + break; + } + } + if (!failed) { + validCommands.add(new ImmutableTriple<>(pair.getLeft(), depth, currentParam)); + } + } + if (!validCommands.isEmpty() || annotation.helpCommand()) { + Set completions = new HashSet<>(); + for (Triple valid : validCommands) { + if (valid.getMiddle() == args.length) { + completions.add(valid.getLeft().name); + completions.addAll(Arrays.asList(valid.getLeft().aliases)); + continue; + } + if (valid.getRight() + 1 > valid.getLeft().parameterTypes.length) continue; + Parameter param = valid.getLeft().method.getParameters()[valid.getRight()]; + if (param.isAnnotationPresent(Greedy.class) && valid.getRight() + 1 != valid.getLeft().parameterTypes.length) { + continue; + } + ArgumentParser parser = INSTANCE.parsers.get(param.getType()); + if (parser == null) { + continue; + } + try { + Arguments arguments = new Arguments(Arrays.copyOfRange(args, valid.getMiddle(), args.length), param.isAnnotationPresent(Greedy.class)); + List possibleCompletions = parser.complete(arguments, param); + if (possibleCompletions != null) { + completions.addAll(possibleCompletions); + } + } catch (Exception ignored) { + + } + } + if (args.length == 1 && annotation.helpCommand()) { + if ("help".startsWith(args[0].toLowerCase(Locale.ENGLISH))) { + completions.add("help"); + } + } + return new ArrayList<>(completions); + } + } + } catch (Exception ignored) { + + } + return null; + } + + private List getParametersForInvoker(CommandManager.InternalCommand.InternalCommandInvoker invoker, int depth, String[] args) { + List parameters = new ArrayList<>(); + int processed = depth; + int currentParam = 0; + while (processed < args.length) { + Parameter param = invoker.method.getParameters()[currentParam]; + if (param.isAnnotationPresent(Greedy.class) && currentParam + 1 != invoker.parameterTypes.length) { + return Collections.singletonList(new CommandManager.CustomError("Parsing failed: Greedy parameter must be the last one.")); + } + ArgumentParser parser = INSTANCE.parsers.get(param.getType()); + if (parser == null) { + return Collections.singletonList(new CommandManager.CustomError("No parser for " + invoker.method.getParameterTypes()[currentParam].getSimpleName() + "! Please report this to the mod author.")); + } + try { + Arguments arguments = new Arguments(Arrays.copyOfRange(args, processed, args.length), param.isAnnotationPresent(Greedy.class)); + try { + Object a = parser.parse(arguments); + if (a != null) { + parameters.add(a); + processed += arguments.getPosition(); + currentParam++; + } else { + return Collections.singletonList(new CommandManager.CustomError("Failed to parse " + param.getType().getSimpleName() + "! Please report this to the mod author.")); + } + } catch (Exception e) { + return Collections.singletonList(new CommandManager.CustomError("A " + e.getClass().getSimpleName() + " has occured while try to parse " + param.getType().getSimpleName() + "! Please report this to the mod author.")); + } + } catch (Exception e) { + return Collections.singletonList(new CommandManager.CustomError("A " + e.getClass().getSimpleName() + " has occured while try to parse " + param.getType().getSimpleName() + "! Please report this to the mod author.")); + } + } + return parameters; + } + + private int loopThroughCommands(List commands, int depth, CommandManager.InternalCommand command, String[] args) { + int nextDepth = depth + 1; + boolean thatOneSpecialError = false; + if (command.isValid(args[depth], false)) { + for (CommandManager.InternalCommand child : command.children) { + if (args.length > nextDepth && child.isValid(args[nextDepth], false)) { + int result = loopThroughCommands(commands, nextDepth, child, args); + if (result > -1) { + return result; + } else if (result == -2) { + thatOneSpecialError = true; + } + } + } + boolean added = false; + for (CommandManager.InternalCommand.InternalCommandInvoker invoker : command.invokers) { + if (args.length - nextDepth == invoker.parameterTypes.length) { + commands.add(invoker); + added = true; + } else { + thatOneSpecialError = true; + } + } + if (added) { + return nextDepth; + } + } + return thatOneSpecialError ? -2 : -1; + } + + private void loopThroughCommandsTab(Set> commands, int depth, CommandManager.InternalCommand command, String[] args) { + int nextDepth = depth + 1; + if (command.isValid(args[depth], args.length == nextDepth)) { + if (args.length != nextDepth) { + for (CommandManager.InternalCommand child : command.children) { + if (child.isValid(args[nextDepth], args.length == nextDepth + 1)) { + loopThroughCommandsTab(commands, nextDepth, child, args); + } + } + } + for (CommandManager.InternalCommand.InternalCommandInvoker invoker : command.invokers) { + commands.add(new ImmutablePair<>(invoker, nextDepth)); + } + } + } + + //TODO: someone make the help command actually look nice lmao + private String sendHelpCommand(CommandManager.InternalCommand root) { + StringBuilder builder = new StringBuilder(); + builder.append(ChatColor.GOLD).append("Help for ").append(ChatColor.BOLD).append(root.name).append(ChatColor.RESET).append(ChatColor.GOLD).append(":\n"); + if (!root.description.isEmpty()) { + builder.append("\n").append(ChatColor.GOLD).append("Description: ").append(ChatColor.BOLD).append(root.description); + } + for (CommandManager.InternalCommand command : root.children) { + runThroughCommandsHelp(root.name, command, builder); + } + builder.append("\n").append(ChatColor.GOLD).append("Aliases: ").append(ChatColor.BOLD); + int index = 0; + for (String alias : root.aliases) { + ++index; + builder.append(alias).append(index < root.aliases.length ? ", " : ""); + } + builder.append("\n"); + return builder.toString(); + } + + private void runThroughCommandsHelp(String append, CommandManager.InternalCommand command, StringBuilder builder) { + if (!command.invokers.isEmpty()) { + Class declaringClass = command.invokers.get(0).method.getDeclaringClass(); + if (declaringClass.isAnnotationPresent(SubCommand.class)) { + String description = declaringClass.getAnnotation(SubCommand.class).description(); + if (!description.isEmpty()) { + builder.append("\n").append(ChatColor.GOLD).append("Description: ").append(ChatColor.BOLD).append(description); + } + } + } + for (CommandManager.InternalCommand.InternalCommandInvoker invoker : command.invokers) { + builder.append("\n").append(ChatColor.GOLD).append("/").append(append).append(" ").append(command.name); + for (Parameter parameter : invoker.method.getParameters()) { + String name = parameter.getName(); + if (parameter.isAnnotationPresent(Name.class)) { + name = parameter.getAnnotation(Name.class).value(); + } + builder.append(" <").append(name).append(">"); + } + if (!command.description.trim().isEmpty()) { + builder.append(": ").append(ChatColor.BOLD).append(command.description); + } + } + for (CommandManager.InternalCommand subCommand : command.children) { + runThroughCommandsHelp(append + " " + command.name, subCommand, builder); + } + } +} \ No newline at end of file diff --git a/versions/src/main/java/cc/polyfrost/oneconfig/utils/gui/GuiUtils.java b/versions/src/main/java/cc/polyfrost/oneconfig/utils/gui/GuiUtils.java new file mode 100644 index 0000000..6217bb6 --- /dev/null +++ b/versions/src/main/java/cc/polyfrost/oneconfig/utils/gui/GuiUtils.java @@ -0,0 +1,100 @@ +package cc.polyfrost.oneconfig.utils.gui; + +import cc.polyfrost.oneconfig.events.EventManager; +import cc.polyfrost.oneconfig.events.event.RenderEvent; +import cc.polyfrost.oneconfig.events.event.Stage; +import cc.polyfrost.oneconfig.gui.OneConfigGui; +import cc.polyfrost.oneconfig.libs.eventbus.Subscribe; +import cc.polyfrost.oneconfig.libs.universal.UMinecraft; +import cc.polyfrost.oneconfig.libs.universal.UScreen; +import cc.polyfrost.oneconfig.utils.TickDelay; +import net.minecraft.client.gui.GuiScreen; + +import java.util.Deque; +import java.util.Optional; +import java.util.concurrent.ConcurrentLinkedDeque; + +/** + * A class containing utility methods for working with GuiScreens. + */ +public final class GuiUtils { + private static long time = -1L; + private static long deltaTime = 17L; + private static final Deque> screenQueue = new ConcurrentLinkedDeque<>(); + + static { + EventManager.INSTANCE.register(new GuiUtils()); + } + + /** + * Displays a screen after a tick, preventing mouse sync issues. + * + * @param screen the screen to display. + * @deprecated Not actually deprecated, but should not be used. + */ + @Deprecated + public static void displayScreen(Object screen) { + displayScreen(((GuiScreen) screen)); + } + + /** + * Displays a screen after a tick, preventing mouse sync issues. + * + * @param screen the screen to display. + */ + public static void displayScreen(GuiScreen screen) { + //noinspection ConstantConditions + displayScreen(screen, screen instanceof OneConfigGui ? 2 : 1); + } + + /** + * Displays a screen after the specified amount of ticks. + * + * @param screen the screen to display. + * @param ticks the amount of ticks to wait for before displaying the screen. + */ + public static void displayScreen(GuiScreen screen, int ticks) { + Optional optional = Optional.of(screen); + screenQueue.add(optional); + new TickDelay(() -> { + UScreen.displayScreen(screen); + screenQueue.remove(optional); + }, ticks); + } + + public static Deque> getScreenQueue() { + return screenQueue; + } + + /** + * Close the current open GUI screen. + */ + public static void closeScreen() { + UScreen.displayScreen(null); + } + + /** + * Gets the delta time (in milliseconds) between frames. + *

+ * Not to be confused with Minecraft deltaTicks / renderPartialTicks, which can be gotten via + * {@link cc.polyfrost.oneconfig.events.event.TimerUpdateEvent} + *

+ * + * @return the delta time. + */ + public static float getDeltaTime() { + return deltaTime; + } + + @Subscribe + private void onRenderEvent(RenderEvent event) { + if (event.stage == Stage.START) { + if (time == -1) time = UMinecraft.getTime(); + else { + long currentTime = UMinecraft.getTime(); + deltaTime = currentTime - time; + time = currentTime; + } + } + } +} diff --git a/versions/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/DSLs.kt b/versions/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/DSLs.kt new file mode 100644 index 0000000..c8c18e4 --- /dev/null +++ b/versions/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/DSLs.kt @@ -0,0 +1,9 @@ +package cc.polyfrost.oneconfig.utils.dsl + +import cc.polyfrost.oneconfig.libs.universal.UMinecraft + +/** + * Gets the current [net.minecraft.client.Minecraft] instance. + */ +val mc + get() = UMinecraft.getMinecraft() \ No newline at end of file diff --git a/versions/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/GuiUtilsDSL.kt b/versions/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/GuiUtilsDSL.kt new file mode 100644 index 0000000..c70f686 --- /dev/null +++ b/versions/src/main/kotlin/cc/polyfrost/oneconfig/utils/dsl/GuiUtilsDSL.kt @@ -0,0 +1,11 @@ +package cc.polyfrost.oneconfig.utils.dsl + +import cc.polyfrost.oneconfig.utils.gui.GuiUtils +import net.minecraft.client.gui.GuiScreen + +/** + * Displays a screen after the specified amount of ticks. + * + * @param ticks the amount of ticks to wait for before displaying the screen. + */ +fun GuiScreen.openScreen(ticks: Int = 1) = GuiUtils.displayScreen(this, ticks) \ No newline at end of file diff --git a/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.internal.gui.BlurHandler b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.internal.gui.BlurHandler new file mode 100644 index 0000000..85a263a --- /dev/null +++ b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.internal.gui.BlurHandler @@ -0,0 +1 @@ +cc.polyfrost.oneconfig.internal.gui.impl.BlurHandlerImpl \ No newline at end of file diff --git a/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.GLPlatform b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.GLPlatform new file mode 100644 index 0000000..74d17cb --- /dev/null +++ b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.GLPlatform @@ -0,0 +1 @@ +cc.polyfrost.oneconfig.platform.impl.GLPlatformImpl \ No newline at end of file diff --git a/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.GuiPlatform b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.GuiPlatform new file mode 100644 index 0000000..b228911 --- /dev/null +++ b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.GuiPlatform @@ -0,0 +1 @@ +cc.polyfrost.oneconfig.platform.impl.GuiPlatformImpl \ No newline at end of file diff --git a/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.I18nPlatform b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.I18nPlatform new file mode 100644 index 0000000..a8ffd49 --- /dev/null +++ b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.I18nPlatform @@ -0,0 +1 @@ +cc.polyfrost.oneconfig.platform.impl.I18nPlatformImpl \ No newline at end of file diff --git a/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.LoaderPlatform b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.LoaderPlatform new file mode 100644 index 0000000..f17bd87 --- /dev/null +++ b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.LoaderPlatform @@ -0,0 +1 @@ +cc.polyfrost.oneconfig.platform.impl.LoaderPlatformImpl \ No newline at end of file diff --git a/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.MousePlatform b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.MousePlatform new file mode 100644 index 0000000..a6071db --- /dev/null +++ b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.MousePlatform @@ -0,0 +1 @@ +cc.polyfrost.oneconfig.platform.impl.MousePlatformImpl \ No newline at end of file diff --git a/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.Platform b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.Platform new file mode 100644 index 0000000..397ade7 --- /dev/null +++ b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.Platform @@ -0,0 +1 @@ +cc.polyfrost.oneconfig.platform.impl.PlatformImpl \ No newline at end of file diff --git a/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.ServerPlatform b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.ServerPlatform new file mode 100644 index 0000000..261df35 --- /dev/null +++ b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.platform.ServerPlatform @@ -0,0 +1 @@ +cc.polyfrost.oneconfig.platform.impl.ServerPlatformImpl \ No newline at end of file diff --git a/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.utils.commands.PlatformCommandManager b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.utils.commands.PlatformCommandManager new file mode 100644 index 0000000..000adc7 --- /dev/null +++ b/versions/src/main/resources/META-INF/services/cc.polyfrost.oneconfig.utils.commands.PlatformCommandManager @@ -0,0 +1 @@ +cc.polyfrost.oneconfig.utils.commands.PlatformCommandManagerImpl \ No newline at end of file diff --git a/versions/src/main/resources/mixins.oneconfig.json b/versions/src/main/resources/mixins.oneconfig.json new file mode 100644 index 0000000..4a03fd0 --- /dev/null +++ b/versions/src/main/resources/mixins.oneconfig.json @@ -0,0 +1,21 @@ +{ + "compatibilityLevel": "JAVA_8", + "minVersion": "0.7", + "package": "cc.polyfrost.oneconfig.internal.mixin", + "refmap": "mixins.oneconfig.refmap.json", + "plugin": "cc.polyfrost.oneconfig.internal.plugin.OneConfigMixinPlugin", + "injectors": { + "maxShiftBy": 5 + }, + "verbose": true, + "client": [ + "GuiIngameForgeMixin", + "MinecraftMixin", + "NetHandlerPlayClientMixin", + "NetworkManagerMixin", + "OptifineConfigMixin", + "ShaderGroupAccessor", + "VigilantMixin", + "WorldClientMixin" + ] +} \ No newline at end of file -- cgit