diff --git a/26_3/.gitignore b/26_3/.gitignore new file mode 100644 index 0000000..10db306 --- /dev/null +++ b/26_3/.gitignore @@ -0,0 +1,43 @@ +# gradle + +.gradle/ +build/ +out/ +classes/ + +# eclipse + +*.launch + +# idea + +.idea/ +*.iml +*.ipr +*.iws + +# vscode + +.settings/ +.vscode/ +bin/ +.classpath +.project + +# macos + +*.DS_Store + +# fabric + +run/ + +# java + +hs_err_*.log +replay_*.log +*.hprof +*.jfr +/libs/ +/logs/ +/.architectury-transformer/ diff --git a/26_3/build.gradle b/26_3/build.gradle new file mode 100644 index 0000000..4f4a226 --- /dev/null +++ b/26_3/build.gradle @@ -0,0 +1,257 @@ +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar + +plugins { + id 'com.gradleup.shadow' version '9.4.1' + id 'java' + id 'maven-publish' + id 'xyz.wagyourtail.unimined' version '1.4.2-SNAPSHOT' +} + +group 'me.earth' +version "$minecraft_version-${project(':api').project_version}" + +base { + archivesName = 'mc-runtime-test' +} + +sourceSets { + fabric + neoforge + lexforge +} + +repositories { + mavenCentral() + maven { + url = "https://maven.neoforged.net/releases" + } + maven { + url = "https://maven.fabricmc.net/" + } + maven { + url = "https://files.minecraftforge.net/maven" + } + maven { + name = "sponge" + url = "https://repo.spongepowered.org/maven" + } + maven { + url = "https://maven.wagyourtail.xyz/releases" + } + + maven { + name = '3arthMaven' + url = 'https://3arthqu4ke.github.io/maven' + } +} + +unimined.minecraft { + version project.minecraft_version + + mappings { + mojmap() + // intermediary() + // yarn(1) + + devFallbackNamespace "mojmap" + + /*stub.withMappings("intermediary", ["yarn"]) { + c("net/minecraft/class_1927", []) { + m("method_55109", "()Lnet/minecraft/class_243;", ["getPos"]) + } + }*/ + } + + defaultRemapJar = false +} + +unimined.minecraft(sourceSets.fabric) { + combineWith(sourceSets.main) + + fabric { + loader project.fabric_version + } + + defaultRemapJar = true +} + +unimined.minecraft(sourceSets.neoforge) { + combineWith(sourceSets.main) + + neoForged { + loader project.neoforge_version + mixinConfig 'mc_runtime_test.mixins.json' + mixinConfig 'mc_runtime_test.gametest.mixins.json' + } + + minecraftRemapper.config { + // neoforge adds 1 conflict, where 2 interfaces have a method with the same name on yarn/mojmap, + // but the method has different names in the intermediary mappings. + // this is a conflict because they have a class that extends both interfaces. + // this shouldn't be a problem as long as named mappings don't make the name of those 2 methods different. + ignoreConflicts(true) + } + + defaultRemapJar = true +} + +unimined.minecraft(sourceSets.lexforge) { + combineWith(sourceSets.main) + + minecraftForge { + loader project.lexforge_version + mixinConfig 'mc_runtime_test.mixins.json' + mixinConfig 'mc_runtime_test.gametest.mixins.json' + } + + minecraftRemapper.config { + ignoreConflicts(true) + } + + defaultRemapJar = true +} + +configurations { + mainImplementation + lwjglAgent.extendsFrom runtimeOnly + jarLibs + implementation.extendsFrom jarLibs +} + +for (String platform_capitalized : ['Fabric', 'Neoforge', 'Lexforge']) { + def platform = platform_capitalized.toLowerCase() + def remapJarTask = tasks.named("remap${platform_capitalized}Jar", AbstractArchiveTask).get() + def shadowTask = tasks.register("${platform}ShadowJar", ShadowJar) { + dependsOn(remapJarTask) + it.group = 'build' + it.archiveClassifier = "${platform}-release" + from { zipTree(remapJarTask.archiveFile.get().asFile) } + it.configurations.add(project.configurations.jarLibs) + exclude "**/module-info.class" + } + tasks.named('build') { finalizedBy(shadowTask) } +} + +dependencies { + compileOnly 'org.spongepowered:mixin:0.8.5-SNAPSHOT' + compileOnly 'me.earth.headlessmc:headlessmc:1.8.1' + lwjglAgent 'me.earth.headlessmc:headlessmc-lwjgl:1.8.1' + // yes, I actually want this at runtime to use assertions! + jarLibs 'org.junit.jupiter:junit-jupiter-api:5.10.1' + jarLibs project(':api') + neoforgeCompileOnly project(':api') + lexforgeCompileOnly project(':api') +} + +afterEvaluate { + fabricRunClient { + standardInput = System.in + if (rootProject.property('hmc.lwjgl').toBoolean()) { + jvmArgs += ["-javaagent:${configurations.lwjglAgent.files.iterator().next()}"] + systemProperties['joml.nounsafe'] = 'true' + systemProperties['fabric.systemLibraries'] = "${configurations.lwjglAgent.files.iterator().next()}" + } + } +} + +processFabricResources { + inputs.property "version", project.version + + filesMatching("fabric.mod.json") { + expand "version": project.version + } +} + +processNeoforgeResources { + inputs.property "version", project.version + + filesMatching("META-INF/neoforge.mods.toml") { + expand "version": project.version + } +} + +processLexforgeResources { + inputs.property "version", project.version + + filesMatching("META-INF/mods.toml") { + expand "version": project.version + } +} + +// Forge Runs seem to have problems running from the build/classes folder +// So instead we just run from the built jar +afterEvaluate { + lexforgeRunClient { + dependsOn(lexforgeJar) + classpath = classpath.filter { + !it.toString().contains('mc-runtime-test/build/classes/java/'.replace('/', File.separator)) + && !it.toString().contains('mc-runtime-test/build/resources/'.replace('/', File.separator)) + } + + classpath += files("${projectDir}/build/libs/mc-runtime-test-${version}-lexforge-dev.jar".replace('/', File.separator)) + } + + neoforgeRunClient { + dependsOn(neoforgeJar) + classpath = classpath.filter { + !it.toString().contains('mc-runtime-test/build/classes/java/'.replace('/', File.separator)) + && !it.toString().contains('mc-runtime-test/build/resources/'.replace('/', File.separator)) + } + + classpath += files("${projectDir}/build/libs/mc-runtime-test-${version}-neoforge-dev.jar".replace('/', File.separator)) + } +} + +tasks.withType(org.gradle.jvm.tasks.Jar).configureEach { + from("LICENSE") { + duplicatesStrategy = DuplicatesStrategy.INCLUDE + rename { "${it}_${project.archivesBaseName}" } + } + + manifest { + attributes( + 'Implementation-Title': 'MC-Runtime-Test', + 'MixinConfigs': name.toLowerCase().contains('lexforge') + ? 'mc_runtime_test.mixins.json,mc_runtime_test.gametest.mixins.json' + : 'mc_runtime_test.mixins.json', + 'Implementation-Version': project.version, + ) + } +} + +afterEvaluate { + publishing { + publications { + "${name.toLowerCase()}"(MavenPublication) { + ((MavenPublication) it).groupId "${group}" + ((MavenPublication) it).artifactId "${base.archivesName.get().toLowerCase()}" + ((MavenPublication) it).version "${version}" + from components.java + for (String platform: ['Fabric', 'Lexforge', 'Neoforge']) { + String platform_lower = platform.toLowerCase() + artifact tasks.named("${platform_lower}Jar").get() + artifact tasks.named("remap${platform}Jar").get() + artifact tasks.named("${platform_lower}ShadowJar").get() + } + } + } + + repositories { + if (System.getenv('DEPLOY_TO_GITHUB_PACKAGES_URL') == null) { + maven { + name = 'BuildDirMaven' + url = rootProject.projectDir.toPath().parent.resolve('build').resolve('maven') + } + } else { + maven { + name = 'GithubPagesMaven' + url = System.getenv('DEPLOY_TO_GITHUB_PACKAGES_URL') + credentials { + username = System.getenv('GITHUB_USER') + password = System.getenv('GITHUB_TOKEN') + } + } + } + } + } +} diff --git a/26_3/gradle.properties b/26_3/gradle.properties new file mode 100644 index 0000000..f3921ce --- /dev/null +++ b/26_3/gradle.properties @@ -0,0 +1,10 @@ +org.gradle.jvmargs = -Xmx2G + +minecraft_version = 26.3 +# TODO: can this be removed? +mapping_version = 1 +neoforge_version = 6-beta +lexforge_version = 66.0.2 +fabric_version = 0.19.5 +# Whether to use the headlessmc lwjgl agent or not +hmc.lwjgl=false diff --git a/26_3/gradle/wrapper/gradle-wrapper.jar b/26_3/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 Binary files /dev/null and b/26_3/gradle/wrapper/gradle-wrapper.jar differ diff --git a/26_3/gradle/wrapper/gradle-wrapper.properties b/26_3/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..eef906c --- /dev/null +++ b/26_3/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists \ No newline at end of file diff --git a/26_3/gradlew b/26_3/gradlew new file mode 100755 index 0000000..79a61d4 --- /dev/null +++ b/26_3/gradlew @@ -0,0 +1,244 @@ +#!/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##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# 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"' + +# 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 + which java >/dev/null 2>&1 || 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 + +# 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=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=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 + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +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/26_3/gradlew.bat b/26_3/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/26_3/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/26_3/settings.gradle b/26_3/settings.gradle new file mode 100644 index 0000000..e17fb98 --- /dev/null +++ b/26_3/settings.gradle @@ -0,0 +1,33 @@ +pluginManagement { + repositories { + mavenCentral() + maven { + url = "https://maven.neoforged.net/releases" + } + maven { + url = "https://maven.minecraftforge.net/" + } + maven { + url = "https://maven.fabricmc.net/" + } + maven { + url = "https://maven.wagyourtail.xyz/releases" + } + maven { + url 'https://3arthqu4ke.github.io/maven' + } + maven { + url = "https://maven.wagyourtail.xyz/snapshots" + } + gradlePluginPortal() { + content { + excludeGroup("org.apache.logging.log4j") + } + } + } +} + +include 'api' +project(':api').projectDir = file('../api') + +rootProject.name = 'mc-runtime-test' \ No newline at end of file diff --git a/26_3/src/fabric/resources/fabric.mod.json b/26_3/src/fabric/resources/fabric.mod.json new file mode 100644 index 0000000..eed8869 --- /dev/null +++ b/26_3/src/fabric/resources/fabric.mod.json @@ -0,0 +1,28 @@ +{ + "schemaVersion": 1, + "id": "mc_runtime_test", + "version": "${version}", + + "name": "MC-Runtime-Test", + "description": "Run tests on the Minecraft client at runtime", + "authors": [ + "3arthqu4ke" + ], + "contact": { + "homepage": "https://github.com/headlesshq/mc-runtime-test", + "sources": "https://github.com/headlesshq/mc-runtime-test" + }, + + "license": "MIT", + + "environment": "*", + "mixins": [ + "mc_runtime_test.mixins.json" + ], + + "depends": { + "fabricloader": ">=0.14.19", + "minecraft": "~26.3", + "java": ">=8" + } +} diff --git a/26_3/src/lexforge/java/me/earth/mc_runtime_test/forge/ForgeMod.java b/26_3/src/lexforge/java/me/earth/mc_runtime_test/forge/ForgeMod.java new file mode 100644 index 0000000..d21a353 --- /dev/null +++ b/26_3/src/lexforge/java/me/earth/mc_runtime_test/forge/ForgeMod.java @@ -0,0 +1,8 @@ +package me.earth.mc_runtime_test.forge; + +import net.minecraftforge.fml.common.Mod; + +@Mod("mc_runtime_test") +public class ForgeMod { + +} diff --git a/26_3/src/lexforge/java/me/earth/mc_runtime_test/mixin/MixinGameTestHooks.java b/26_3/src/lexforge/java/me/earth/mc_runtime_test/mixin/MixinGameTestHooks.java new file mode 100644 index 0000000..f85bb34 --- /dev/null +++ b/26_3/src/lexforge/java/me/earth/mc_runtime_test/mixin/MixinGameTestHooks.java @@ -0,0 +1,20 @@ +package me.earth.mc_runtime_test.mixin; + +import me.earth.mc_runtime_test.McRuntimeTest; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** Allows the test harness to run GameTests in installed Forge/NeoForge clients. */ +@Mixin(targets = "net.minecraftforge.gametest.ForgeGameTestHooks", remap = false) +public abstract class MixinGameTestHooks { + @Inject(method = "isGametestEnabled", at = @At("HEAD"), cancellable = true) + private static void enableRuntimeTests(CallbackInfoReturnable cir) { + // Both loaders gate their normal GameTest ticker behind development + // mode. The enableGameTest property alone cannot override production. + if (McRuntimeTest.RUN_GAME_TESTS) { + cir.setReturnValue(true); + } + } +} diff --git a/26_3/src/lexforge/resources/META-INF/mods.toml b/26_3/src/lexforge/resources/META-INF/mods.toml new file mode 100644 index 0000000..d099627 --- /dev/null +++ b/26_3/src/lexforge/resources/META-INF/mods.toml @@ -0,0 +1,20 @@ +modLoader = "javafml" +loaderVersion = "[1,)" +issueTrackerURL = "https://github.com/headlesshq/mc-runtime-test" +license = "MIT" + +[[mods]] +modId = "mc_runtime_test" +version = "${version}" +displayName = "MC-Runtime-Test" +authors = "3arthqu4ke" +description = ''' + Run tests on the Minecraft client at runtime +''' + +[[dependencies.mc_runtime_test]] +modId = "minecraft" +mandatory = true +versionRange = "[26.3,26.4)" +ordering = "NONE" +side = "BOTH" diff --git a/26_3/src/lexforge/resources/mc_runtime_test.gametest.mixins.json b/26_3/src/lexforge/resources/mc_runtime_test.gametest.mixins.json new file mode 100644 index 0000000..1e14976 --- /dev/null +++ b/26_3/src/lexforge/resources/mc_runtime_test.gametest.mixins.json @@ -0,0 +1,12 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "me.earth.mc_runtime_test.mixin", + "compatibilityLevel": "JAVA_8", + "client": [ + "MixinGameTestHooks" + ], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/26_3/src/lexforge/resources/pack.mcmeta b/26_3/src/lexforge/resources/pack.mcmeta new file mode 100644 index 0000000..d2b91b6 --- /dev/null +++ b/26_3/src/lexforge/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "mc_runtime_test resources", + "pack_format": 6 + } +} \ No newline at end of file diff --git a/26_3/src/main/java/me/earth/mc_runtime_test/McGameTestRunner.java b/26_3/src/main/java/me/earth/mc_runtime_test/McGameTestRunner.java new file mode 100644 index 0000000..2dd1406 --- /dev/null +++ b/26_3/src/main/java/me/earth/mc_runtime_test/McGameTestRunner.java @@ -0,0 +1,111 @@ +package me.earth.mc_runtime_test; + +import com.mojang.brigadier.Command; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.logging.LogUtils; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.gametest.framework.*; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.block.Rotation; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; + +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; + +/** + * Similar to running the "/test runall" command. + */ +public class McGameTestRunner { + private static final Logger LOGGER = LogUtils.getLogger(); + + /** + * Basically what happens in {@link TestCommand} when "runall" is used. + * The client checks the result and shuts down after the tests finish. + * + * @param playerUUID the uuid of the player. + * @param server the server to run the tests on. + */ + public static @Nullable MultipleTestTracker runGameTests(UUID playerUUID, MinecraftServer server) throws ExecutionException, InterruptedException, TimeoutException { + return server.submit(() -> { + Player player = Objects.requireNonNull(server.getPlayerList().getPlayer(playerUUID)); + ServerLevel level = (ServerLevel) player.level(); + // GameTestRunner.clearMarkers(level); + + AtomicReference> result = new AtomicReference<>(); + CommandDispatcher dispatcher = new CommandDispatcher<>(); + dispatcher.register(Commands.literal("test").executes(ctx -> { + String instance = System.getProperty("McRuntimeGameTestInstance"); + // Named tests can run in a fresh world without preplaced test + // blocks. Missing registry entries must fail rather than skip. + Collection> testFunctions = instance == null + ? TestFinder.builder().allNearby(ctx).findTests().toList() + : List.of(server.registryAccess().lookupOrThrow(Registries.TEST_INSTANCE) + .getOrThrow(ResourceKey.create(Registries.TEST_INSTANCE, Identifier.parse(instance)))); + LOGGER.info("TestFunctions: " + testFunctions); + if (testFunctions.size() < McRuntimeTest.MIN_GAME_TESTS_TO_FIND) { + LOGGER.error("Failed to find the minimum amount of gametests, expected " + McRuntimeTest.MIN_GAME_TESTS_TO_FIND + ", but found " + testFunctions.size()); + throw new IllegalStateException("Failed to find the minimum amount of gametests, expected " + McRuntimeTest.MIN_GAME_TESTS_TO_FIND + ", but found " + testFunctions.size()); + } else if (testFunctions.isEmpty()) { + result.set(Optional.empty()); + return Command.SINGLE_SUCCESS; + } + + GameTestBatchFactory.TestDecorator testDecorator = (reference, serverLevel) -> Stream.of( + new GameTestInfo(reference, Rotation.NONE, serverLevel, RetryOptions.noRetries()) + ); + // In 26.3, batch creation and the runner take the server. + Collection batches = GameTestBatchFactory.divideIntoBatches(testFunctions, testDecorator, ctx.getSource().getServer()); + + + FailedTestTracker.forgetFailedTests(); + + GameTestRunner.Builder builder = GameTestRunner.Builder.fromBatches(batches, server); + if (instance != null) { + builder.newStructureSpawner(new StructureGridSpawner( + dimension -> player.blockPosition().offset(0, 4, 8), 1, false)); + } + GameTestRunner gameTestRunner = builder.build(); + gameTestRunner.start(); + + MultipleTestTracker multipleTestTracker = new MultipleTestTracker(gameTestRunner.getTestInfos()); + multipleTestTracker.addFailureListener(gameTestInfo -> { + LOGGER.error("Test failed: " + gameTestInfo); + if (gameTestInfo.getError() != null) { + LOGGER.error(String.valueOf(gameTestInfo), gameTestInfo.getError()); + } + // The client handles failure after the batch completes, so + // the integrated server can save before the process exits. + }); + + result.set(Optional.of(multipleTestTracker)); + return Command.SINGLE_SUCCESS; + })); + + try { + dispatcher.execute("test", server.createCommandSourceStack()); + } catch (CommandSyntaxException e) { + throw new RuntimeException(e); + } + + return result.get().orElse(null); + }).get(60, TimeUnit.SECONDS); + } + +} diff --git a/26_3/src/main/java/me/earth/mc_runtime_test/mixin/ICreateWorldScreen.java b/26_3/src/main/java/me/earth/mc_runtime_test/mixin/ICreateWorldScreen.java new file mode 100644 index 0000000..f350807 --- /dev/null +++ b/26_3/src/main/java/me/earth/mc_runtime_test/mixin/ICreateWorldScreen.java @@ -0,0 +1,12 @@ +package me.earth.mc_runtime_test.mixin; + +import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(CreateWorldScreen.class) +public interface ICreateWorldScreen { + @Invoker("onCreate") + void invokeOnCreate(); + +} diff --git a/26_3/src/main/java/me/earth/mc_runtime_test/mixin/MixinGui.java b/26_3/src/main/java/me/earth/mc_runtime_test/mixin/MixinGui.java new file mode 100644 index 0000000..5b6428d --- /dev/null +++ b/26_3/src/main/java/me/earth/mc_runtime_test/mixin/MixinGui.java @@ -0,0 +1,43 @@ +package me.earth.mc_runtime_test.mixin; + +import me.earth.mc_runtime_test.McRuntimeTest; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.screens.DeathScreen; +import net.minecraft.client.gui.screens.ErrorScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.server.IntegratedServer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(Gui.class) +public class MixinGui { + + @Inject(method = "setScreen", at = @At("HEAD")) + private void setScreenHook(Screen screen, CallbackInfo ci) { + if (!McRuntimeTest.screenHook()) { + return; + } + var player = Minecraft.getInstance().player; + if (screen instanceof ErrorScreen) { + mcRuntime$stop(); + throw new RuntimeException("Error Screen " + screen); + } else if (screen instanceof DeathScreen && player != null) { + player.respawn(); + } + } + + @Unique + private void mcRuntime$stop() { + IntegratedServer server = Minecraft.getInstance().getSingleplayerServer(); + if (server != null) { + server.halt(true); + Minecraft.getInstance().disconnectWithProgressScreen(); + } + + Minecraft.getInstance().stop(); + } +} diff --git a/26_3/src/main/java/me/earth/mc_runtime_test/mixin/MixinMinecraft.java b/26_3/src/main/java/me/earth/mc_runtime_test/mixin/MixinMinecraft.java new file mode 100644 index 0000000..924322c --- /dev/null +++ b/26_3/src/main/java/me/earth/mc_runtime_test/mixin/MixinMinecraft.java @@ -0,0 +1,130 @@ +package me.earth.mc_runtime_test.mixin; + +import me.earth.mc_runtime_test.McGameTestRunner; +import me.earth.mc_runtime_test.McRuntimeTest; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.screens.DeathScreen; +import net.minecraft.client.gui.screens.ErrorScreen; +import net.minecraft.client.gui.screens.Overlay; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.server.IntegratedServer; +import net.minecraft.core.SectionPos; +import net.minecraft.gametest.framework.MultipleTestTracker; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.Objects; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; + +@Mixin(Minecraft.class) +public abstract class MixinMinecraft { + @Shadow @Final private static Logger LOGGER; + @Shadow @Nullable public LocalPlayer player; + @Shadow @Nullable public ClientLevel level; + @Shadow @Nullable private IntegratedServer singleplayerServer; + @Shadow private volatile boolean running; + + @Unique + private boolean mcRuntimeTest$startedLoadingSPWorld = false; + @Unique + private boolean mcRuntimeTest$worldCreationStarted = false; + @Unique + private MultipleTestTracker mcRuntimeTest$testTracker = null; + + @Shadow + public abstract void disconnectWithProgressScreen(); + + @Shadow + @Final + public Gui gui; + + @Inject(method = "tick", at = @At("HEAD")) + private void tickHook(CallbackInfo ci) throws ExecutionException, InterruptedException, TimeoutException { + if (!McRuntimeTest.tickHook()) { + return; + } + + if (gui.overlay() == null) { + if (!mcRuntimeTest$startedLoadingSPWorld && gui.overlay() == null) { + CreateWorldScreen.openFresh(Minecraft.class.cast(this), null); + mcRuntimeTest$startedLoadingSPWorld = true; + } else if (!mcRuntimeTest$worldCreationStarted && gui.screen() instanceof ICreateWorldScreen createWorldScreen) { + createWorldScreen.invokeOnCreate(); + mcRuntimeTest$worldCreationStarted = true; + } + } else { + LOGGER.info("Waiting for overlay to disappear..."); + } + + // TODO: detect SinglePlayerServer crash where game freezes? + if (player != null && level != null) { + if (gui.screen() == null) { + if (!level.getChunk(SectionPos.blockToSectionCoord(player.getBlockX()), SectionPos.blockToSectionCoord(player.getBlockZ())).isEmpty()) { + if (player.tickCount < 100) { + LOGGER.info("Waiting " + (100 - player.tickCount) + " ticks before testing..."); + } else if (mcRuntimeTest$testTracker == null) { + if (McRuntimeTest.RUN_GAME_TESTS) { + LOGGER.info("Running game tests..."); + mcRuntimeTest$testTracker = McGameTestRunner.runGameTests(player.getUUID(), Objects.requireNonNull(singleplayerServer)); + if (mcRuntimeTest$testTracker == null) { + mcRuntimeTest$testTracker = new MultipleTestTracker(); + LOGGER.info("No tests found, Successfully finished."); + mcRuntime$stop(); + } + } else { + LOGGER.info("Successfully finished."); + mcRuntime$stop(); + } + } else if (mcRuntimeTest$testTracker.isDone()) { + LOGGER.info("Game tests finished: {} run, {} required failures, {} optional failures", + mcRuntimeTest$testTracker.getTotalCount(), + mcRuntimeTest$testTracker.getFailedRequiredCount(), + mcRuntimeTest$testTracker.getFailedOptionalCount()); + mcRuntime$stop(); + if (mcRuntimeTest$testTracker.getFailedRequiredCount() > 0 + || mcRuntimeTest$testTracker.getFailedOptionalCount() > 0 && McRuntimeTest.GAME_TESTS_FAIL_ON_OPTIONAL) { + throw new IllegalStateException("Game tests failed; see the test results above"); + } + } else { + LOGGER.info("Waiting for GameTest: " + mcRuntimeTest$testTracker.getProgressBar()); + } + } else { + LOGGER.info("Players chunk not yet loaded, " + player + ": cores: " + Runtime.getRuntime().availableProcessors() + + ", server running: " + (singleplayerServer == null ? "null" : singleplayerServer.isRunning())); + } + } else { + LOGGER.info("Screen not yet null: " + gui.screen()); + if (McRuntimeTest.CLOSE_ANY_SCREEN || McRuntimeTest.CLOSE_CREATE_WORLD_SCREEN && gui.screen() instanceof CreateWorldScreen) { + LOGGER.info("Closing screen"); + gui.setScreen(null); + } + } + } else { + LOGGER.info("Waiting for player to load..."); + } + } + + @Unique + private void mcRuntime$stop() { + IntegratedServer server = singleplayerServer; + if (server != null) { + server.halt(true); + disconnectWithProgressScreen(); + } + + running = false; + } + +} diff --git a/26_3/src/main/resources/mc_runtime_test.mixins.json b/26_3/src/main/resources/mc_runtime_test.mixins.json new file mode 100644 index 0000000..8a366e5 --- /dev/null +++ b/26_3/src/main/resources/mc_runtime_test.mixins.json @@ -0,0 +1,14 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "me.earth.mc_runtime_test.mixin", + "compatibilityLevel": "JAVA_8", + "client": [ + "ICreateWorldScreen", + "MixinMinecraft", + "MixinGui" + ], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/26_3/src/neoforge/java/me/earth/mc_runtime_test/mixin/MixinGameTestHooks.java b/26_3/src/neoforge/java/me/earth/mc_runtime_test/mixin/MixinGameTestHooks.java new file mode 100644 index 0000000..b797363 --- /dev/null +++ b/26_3/src/neoforge/java/me/earth/mc_runtime_test/mixin/MixinGameTestHooks.java @@ -0,0 +1,20 @@ +package me.earth.mc_runtime_test.mixin; + +import me.earth.mc_runtime_test.McRuntimeTest; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** Allows the test harness to run GameTests in installed Forge/NeoForge clients. */ +@Mixin(targets = "net.neoforged.neoforge.gametest.GameTestHooks", remap = false) +public abstract class MixinGameTestHooks { + @Inject(method = "isGametestEnabled", at = @At("HEAD"), cancellable = true) + private static void enableRuntimeTests(CallbackInfoReturnable cir) { + // Both loaders gate their normal GameTest ticker behind development + // mode. The enableGameTest property alone cannot override production. + if (McRuntimeTest.RUN_GAME_TESTS) { + cir.setReturnValue(true); + } + } +} diff --git a/26_3/src/neoforge/java/me/earth/mc_runtime_test/neoforge/NeoForgeMod.java b/26_3/src/neoforge/java/me/earth/mc_runtime_test/neoforge/NeoForgeMod.java new file mode 100644 index 0000000..c8e767c --- /dev/null +++ b/26_3/src/neoforge/java/me/earth/mc_runtime_test/neoforge/NeoForgeMod.java @@ -0,0 +1,8 @@ +package me.earth.mc_runtime_test.neoforge; + +import net.neoforged.fml.common.Mod; + +@Mod("mc_runtime_test") +public class NeoForgeMod { + +} diff --git a/26_3/src/neoforge/resources/META-INF/neoforge.mods.toml b/26_3/src/neoforge/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..fa2a26f --- /dev/null +++ b/26_3/src/neoforge/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,26 @@ +modLoader = "javafml" +loaderVersion = "[1,)" +issueTrackerURL = "https://github.com/headlesshq/mc-runtime-test" +license = "MIT" + +[[mods]] +modId = "mc_runtime_test" +version = "${version}" +displayName = "MC-Runtime-Test" +authors = "3arthqu4ke" +description = ''' + Run tests on the Minecraft client at runtime +''' + +[[mixins]] +config="mc_runtime_test.mixins.json" + +[[mixins]] +config="mc_runtime_test.gametest.mixins.json" + +[[dependencies.mc_runtime_test]] +modId = "minecraft" +mandatory = true +versionRange = "[26.3,26.4)" +ordering = "NONE" +side = "BOTH" diff --git a/26_3/src/neoforge/resources/mc_runtime_test.gametest.mixins.json b/26_3/src/neoforge/resources/mc_runtime_test.gametest.mixins.json new file mode 100644 index 0000000..1e14976 --- /dev/null +++ b/26_3/src/neoforge/resources/mc_runtime_test.gametest.mixins.json @@ -0,0 +1,12 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "me.earth.mc_runtime_test.mixin", + "compatibilityLevel": "JAVA_8", + "client": [ + "MixinGameTestHooks" + ], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/26_3/src/neoforge/resources/pack.mcmeta b/26_3/src/neoforge/resources/pack.mcmeta new file mode 100644 index 0000000..d2b91b6 --- /dev/null +++ b/26_3/src/neoforge/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "mc_runtime_test resources", + "pack_format": 6 + } +} \ No newline at end of file diff --git a/README.md b/README.md index 66e0474..9c9e712 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ This project helps streamline that process by automating the client launch and b ### Supported Minecraft Versions and Modloaders | Version | Forge | Fabric | NeoForge | |-----------------|----------------|----------------|----------------| -| 26.1 - 26.2 | ✔️ | ✔️ | ✔️ | +| 26.1 - 26.3 | ✔️ | ✔️ | ✔️ | | 1.21 - 1.21.11 | ✔️ | ✔️ | ✔️ | | 1.20.2 - 1.20.6 | ✔️ | ✔️ | ✔️ | | 1.20.1 | ✔️ | ✔️ | ⚠️ | @@ -139,6 +139,20 @@ You can also use the `headlessmc-command` input to specify a JVM argument to enf -DMcRuntimeGameTestMinExpectedGameTests=1 +For 26.3, `-DMcRuntimeGameTestInstance=minecraft:always_pass` selects one +registered test instance and places its structure in the fresh world. Combine +it with `-DMcRuntimeGameTestMinExpectedGameTests=1` to prevent an empty run from +passing. Without the selector, discovery still uses nearby test blocks. +No-render runs on 26.3 also need a HeadlessMC release containing the SDL update. + +The 26.3 harness enables GameTests in installed Forge and NeoForge clients when +`McRuntimeGameTest` is true. Those loaders normally disable their GameTest ticker +in production, even with the `enableGameTest` property. Fabric uses the vanilla +ticker. Set `-DMcRuntimeGameTest=false` for a world-loading check without tests. + +Failed tests finish the batch and save the world before the client exits with an +error. `McRuntimeGameTestFailOnOptional=false` still allows optional failures. + --- ## Acknowledgments diff --git a/ci-data.json b/ci-data.json index e67eaf0..29b6b2d 100644 --- a/ci-data.json +++ b/ci-data.json @@ -5,6 +5,13 @@ "dir": "api", "java": "8" }, + { + "dir": "26_3", + "mc": "26.3", + "lex": "66.0.2", + "neo": "6-beta", + "java": "25" + }, { "dir": "26_2", "mc": "26.2",