From e8196b0b5e02ec21f75109ab7aba8d48220c8d05 Mon Sep 17 00:00:00 2001 From: Linnea Gräf Date: Thu, 22 Feb 2024 21:23:38 +0100 Subject: Template --- .gitattributes | 3 + .github/workflows/build.yml | 29 +++ .github/workflows/gradle-wrapper-validation.yml | 10 + .gitignore | 6 + build.gradle.kts | 155 +++++++++++++ gradle.properties | 6 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43462 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 249 +++++++++++++++++++++ gradlew.bat | 92 ++++++++ log4j2.xml | 5 + settings.gradle.kts | 26 +++ .../kowalski/init/AutoDiscoveryMixinPlugin.java | 188 ++++++++++++++++ src/main/kotlin/moe/nea/kowalski/ExampleMod.kt | 22 ++ .../moe/nea/kowalski/mixin/MixinGuiMainMenu.java | 16 ++ src/main/resources/assets/test/test.txt | 3 + src/main/resources/mcmod.info | 18 ++ src/main/resources/mixins.kowalski.json | 8 + 18 files changed, 843 insertions(+) create mode 100644 .gitattributes create mode 100644 .github/workflows/build.yml create mode 100644 .github/workflows/gradle-wrapper-validation.yml create mode 100644 .gitignore create mode 100644 build.gradle.kts create mode 100644 gradle.properties create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 log4j2.xml create mode 100644 settings.gradle.kts create mode 100644 src/main/java/moe/nea/kowalski/init/AutoDiscoveryMixinPlugin.java create mode 100644 src/main/kotlin/moe/nea/kowalski/ExampleMod.kt create mode 100644 src/main/kotlin/moe/nea/kowalski/mixin/MixinGuiMainMenu.java create mode 100644 src/main/resources/assets/test/test.txt create mode 100644 src/main/resources/mcmod.info create mode 100644 src/main/resources/mixins.kowalski.json diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..df936ee --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +gradlew* linguist-vendored +gradle/wrapper/* linguist-vendored + diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..e1e773f --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,29 @@ +name: Run Gradle Build +on: + - push + - pull_request + +jobs: + gradle: + runs-on: ubuntu-latest + steps: + - name: Checkout source + uses: actions/checkout@v4.1.1 + + - name: Setup Java + uses: actions/setup-java@v4.0.0 + with: + distribution: temurin + java-version: 17 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + + - name: Execute Gradle build + run: ./gradlew build + + - name: Upload built mod JAR + uses: actions/upload-artifact@v4.3.0 + with: + name: mod-jar + path: build/libs/*.jar diff --git a/.github/workflows/gradle-wrapper-validation.yml b/.github/workflows/gradle-wrapper-validation.yml new file mode 100644 index 0000000..12213d2 --- /dev/null +++ b/.github/workflows/gradle-wrapper-validation.yml @@ -0,0 +1,10 @@ +name: "Validate Gradle Wrapper" +on: [push, pull_request] + +jobs: + validation: + name: "Validation" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4.1.1 + - uses: gradle/wrapper-validation-action@v2.0.0 \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..69fa48a --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.idea/ +.vscode/ +run/ +build/ +.gradle/ + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..98f7efa --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,155 @@ +import org.apache.commons.lang3.SystemUtils + +plugins { + idea + java + id("gg.essential.loom") version "0.10.0.+" + id("dev.architectury.architectury-pack200") version "0.1.3" + id("com.github.johnrengelman.shadow") version "8.1.1" + kotlin("jvm") version "1.8.21" +} + +//Constants: + +val baseGroup: String by project +val mcVersion: String by project +val version: String by project +val mixinGroup = "$baseGroup.mixin" +val modid: String by project + +// Toolchains: +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(8)) +} + +// Minecraft configuration: +loom { + log4jConfigs.from(file("log4j2.xml")) + launchConfigs { + "client" { + // If you don't want mixins, remove these lines + property("mixin.debug", "true") + property("asmhelper.verbose", "true") + arg("--tweakClass", "org.spongepowered.asm.launch.MixinTweaker") + } + } + runConfigs { + "client" { + if (SystemUtils.IS_OS_MAC_OSX) { + // This argument causes a crash on macOS + vmArgs.remove("-XstartOnFirstThread") + } + } + remove(getByName("server")) + } + forge { + pack200Provider.set(dev.architectury.pack200.java.Pack200Adapter()) + // If you don't want mixins, remove this lines + mixinConfig("mixins.$modid.json") + } + // If you don't want mixins, remove these lines + mixin { + defaultRefmapName.set("mixins.$modid.refmap.json") + } +} + +tasks.compileJava { + dependsOn(tasks.processResources) +} + +sourceSets.main { + output.setResourcesDir(sourceSets.main.flatMap { it.java.classesDirectory }) + java.srcDir(layout.projectDirectory.dir("src/main/kotlin")) + kotlin.destinationDirectory.set(java.destinationDirectory) +} + +// Dependencies: + +repositories { + mavenCentral() + maven("https://repo.spongepowered.org/maven/") + // If you don't want to log in with your real minecraft account, remove this line + maven("https://pkgs.dev.azure.com/djtheredstoner/DevAuth/_packaging/public/maven/v1") +} + +val shadowImpl: Configuration by configurations.creating { + configurations.implementation.get().extendsFrom(this) +} + +dependencies { + minecraft("com.mojang:minecraft:1.8.9") + mappings("de.oceanlabs.mcp:mcp_stable:22-1.8.9") + forge("net.minecraftforge:forge:1.8.9-11.15.1.2318-1.8.9") + + shadowImpl(kotlin("stdlib-jdk8")) + + // If you don't want mixins, remove these lines + shadowImpl("org.spongepowered:mixin:0.7.11-SNAPSHOT") { + isTransitive = false + } + annotationProcessor("org.spongepowered:mixin:0.8.5-SNAPSHOT") + + // If you don't want to log in with your real minecraft account, remove this line + runtimeOnly("me.djtheredstoner:DevAuth-forge-legacy:1.1.2") + +} + +// Tasks: + +tasks.withType(JavaCompile::class) { + options.encoding = "UTF-8" +} + +tasks.withType(Jar::class) { + archiveBaseName.set(modid) + manifest.attributes.run { + this["FMLCorePluginContainsFMLMod"] = "true" + this["ForceLoadAsMod"] = "true" + + // If you don't want mixins, remove these lines + this["TweakClass"] = "org.spongepowered.asm.launch.MixinTweaker" + this["MixinConfigs"] = "mixins.$modid.json" + } +} + +tasks.processResources { + inputs.property("version", project.version) + inputs.property("mcversion", mcVersion) + inputs.property("modid", modid) + inputs.property("basePackage", baseGroup) + + filesMatching(listOf("mcmod.info", "mixins.$modid.json")) { + expand(inputs.properties) + } + + rename("(.+_at.cfg)", "META-INF/$1") +} + + +val remapJar by tasks.named("remapJar") { + archiveClassifier.set("") + from(tasks.shadowJar) + input.set(tasks.shadowJar.get().archiveFile) +} + +tasks.jar { + archiveClassifier.set("without-deps") + destinationDirectory.set(layout.buildDirectory.dir("badjars")) +} + +tasks.shadowJar { + destinationDirectory.set(layout.buildDirectory.dir("badjars")) + archiveClassifier.set("all-dev") + configurations = listOf(shadowImpl) + doLast { + configurations.forEach { + println("Copying jars into mod: ${it.files}") + } + } + + // If you want to include other dependencies and shadow them, you can relocate them in here + fun relocate(name: String) = relocate(name, "$baseGroup.deps.$name") +} + +tasks.assemble.get().dependsOn(tasks.remapJar) + diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..53b0217 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,6 @@ +loom.platform=forge +org.gradle.jvmargs=-Xmx2g +baseGroup = moe.nea.kowalski +mcVersion = 1.8.9 +modid = kowalski +version = 1.0.0 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a80b22c --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/log4j2.xml b/log4j2.xml new file mode 100644 index 0000000..af9b1b7 --- /dev/null +++ b/log4j2.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..5e8b872 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + maven("https://oss.sonatype.org/content/repositories/snapshots") + maven("https://maven.architectury.dev/") + maven("https://maven.fabricmc.net") + maven("https://maven.minecraftforge.net/") + maven("https://repo.spongepowered.org/maven/") + maven("https://repo.sk1er.club/repository/maven-releases/") + } + resolutionStrategy { + eachPlugin { + when (requested.id.id) { + "gg.essential.loom" -> useModule("gg.essential:architectury-loom:${requested.version}") + } + } + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version("0.6.0") +} + + +rootProject.name = "Kowalski" diff --git a/src/main/java/moe/nea/kowalski/init/AutoDiscoveryMixinPlugin.java b/src/main/java/moe/nea/kowalski/init/AutoDiscoveryMixinPlugin.java new file mode 100644 index 0000000..715c41f --- /dev/null +++ b/src/main/java/moe/nea/kowalski/init/AutoDiscoveryMixinPlugin.java @@ -0,0 +1,188 @@ +package moe.nea.kowalski.init; + +import org.spongepowered.asm.lib.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +/** + * A mixin plugin to automatically discover all mixins in the current JAR. + *

+ * This mixin plugin automatically scans your entire JAR (or class directory, in case of an in-IDE launch) for classes inside of your + * mixin package and registers those. It does this recursively for sub packages of the mixin package as well. This means you will need + * to only have mixin classes inside of your mixin package, which is good style anyway. + * + * @author Linnea Gräf + */ +public class AutoDiscoveryMixinPlugin implements IMixinConfigPlugin { + private static final List mixinPlugins = new ArrayList<>(); + + public static List getMixinPlugins() { + return mixinPlugins; + } + + private String mixinPackage; + + @Override + public void onLoad(String mixinPackage) { + this.mixinPackage = mixinPackage; + mixinPlugins.add(this); + } + + /** + * Resolves the base class root for a given class URL. This resolves either the JAR root, or the class file root. + * In either case the return value of this + the class name will resolve back to the original class url, or to other + * class urls for other classes. + */ + public URL getBaseUrlForClassUrl(URL classUrl) { + String string = classUrl.toString(); + if (classUrl.getProtocol().equals("jar")) { + try { + return new URL(string.substring(4).split("!")[0]); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + if (string.endsWith(".class")) { + try { + return new URL(string.replace("\\", "/") + .replace(getClass().getCanonicalName() + .replace(".", "/") + ".class", "")); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + return classUrl; + } + + /** + * Get the package that contains all the mixins. This value is set by mixin itself using {@link #onLoad}. + */ + public String getMixinPackage() { + return mixinPackage; + } + + /** + * Get the path inside the class root to the mixin package + */ + public String getMixinBaseDir() { + return mixinPackage.replace(".", "/"); + } + + /** + * A list of all discovered mixins. + */ + private List mixins = null; + + /** + * Try to add mixin class ot the mixins based on the filepath inside of the class root. + * Removes the {@code .class} file suffix, as well as the base mixin package. + *

This method cannot be called after mixin initialization.

+ * + * @param className the name or path of a class to be registered as a mixin. + */ + public void tryAddMixinClass(String className) { + String norm = (className.endsWith(".class") ? className.substring(0, className.length() - ".class".length()) : className) + .replace("\\", "/") + .replace("/", "."); + if (norm.startsWith(getMixinPackage() + ".") && !norm.endsWith(".")) { + mixins.add(norm.substring(getMixinPackage().length() + 1)); + } + } + + /** + * Search through the JAR or class directory to find mixins contained in {@link #getMixinPackage()} + */ + @Override + public List getMixins() { + if (mixins != null) return mixins; + System.out.println("Trying to discover mixins"); + mixins = new ArrayList<>(); + URL classUrl = getClass().getProtectionDomain().getCodeSource().getLocation(); + System.out.println("Found classes at " + classUrl); + Path file; + try { + file = Paths.get(getBaseUrlForClassUrl(classUrl).toURI()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + System.out.println("Base directory found at " + file); + if (Files.isDirectory(file)) { + walkDir(file); + } else { + walkJar(file); + } + System.out.println("Found mixins: " + mixins); + + return mixins; + } + + /** + * Search through directory for mixin classes based on {@link #getMixinBaseDir}. + * + * @param classRoot The root directory in which classes are stored for the default package. + */ + private void walkDir(Path classRoot) { + System.out.println("Trying to find mixins from directory"); + try (Stream classes = Files.walk(classRoot.resolve(getMixinBaseDir()))) { + classes.map(it -> classRoot.relativize(it).toString()) + .forEach(this::tryAddMixinClass); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Read through a JAR file, trying to find all mixins inside. + */ + private void walkJar(Path file) { + System.out.println("Trying to find mixins from jar file"); + try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(file))) { + ZipEntry next; + while ((next = zis.getNextEntry()) != null) { + tryAddMixinClass(next.getName()); + zis.closeEntry(); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + + } + + @Override + public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + + } + + @Override + public String getRefMapperConfig() { + return null; + } + + @Override + public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + return true; + } + + @Override + public void acceptTargets(Set myTargets, Set otherTargets) { + + } +} diff --git a/src/main/kotlin/moe/nea/kowalski/ExampleMod.kt b/src/main/kotlin/moe/nea/kowalski/ExampleMod.kt new file mode 100644 index 0000000..a622a6c --- /dev/null +++ b/src/main/kotlin/moe/nea/kowalski/ExampleMod.kt @@ -0,0 +1,22 @@ +package moe.nea.kowalski + +import net.minecraft.client.Minecraft +import net.minecraft.init.Blocks +import net.minecraftforge.fml.common.Mod +import net.minecraftforge.fml.common.event.FMLInitializationEvent + +@Mod(modid = "kowalski", useMetadata = true) +class ExampleMod { + @Mod.EventHandler + fun init(event: FMLInitializationEvent) { + try { + val resource: net.minecraft.client.resources.IResource = Minecraft.getMinecraft().getResourceManager() + .getResource(net.minecraft.util.ResourceLocation("test:test.txt")) + org.apache.commons.io.IOUtils.copy(resource.getInputStream(), java.lang.System.out) + } catch (e: java.io.IOException) { + throw java.lang.RuntimeException(e) + } + + println("Dirt: ${Blocks.dirt.unlocalizedName}") + } +} diff --git a/src/main/kotlin/moe/nea/kowalski/mixin/MixinGuiMainMenu.java b/src/main/kotlin/moe/nea/kowalski/mixin/MixinGuiMainMenu.java new file mode 100644 index 0000000..4ddc1b4 --- /dev/null +++ b/src/main/kotlin/moe/nea/kowalski/mixin/MixinGuiMainMenu.java @@ -0,0 +1,16 @@ +package moe.nea.kowalski.mixin; + +import net.minecraft.client.gui.GuiMainMenu; +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(GuiMainMenu.class) +public class MixinGuiMainMenu { + + @Inject(method = "initGui", at = @At("HEAD")) + public void onInitGui(CallbackInfo ci) { + System.out.println("Hello from Main Menu!"); + } +} diff --git a/src/main/resources/assets/test/test.txt b/src/main/resources/assets/test/test.txt new file mode 100644 index 0000000..ea839e2 --- /dev/null +++ b/src/main/resources/assets/test/test.txt @@ -0,0 +1,3 @@ +test +from resource pack + diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info new file mode 100644 index 0000000..ab6d5dd --- /dev/null +++ b/src/main/resources/mcmod.info @@ -0,0 +1,18 @@ +[ + { + "modid": "${modid}", + "name": "Xample Mod", + "description": "A mod that is used as an example.", + "version": "${version}", + "mcversion": "${mcversion}", + "url": "https://github.com/romangraef/Forge1.8.9Template/", + "updateUrl": "", + "authorList": [ + "You" + ], + "credits": "", + "logoFile": "", + "screenshots": [], + "dependencies": [] + } +] \ No newline at end of file diff --git a/src/main/resources/mixins.kowalski.json b/src/main/resources/mixins.kowalski.json new file mode 100644 index 0000000..5ea0c57 --- /dev/null +++ b/src/main/resources/mixins.kowalski.json @@ -0,0 +1,8 @@ +{ + "package": "${basePackage}.mixin", + "plugin": "${basePackage}.init.AutoDiscoveryMixinPlugin", + "refmap": "mixins.${modid}.refmap.json", + "minVersion": "0.7", + "compatibilityLevel": "JAVA_8", + "__comment": "You do not need to manually register mixins in this template. Check the auto discovery mixin plugin for more info." +} -- cgit