diff --git a/.gitignore b/.gitignore index d4c25ad90..8f43e8055 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ run/ autotest/ dist/ +mapping/ # Gradle build/ diff --git a/build.gradle b/build.gradle index 0ce05058c..4d76c9e16 100755 --- a/build.gradle +++ b/build.gradle @@ -15,97 +15,140 @@ * along with Baritone. If not, see . */ -group 'baritone' -version '1.2.17' +allprojects { + apply plugin: 'java' + apply plugin: "xyz.wagyourtail.unimined" + apply plugin: "maven-publish" + + archivesBaseName = rootProject.archives_base_name + def vers; + try { + vers = 'git describe --always --tags --match=v* --dirty'.execute().text.trim() + } catch (IOException ignored) { + vers = "" + println "git doesn't appear to be installed!" + } + if (vers.equals("")) { + println "Couldn't find version tag!" + println "Using fallback version number: " + rootProject.mod_version + version = rootProject.mod_version + } else if (!vers.startsWith("v")) { + println "Couldn't find version tag!" + println "Using fallback version number: " + rootProject.mod_version + version = rootProject.mod_version + "-g" + vers + } else { + version = vers.substring(1) + } + group = rootProject.maven_group + + sourceCompatibility = targetCompatibility = JavaVersion.VERSION_1_8 + + minecraft { + mcRemapper.tinyRemapperConf = { + ignoreFieldDesc(true) + ignoreConflicts(true) + } + } -buildscript { repositories { maven { - name = 'forge' - url = 'http://files.minecraftforge.net/maven' + name = 'spongepowered-repo' + url = 'https://repo.spongepowered.org/repository/maven-public/' } maven { - name = 'SpongePowered' - url = 'https://repo.spongepowered.org/repository/maven-public/' + name = 'fabric-maven' + url = 'https://maven.fabricmc.net/' + } + maven { + name = 'forge-maven' + url = 'https://maven.minecraftforge.net/' + metadataSources { + artifact() + } + } + maven { + name = 'impactdevelopment-repo' + url = 'https://impactdevelopment.github.io/maven/' + } + maven { + name = "ldtteam" + url = "https://maven.parchmentmc.net/" + } + // for the newer version of launchwrapper + maven { + name = "multimc-maven" + url = "https://files.multimc.org/maven/" + metadataSources { + artifact() + } } - jcenter() + mavenCentral() } dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' - classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT' - } -} + minecraft "net.minecraft:minecraft:${rootProject.minecraft_version}" + mappings "de.oceanlabs.mcp:mcp_config:${rootProject.minecraft_version}@zip" + mappings "de.oceanlabs.mcp:mcp_${rootProject.mcp_channel}:${rootProject.mcp_version}@zip" + } -import baritone.gradle.task.CreateDistTask -import baritone.gradle.task.ProguardTask + tasks.withType(JavaCompile).configureEach { + it.options.encoding = "UTF-8" -apply plugin: 'java' -apply plugin: 'maven' -apply plugin: 'net.minecraftforge.gradle.tweaker-client' -apply plugin: 'org.spongepowered.mixin' + def targetVersion = 8 + if (JavaVersion.current().isJava9Compatible()) { + it.options.release = targetVersion + } + } +} -sourceCompatibility = targetCompatibility = '1.8' -compileJava { - sourceCompatibility = targetCompatibility = '1.8' - options.encoding = "UTF-8" // allow emoji in comments :^) +minecraft { + runs.off = true } +archivesBaseName = archivesBaseName + "-common" + sourceSets { + api { + compileClasspath += main.compileClasspath + runtimeClasspath += main.runtimeClasspath + } + main { + compileClasspath += api.output + runtimeClasspath += api.output + } + test { + compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output + runtimeClasspath += main.compileClasspath + main.runtimeClasspath + main.output + } launch { compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output + runtimeClasspath += main.compileClasspath + main.runtimeClasspath + main.output } - schematica_api { compileClasspath += main.compileClasspath + runtimeClasspath += main.runtimeClasspath } - main { compileClasspath += schematica_api.output + runtimeClasspath += schematica_api.output } } -minecraft { - version = '1.12.2' - mappings = 'stable_39' - tweakClass = 'baritone.launch.BaritoneTweaker' - runDir = 'run' - - // The sources jar should use SRG names not MCP to ensure compatibility with all mappings - makeObfSourceJar = true -} - -repositories { - mavenCentral() - - maven { - name = 'spongepowered-repo' - url = 'https://repo.spongepowered.org/repository/maven-public/' - } +dependencies { + testImplementation 'junit:junit:4.13.2' - maven { - name = 'impactdevelopment-repo' - url = 'https://impactdevelopment.github.io/maven/' + implementation "org.spongepowered:mixin:0.7.11-SNAPSHOT", { + transitive = false } } -dependencies { - runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.2') - runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') { - // Mixin includes a lot of dependencies that are too up-to-date - exclude module: 'launchwrapper' - exclude module: 'guava' - exclude module: 'gson' - exclude module: 'commons-io' - exclude module: 'log4j-core' - } - testImplementation 'junit:junit:4.12' +jar { + from sourceSets.main.output, sourceSets.launch.output, sourceSets.api.output } -mixin { - defaultObfuscationEnv searge - add sourceSets.launch, 'mixins.baritone.refmap.json' +remapJar { + target = "mcp" } javadoc { @@ -114,56 +157,4 @@ javadoc { options.encoding "UTF-8" // allow emoji in comments :^) source = sourceSets.api.allJava classpath += sourceSets.api.compileClasspath -} - -jar { - from sourceSets.launch.output, sourceSets.api.output - - if (!getProject().hasProperty("baritone.forge_build")) { - exclude "**/BaritoneForgeModXD.class" - exclude "**/mods.toml" - } - - preserveFileTimestamps = false - reproducibleFileOrder = true - - manifest { - attributes( - 'MixinConfigs': 'mixins.baritone.json', - - 'Implementation-Title': 'Baritone', - 'Implementation-Version': version - ) - } -} - -task proguard(type: ProguardTask) { - url 'https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip' - extract 'proguard6.0.3/lib/proguard.jar' -} - -task createDist(type: CreateDistTask, dependsOn: proguard) - -build.finalizedBy(createDist) - -install { - def jarApiName = String.format("%s-api-%s", rootProject.name, version.toString()) - def jarApiForgeName = String.format("%s-api-forge-%s", rootProject.name, version.toString()) - def jarSAName = String.format("%s-standalone-%s", rootProject.name, version.toString()) - def jarSAForgeName = String.format("%s-standalone-forge-%s", rootProject.name, version.toString()) - - artifacts { - archives file("$buildDir/libs/"+jarApiName+".jar") - archives file("$buildDir/libs/"+jarApiForgeName+".jar") - archives file("$buildDir/libs/"+jarSAName+".jar") - archives file("$buildDir/libs/"+jarSAForgeName+".jar") - } - repositories.mavenInstaller { - addFilter('api') { artifact, file -> artifact.name == "baritone-api" } - addFilter('api-forge') { artifact, file -> artifact.name == "baritone-api-forge" } - addFilter('standalone') { artifact, file -> artifact.name == "baritone-standalone" } - addFilter('standalone-forge') { artifact, file -> artifact.name == "baritone-standalone-forge" } - } -} - -install.dependsOn(build) +} \ No newline at end of file diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index 2ac49af0f..4ac65b03d 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -16,10 +16,24 @@ */ repositories { + maven { + name = 'WagYourMaven' + url = 'https://maven.wagyourtail.xyz/releases' + } + maven { + name = 'ForgeMaven' + url = 'https://maven.minecraftforge.net/' + } + maven { + name = 'FabricMaven' + url = 'https://maven.fabricmc.net/' + } mavenCentral() } dependencies { - compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5' - compile group: 'commons-io', name: 'commons-io', version: '2.6' + implementation group: 'com.google.code.gson', name: 'gson', version: '2.9.0' + implementation group: 'commons-io', name: 'commons-io', version: '2.6' + + implementation group: 'xyz.wagyourtail.unimined', name: 'xyz.wagyourtail.unimined.gradle.plugin', version: '0.4.9' } \ No newline at end of file diff --git a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java index 7e26dac11..2dad551f2 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/BaritoneGradleTask.java @@ -18,8 +18,12 @@ package baritone.gradle.task; import org.gradle.api.DefaultTask; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.Optional; +import org.gradle.api.tasks.TaskAction; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; @@ -39,38 +43,60 @@ class BaritoneGradleTask extends DefaultTask { PROGUARD_API_CONFIG = "api.pro", PROGUARD_STANDALONE_CONFIG = "standalone.pro", PROGUARD_EXPORT_PATH = "proguard_out.jar", + PROGUARD_MAPPING_DIR = "mapping", - TEMP_LIBRARY_DIR = "tempLibraries/", - - ARTIFACT_STANDARD = "%s-%s.jar", - ARTIFACT_UNOPTIMIZED = "%s-unoptimized-%s.jar", - ARTIFACT_API = "%s-api-%s.jar", - ARTIFACT_STANDALONE = "%s-standalone-%s.jar", - ARTIFACT_FORGE_API = "%s-api-forge-%s.jar", - ARTIFACT_FORGE_STANDALONE = "%s-standalone-forge-%s.jar"; + ARTIFACT_STANDARD = "%s-%s.jar", + ARTIFACT_UNOPTIMIZED = "%s-unoptimized-%s.jar", + ARTIFACT_API = "%s-api-%s.jar", + ARTIFACT_STANDALONE = "%s-standalone-%s.jar"; protected String artifactName, artifactVersion; - protected Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, artifactForgeApiPath, artifactForgeStandalonePath, proguardOut; + protected Path + artifactPath, + artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, // these are different for forge builds + proguardOut; - protected void verifyArtifacts() throws IllegalStateException { - this.artifactName = getProject().getName(); - this.artifactVersion = getProject().getVersion().toString(); - this.artifactPath = this.getBuildFile(formatVersion(ARTIFACT_STANDARD)); - this.artifactUnoptimizedPath = this.getBuildFile(formatVersion(ARTIFACT_UNOPTIMIZED)); - this.artifactApiPath = this.getBuildFile(formatVersion(ARTIFACT_API)); - this.artifactStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_STANDALONE)); - this.artifactForgeApiPath = this.getBuildFile(formatVersion(ARTIFACT_FORGE_API)); - this.artifactForgeStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_FORGE_STANDALONE)); + @Input + @Optional + protected String compType = null; + + public String getCompType() { + return compType; + } + + public void setCompType(String compType) { + this.compType = compType; + } + + + public BaritoneGradleTask() { + this.artifactName = getProject().getRootProject().getProperties().get("archives_base_name").toString(); + } + + public void doFirst() { + if (compType != null) { + this.artifactVersion = compType + "-" + getProject().getVersion(); + } else { + this.artifactVersion = getProject().getVersion().toString(); + } + + this.artifactPath = this.getBuildFile(formatVersion(ARTIFACT_STANDARD)); + + this.artifactUnoptimizedPath = this.getBuildFile(formatVersion(ARTIFACT_UNOPTIMIZED)); + this.artifactApiPath = this.getBuildFile(formatVersion(ARTIFACT_API)); + this.artifactStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_STANDALONE)); this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH); + } + protected void verifyArtifacts() throws IllegalStateException { if (!Files.exists(this.artifactPath)) { - throw new IllegalStateException("Artifact not found! Run build first!"); + throw new IllegalStateException("Artifact not found! Run build first! Missing file: " + this.artifactPath); } } - protected void write(InputStream stream, Path file) throws Exception { + protected void write(InputStream stream, Path file) throws IOException { if (Files.exists(file)) { Files.delete(file); } @@ -82,7 +108,11 @@ protected String formatVersion(String string) { } protected Path getRelativeFile(String file) { - return Paths.get(new File(file).getAbsolutePath()); + return Paths.get(new File(getProject().getBuildDir(), file).getAbsolutePath()); + } + + protected Path getRootRelativeFile(String file) { + return Paths.get(new File(getProject().getRootDir(), file).getAbsolutePath()); } protected Path getTemporaryFile(String file) { @@ -90,6 +120,10 @@ protected Path getTemporaryFile(String file) { } protected Path getBuildFile(String file) { - return getRelativeFile("build/libs/" + file); + return getRelativeFile("libs/" + file); + } + + protected String addCompTypeFirst(String string) { + return compType == null ? string : compType + "-" + string; } } diff --git a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java index 3ca935d16..48cd0a72a 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/CreateDistTask.java @@ -19,13 +19,15 @@ import org.gradle.api.tasks.TaskAction; -import javax.xml.bind.DatatypeConverter; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.OpenOption; import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.security.MessageDigest; +import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import java.util.stream.Stream; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; @@ -39,37 +41,40 @@ public class CreateDistTask extends BaritoneGradleTask { @TaskAction protected void exec() throws Exception { + super.doFirst(); super.verifyArtifacts(); // Define the distribution file paths - Path api = getRelativeFile("dist/" + formatVersion(ARTIFACT_API)); - Path standalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_STANDALONE)); - Path unoptimized = getRelativeFile("dist/" + formatVersion(ARTIFACT_UNOPTIMIZED)); - Path forgeApi = getRelativeFile("dist/" + formatVersion(ARTIFACT_FORGE_API)); - Path forgeStandalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_FORGE_STANDALONE)); + Path api = getRootRelativeFile("dist/" + getFileName(artifactApiPath)); + Path standalone = getRootRelativeFile("dist/" + getFileName(artifactStandalonePath)); + Path unoptimized = getRootRelativeFile("dist/" + getFileName(artifactUnoptimizedPath)); // NIO will not automatically create directories - Path dir = getRelativeFile("dist/"); + Path dir = getRootRelativeFile("dist/"); if (!Files.exists(dir)) { Files.createDirectory(dir); } // Copy build jars to dist/ - Files.copy(this.artifactApiPath, api, REPLACE_EXISTING); - Files.copy(this.artifactStandalonePath, standalone, REPLACE_EXISTING); - Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING); - Files.copy(this.artifactForgeApiPath, forgeApi, REPLACE_EXISTING); - Files.copy(this.artifactForgeStandalonePath, forgeStandalone, REPLACE_EXISTING); + // TODO: dont copy files that dont exist + Files.copy(this.artifactApiPath, api, REPLACE_EXISTING); + Files.copy(this.artifactStandalonePath, standalone, REPLACE_EXISTING); + Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING); // Calculate all checksums and format them like "shasum" - List shasum = Stream.of(api, forgeApi, standalone, forgeStandalone, unoptimized) + List shasum = Files.list(getRootRelativeFile("dist/")) + .filter(e -> e.getFileName().toString().endsWith(".jar")) .map(path -> sha1(path) + " " + path.getFileName().toString()) .collect(Collectors.toList()); shasum.forEach(System.out::println); // Write the checksums to a file - Files.write(getRelativeFile("dist/checksums.txt"), shasum); + Files.write(getRootRelativeFile("dist/checksums.txt"), shasum); + } + + private static String getFileName(Path p) { + return p.getFileName().toString(); } private static synchronized String sha1(Path path) { @@ -77,10 +82,22 @@ private static synchronized String sha1(Path path) { if (SHA1_DIGEST == null) { SHA1_DIGEST = MessageDigest.getInstance("SHA-1"); } - return DatatypeConverter.printHexBinary(SHA1_DIGEST.digest(Files.readAllBytes(path))).toLowerCase(); + return bytesToHex(SHA1_DIGEST.digest(Files.readAllBytes(path))).toLowerCase(); } catch (Exception e) { // haha no thanks throw new IllegalStateException(e); } } + + private static final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII); + + public static String bytesToHex(byte[] bytes) { + byte[] hexChars = new byte[bytes.length * 2]; + for (int j = 0; j < bytes.length; j++) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = HEX_ARRAY[v >>> 4]; + hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; + } + return new String(hexChars, StandardCharsets.UTF_8); + } } diff --git a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java index 1789435f7..30941d025 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java @@ -18,34 +18,27 @@ package baritone.gradle.task; import baritone.gradle.util.Determinizer; -import baritone.gradle.util.MappingType; -import baritone.gradle.util.ReobfWrapper; import org.apache.commons.io.IOUtils; import org.gradle.api.JavaVersion; -import org.gradle.api.NamedDomainObjectContainer; -import org.gradle.api.artifacts.Configuration; -import org.gradle.api.artifacts.Dependency; -import org.gradle.api.internal.file.IdentityFileResolver; -import org.gradle.api.internal.plugins.DefaultConvention; +import org.gradle.api.plugins.JavaPluginConvention; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.TaskCollection; import org.gradle.api.tasks.compile.ForkOptions; import org.gradle.api.tasks.compile.JavaCompile; -import org.gradle.internal.Pair; import org.gradle.internal.jvm.Jvm; -import org.gradle.internal.jvm.inspection.DefaultJvmVersionDetector; -import org.gradle.process.internal.DefaultExecActionFactory; +import xyz.wagyourtail.unimined.api.Constants; +import xyz.wagyourtail.unimined.api.minecraft.EnvType; +import xyz.wagyourtail.unimined.api.minecraft.MinecraftProvider; import java.io.*; -import java.lang.reflect.Field; +import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @@ -57,20 +50,23 @@ */ public class ProguardTask extends BaritoneGradleTask { - private static final Pattern TEMP_LIBRARY_PATTERN = Pattern.compile("-libraryjars 'tempLibraries\\/([a-zA-Z0-9/_\\-\\.]+)\\.jar'"); - @Input private String url; + public String getUrl() { + return url; + } + @Input private String extract; - private List requiredLibraries; - - private File mixin; + public String getExtract() { + return extract; + } @TaskAction protected void exec() throws Exception { + super.doFirst(); super.verifyArtifacts(); // "Haha brady why don't you make separate tasks" @@ -78,18 +74,27 @@ protected void exec() throws Exception { downloadProguard(); extractProguard(); generateConfigs(); - acquireDependencies(); proguardApi(); proguardStandalone(); cleanup(); } + MinecraftProvider provider = this.getProject().getExtensions().getByType(MinecraftProvider.class); + + private File getMcJar() { + return provider.getMinecraftWithMapping(EnvType.COMBINED, provider.getMcPatcher().getProdNamespace(), provider.getMcPatcher().getProdNamespace()).toFile(); + } + + private boolean isMcJar(File f) { + return this.getProject().getConfigurations().getByName(Constants.MINECRAFT_COMBINED_PROVIDER).getFiles().contains(f); + } + private void processArtifact() throws Exception { if (Files.exists(this.artifactUnoptimizedPath)) { Files.delete(this.artifactUnoptimizedPath); } - Determinizer.determinize(this.artifactPath.toString(), this.artifactUnoptimizedPath.toString(), Optional.empty()); + Determinizer.determinize(this.artifactPath.toString(), this.artifactUnoptimizedPath.toString()); } private void downloadProguard() throws Exception { @@ -192,197 +197,88 @@ public boolean accept(File dir, String name) { } private boolean validateJavaVersion(String java) { - final JavaVersion javaVersion = new DefaultJvmVersionDetector(new DefaultExecActionFactory(new IdentityFileResolver())).getJavaVersion(java); - - if (!javaVersion.getMajorVersion().equals("8")) { - System.out.println("Failed to validate Java version " + javaVersion.toString() + " [" + java + "] for ProGuard libraryjars"); - // throw new RuntimeException("Java version incorrect: " + javaVersion.getMajorVersion() + " for " + java); - return false; - } - - System.out.println("Validated Java version " + javaVersion.toString() + " [" + java + "] for ProGuard libraryjars"); + //TODO: fix for j16 +// final JavaVersion javaVersion = new DefaultJvmVersionDetector(new DefaultExecActionFactory(new IdentityFileResolver())).getJavaVersion(java); +// +// if (!javaVersion.getMajorVersion().equals("8")) { +// System.out.println("Failed to validate Java version " + javaVersion.toString() + " [" + java + "] for ProGuard libraryjars"); +// // throw new RuntimeException("Java version incorrect: " + javaVersion.getMajorVersion() + " for " + java); +// return false; +// } +// +// System.out.println("Validated Java version " + javaVersion.toString() + " [" + java + "] for ProGuard libraryjars"); return true; } private void generateConfigs() throws Exception { - Files.copy(getRelativeFile(PROGUARD_CONFIG_TEMPLATE), getTemporaryFile(PROGUARD_CONFIG_DEST), REPLACE_EXISTING); + Files.copy(getRootRelativeFile(PROGUARD_CONFIG_TEMPLATE), getTemporaryFile(PROGUARD_CONFIG_DEST), REPLACE_EXISTING); // Setup the template that will be used to derive the API and Standalone configs List template = Files.readAllLines(getTemporaryFile(PROGUARD_CONFIG_DEST)); template.add(0, "-injars '" + this.artifactPath.toString() + "'"); template.add(1, "-outjars '" + this.getTemporaryFile(PROGUARD_EXPORT_PATH) + "'"); - // Acquire the RT jar using "java -verbose". This doesn't work on Java 9+ - Process p = new ProcessBuilder(this.getJavaBinPathForProguard(), "-verbose").start(); - String out = IOUtils.toString(p.getInputStream(), "UTF-8").split("\n")[0].split("Opened ")[1].replace("]", ""); - template.add(2, "-libraryjars '" + out + "'"); - - // API config doesn't require any changes from the changes that we made to the template - Files.write(getTemporaryFile(PROGUARD_API_CONFIG), template); - - // For the Standalone config, don't keep the API package - List standalone = new ArrayList<>(template); - standalone.removeIf(s -> s.contains("# this is the keep api")); - Files.write(getTemporaryFile(PROGUARD_STANDALONE_CONFIG), standalone); - - // Discover all of the libraries that we will need to acquire from gradle - this.requiredLibraries = new ArrayList<>(); - template.forEach(line -> { - if (!line.startsWith("#")) { - Matcher m = TEMP_LIBRARY_PATTERN.matcher(line); - if (m.find()) { - this.requiredLibraries.add(m.group(1)); - } - } - }); - } - - private void acquireDependencies() throws Exception { - - // Create a map of all of the dependencies that we are able to access in this project - // Likely a better way to do this, I just pair the dependency with the first valid configuration - Map> dependencyLookupMap = new HashMap<>(); - getProject().getConfigurations().stream().filter(Configuration::isCanBeResolved).forEach(config -> - config.getAllDependencies().forEach(dependency -> - dependencyLookupMap.putIfAbsent(dependency.getName() + "-" + dependency.getVersion(), Pair.of(config, dependency)))); - - // Create the directory if it doesn't already exist - Path tempLibraries = getTemporaryFile(TEMP_LIBRARY_DIR); - if (!Files.exists(tempLibraries)) { - Files.createDirectory(tempLibraries); + if (JavaVersion.current().isJava9Compatible()) { + template.add(2, "-libraryjars /jmods/java.base.jmod(!**.jar;!module-info.class)"); + template.add(3, "-libraryjars /jmods/java.desktop.jmod(!**.jar;!module-info.class)"); + template.add(4, "-libraryjars /jmods/jdk.unsupported.jmod(!**.jar;!module-info.class)"); + template.add(5, "-libraryjars /jmods/java.compiler.jmod(!**.jar;!module-info.class)"); + } else { + template.add(2, "-libraryjars /lib/rt.jar"); } - // Iterate the required libraries to copy them to tempLibraries - for (String lib : this.requiredLibraries) { - // copy from the forgegradle cache - if (lib.equals("minecraft")) { - Path cachedJar = getMinecraftJar(); - Path inTempDir = getTemporaryFile("tempLibraries/minecraft.jar"); - // TODO: maybe try not to copy every time - Files.copy(cachedJar, inTempDir, REPLACE_EXISTING); - - continue; - } - - // Find a configuration/dependency pair that matches the desired library - Pair pair = null; - for (Map.Entry> entry : dependencyLookupMap.entrySet()) { - if (entry.getKey().startsWith(lib)) { - pair = entry.getValue(); - } + { + final Stream libraries; + File mcJar; + try { + mcJar = getMcJar(); + } catch (Exception e) { + throw new RuntimeException("Failed to find Minecraft jar", e); } - // The pair must be non-null - Objects.requireNonNull(pair); + { + // Discover all of the libraries that we will need to acquire from gradle + final Stream dependencies = acquireDependencies() + // remove MCP mapped jar, and nashorn + .filter(f -> !f.toString().endsWith("-recomp.jar") && !f.getName().startsWith("nashorn") && !f.getName().startsWith("coremods")); - // Find the library jar file, and copy it to tempLibraries - for (File file : pair.getLeft().files(pair.getRight())) { - if (file.getName().startsWith(lib)) { - if (lib.contains("mixin")) { - mixin = file; - } - Files.copy(file.toPath(), getTemporaryFile("tempLibraries/" + lib + ".jar"), REPLACE_EXISTING); - } + libraries = dependencies + .map(f -> isMcJar(f) ? mcJar : f); } - } - if (mixin == null) { - throw new IllegalStateException("Unable to find mixin jar"); - } - } - - // a bunch of epic stuff to get the path to the cached jar - private Path getMinecraftJar() throws Exception { - MappingType mappingType; - try { - mappingType = getMappingType(); - } catch (Exception e) { - System.err.println("Failed to get mapping type, assuming NOTCH."); - mappingType = MappingType.NOTCH; - } - - String suffix; - switch (mappingType) { - case NOTCH: - suffix = ""; - break; - case SEARGE: - suffix = "-srgBin"; - break; - case CUSTOM: - throw new IllegalStateException("Custom mappings not supported!"); - default: - throw new IllegalStateException("Unknown mapping type: " + mappingType); + libraries.forEach(f -> { + template.add(2, "-libraryjars '" + f + "'"); + }); } - DefaultConvention convention = (DefaultConvention) this.getProject().getConvention(); - Object extension = convention.getAsMap().get("minecraft"); - Objects.requireNonNull(extension); - - // for some reason cant use Class.forName - Class class_baseExtension = extension.getClass().getSuperclass().getSuperclass().getSuperclass(); // <-- cursed - Field f_replacer = class_baseExtension.getDeclaredField("replacer"); - f_replacer.setAccessible(true); - Object replacer = f_replacer.get(extension); - Class class_replacementProvider = replacer.getClass(); - Field replacement_replaceMap = class_replacementProvider.getDeclaredField("replaceMap"); - replacement_replaceMap.setAccessible(true); - - Map replacements = (Map) replacement_replaceMap.get(replacer); - String cacheDir = replacements.get("CACHE_DIR").toString() + "/net/minecraft"; - String mcVersion = replacements.get("MC_VERSION").toString(); - String mcpInsert = replacements.get("MAPPING_CHANNEL").toString() + "/" + replacements.get("MAPPING_VERSION").toString(); - String fullJarName = "minecraft-" + mcVersion + suffix + ".jar"; - - String baseDir = String.format("%s/minecraft/%s/", cacheDir, mcVersion); - - String jarPath; - if (mappingType == MappingType.SEARGE) { - jarPath = String.format("%s/%s/%s", baseDir, mcpInsert, fullJarName); - } else { - jarPath = baseDir + fullJarName; - } - jarPath = jarPath - .replace("/", File.separator) - .replace("\\", File.separator); // hecking regex + Files.createDirectories(this.getRootRelativeFile(PROGUARD_MAPPING_DIR)); - return new File(jarPath).toPath(); - } + List api = new ArrayList<>(template); + api.add(2, "-printmapping " + new File(this.getRootRelativeFile(PROGUARD_MAPPING_DIR).toFile(), "mappings-" + addCompTypeFirst("api.txt"))); - // throws IllegalStateException if mapping type is ambiguous or it fails to find it - private MappingType getMappingType() { - // if it fails to find this then its probably a forgegradle version problem - Set reobf = (NamedDomainObjectContainer) this.getProject().getExtensions().getByName("reobf"); - - List mappingTypes = getUsedMappingTypes(reobf); - long mappingTypesUsed = mappingTypes.size(); - if (mappingTypesUsed == 0) { - throw new IllegalStateException("Failed to find mapping type (no jar task?)"); - } - if (mappingTypesUsed > 1) { - throw new IllegalStateException("Ambiguous mapping type (multiple jars with different mapping types?)"); - } + // API config doesn't require any changes from the changes that we made to the template + Files.write(getTemporaryFile(compType+PROGUARD_API_CONFIG), api); - return mappingTypes.get(0); + // For the Standalone config, don't keep the API package + List standalone = new ArrayList<>(template); + standalone.removeIf(s -> s.contains("# this is the keep api")); + standalone.add(2, "-printmapping " + new File(this.getRootRelativeFile(PROGUARD_MAPPING_DIR).toFile(), "mappings-" + addCompTypeFirst("standalone.txt"))); + Files.write(getTemporaryFile(compType+PROGUARD_STANDALONE_CONFIG), standalone); } - private List getUsedMappingTypes(Set reobf) { - return reobf.stream() - .map(ReobfWrapper::new) - .map(ReobfWrapper::getMappingType) - .distinct() - .collect(Collectors.toList()); + private Stream acquireDependencies() { + return getProject().getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().findByName("main").getCompileClasspath().getFiles() + .stream() + .filter(File::isFile); } private void proguardApi() throws Exception { - runProguard(getTemporaryFile(PROGUARD_API_CONFIG)); - Determinizer.determinize(this.proguardOut.toString(), this.artifactApiPath.toString(), Optional.empty()); - Determinizer.determinize(this.proguardOut.toString(), this.artifactForgeApiPath.toString(), Optional.of(mixin)); + runProguard(getTemporaryFile(compType+PROGUARD_API_CONFIG)); + Determinizer.determinize(this.proguardOut.toString(), this.artifactApiPath.toString()); } private void proguardStandalone() throws Exception { - runProguard(getTemporaryFile(PROGUARD_STANDALONE_CONFIG)); - Determinizer.determinize(this.proguardOut.toString(), this.artifactStandalonePath.toString(), Optional.empty()); - Determinizer.determinize(this.proguardOut.toString(), this.artifactForgeStandalonePath.toString(), Optional.of(mixin)); + runProguard(getTemporaryFile(compType+PROGUARD_STANDALONE_CONFIG)); + Determinizer.determinize(this.proguardOut.toString(), this.artifactStandalonePath.toString()); } private void cleanup() { @@ -398,7 +294,6 @@ public void setUrl(String url) { public void setExtract(String extract) { this.extract = extract; } - private void runProguard(Path config) throws Exception { // Delete the existing proguard output file. Proguard probably handles this already, but why not do it ourselves if (Files.exists(this.proguardOut)) { @@ -412,7 +307,10 @@ private void runProguard(Path config) throws Exception { // Honestly, if you still have spaces in your path at this point, you're SOL. - Process p = new ProcessBuilder("java", "-jar", proguardJar.toString(), "@" + config.toString()) + // get the current java executable + String java = System.getProperty("java.home") + "/bin/java"; + + Process p = new ProcessBuilder(java, "-jar", proguardJar.toString(), "@" + config.toString()) .directory(workingDirectory.toFile()) // Set the working directory to the temporary folder] .start(); diff --git a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java index d9f475a5c..fc268cd35 100644 --- a/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java +++ b/buildSrc/src/main/java/baritone/gradle/util/Determinizer.java @@ -22,7 +22,10 @@ import com.google.gson.stream.JsonWriter; import java.io.*; -import java.util.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; @@ -36,7 +39,7 @@ */ public class Determinizer { - public static void determinize(String inputPath, String outputPath, Optional toInclude) throws IOException { + public static void determinize(String inputPath, String outputPath) throws IOException { System.out.println("Running Determinizer"); System.out.println(" Input path: " + inputPath); System.out.println(" Output path: " + outputPath); @@ -63,30 +66,10 @@ public static void determinize(String inputPath, String outputPath, Optional. + */ + +import baritone.gradle.task.CreateDistTask +import baritone.gradle.task.ProguardTask + +plugins { + id "com.github.johnrengelman.shadow" version "7.0.0" +} + +archivesBaseName = archivesBaseName + "-fabric" + +minecraft { + fabric { + devFallbackNamespace = "searge" + } +} + +mappings { + // fabric uses newer mixin... + // in reality, fields from this class should become constants at compile time + getStub("COMBINED").withMappings(["intermediary", "official"]) { + c("org.objectweb.asm.Opcodes", "org.spongepowered.asm.lib.Opcodes") + } +} + +configurations { + common + shadowCommon // Don't use shadow from the shadow plugin because we don't want IDEA to index this. + compileClasspath.extendsFrom common + runtimeClasspath.extendsFrom common +} + +repositories { + maven { + name = "Legacy Fabric" + url = "https://maven.legacyfabric.net/" + } +} + +dependencies { + fabric "net.fabricmc:fabric-loader:${project.fabric_version}" + + mappings "net.legacyfabric:intermediary:${rootProject.minecraft_version}:v2" + + // because of multiple sourcesets `common project(":")` doesn't work + for (sourceSet in rootProject.sourceSets) { + if (sourceSet == rootProject.sourceSets.test) continue + if (sourceSet == rootProject.sourceSets.schematica_api) continue + common sourceSet.output + shadowCommon sourceSet.output + } +} + +processResources { + inputs.property "version", project.version + + filesMatching("fabric.mod.json") { + expand "version": project.version + } +} + +shadowJar { + configurations = [project.configurations.shadowCommon] + classifier "dev-shadow" +} + +remapJar { + inputFile.set shadowJar.archiveFile + dependsOn shadowJar + classifier null +} + +jar { + classifier "dev" +} + +components.java { + withVariantsFromConfiguration(project.configurations.shadowRuntimeElements) { + skip() + } +} + +task proguard(type: ProguardTask) { + url 'https://github.com/Guardsquare/proguard/releases/download/v7.2.1/proguard-7.2.1.zip' + extract 'proguard-7.2.1/lib/proguard.jar' + compType "fabric" +} + +task createDist(type: CreateDistTask, dependsOn: proguard) { + compType "fabric" +} + +build.finalizedBy(createDist) + +publishing { + publications { + mavenFabric(MavenPublication) { + artifactId = rootProject.archives_base_name + "-" + project.name + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + } +} \ No newline at end of file diff --git a/fabric/src/main/resources/fabric.mod.json b/fabric/src/main/resources/fabric.mod.json new file mode 100644 index 000000000..94ec74b2f --- /dev/null +++ b/fabric/src/main/resources/fabric.mod.json @@ -0,0 +1,31 @@ + +{ + "schemaVersion": 1, + "id": "baritoe", + "version": "${version}", + + "name": "Baritone", + "description": "Google Maps for Blockgame", + "authors": [ + "leijurv", "Brady" + ], + "contact": { + "homepage": "https://github.com/cabaletta/baritone", + "sources": "https://github.com/cabaletta/baritone" + }, + + "license": "LGPL-3.0", + "icon": "assets/baritone/icon.png", + + "environment": "*", + "entrypoints": { + }, + "mixins": [ + "mixins.baritone.json" + ], + + "depends": { + "fabricloader": ">=0.11.0", + "minecraft": "1.12.2" + } +} \ No newline at end of file diff --git a/forge/build.gradle b/forge/build.gradle new file mode 100644 index 000000000..9010c4b8f --- /dev/null +++ b/forge/build.gradle @@ -0,0 +1,127 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +import baritone.gradle.task.CreateDistTask +import baritone.gradle.task.ProguardTask + +plugins { + id "com.github.johnrengelman.shadow" version "7.0.0" +} + +archivesBaseName = archivesBaseName + "-forge" + +minecraft { + forge { + mixinConfig = ["mixins.baritone.json"] + } + + launcher.client = { + args.addAll(["--tweakClass", "org.spongepowered.asm.launch.MixinTweaker"]) + } +} + +configurations { + common + shadowCommon // Don't use shadow from the shadow plugin because we don't want IDEA to index this. + compileClasspath.extendsFrom common + runtimeClasspath.extendsFrom common +} + +dependencies { + forge "net.minecraftforge:forge:${rootProject.forge_version}" + + implementation "org.spongepowered:mixin:0.7.11-SNAPSHOT", { + transitive = false + } + shadow "org.spongepowered:mixin:0.7.11-SNAPSHOT", { + transitive = false + } + + + // because of multiple sourcesets `common project(":")` doesn't work + for (sourceSet in rootProject.sourceSets) { + if (sourceSet == rootProject.sourceSets.test) continue + if (sourceSet == rootProject.sourceSets.schematica_api) continue + common sourceSet.output + shadowCommon sourceSet.output + } +} + +processResources { + inputs.property "version", project.version + + filesMatching("META-INF/mods.toml") { + expand "version": project.version + } +} + +shadowJar { + configurations = [project.configurations.shadowCommon, project.configurations.shadow] + classifier "dev-shadow" +} + +remapJar { + inputFile.set shadowJar.archiveFile + dependsOn shadowJar + classifier null +} + +jar { + classifier "dev" + + manifest { + attributes( + 'MixinConfigs': 'mixins.baritone.json', + 'TweakClass': 'org.spongepowered.asm.launch.MixinTweaker', + + 'Implementation-Title': 'Baritone', + 'Implementation-Version': version, + ) + } +} + +components.java { + withVariantsFromConfiguration(project.configurations.shadowRuntimeElements) { + skip() + } +} + +task proguard(type: ProguardTask) { + url 'https://github.com/Guardsquare/proguard/releases/download/v7.2.1/proguard-7.2.1.zip' + extract 'proguard-7.2.1/lib/proguard.jar' + compType "forge" +} + +task createDist(type: CreateDistTask, dependsOn: proguard) { + compType "forge" +} + +build.finalizedBy(createDist) + +publishing { + publications { + mavenFabric(MavenPublication) { + artifactId = rootProject.archives_base_name + "-" + project.name + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + } +} \ No newline at end of file diff --git a/forge/gradle.properties b/forge/gradle.properties new file mode 100644 index 000000000..24befc474 --- /dev/null +++ b/forge/gradle.properties @@ -0,0 +1,18 @@ +# +# This file is part of Baritone. +# +# Baritone is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Baritone is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with Baritone. If not, see . +# + +loom.platform=forge \ No newline at end of file diff --git a/forge/src/main/java/baritone/launch/BaritoneForgeModXD.java b/forge/src/main/java/baritone/launch/BaritoneForgeModXD.java new file mode 100644 index 000000000..54f5e3f28 --- /dev/null +++ b/forge/src/main/java/baritone/launch/BaritoneForgeModXD.java @@ -0,0 +1,22 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch;import net.minecraftforge.fml.common.Mod; + +@Mod(modid = "baritoe") +public class BaritoneForgeModXD { +} diff --git a/forge/src/main/resources/META-INF/mods.toml b/forge/src/main/resources/META-INF/mods.toml new file mode 100644 index 000000000..31c16a4bd --- /dev/null +++ b/forge/src/main/resources/META-INF/mods.toml @@ -0,0 +1,40 @@ +# This is an example mods.toml file. It contains the data relating to the loading mods. +# There are several mandatory fields (#mandatory), and many more that are optional (#optional). +# The overall format is standard TOML format, v0.5.0. +# Note that there are a couple of TOML lists in this file. +# Find more information on toml format here: https://github.com/toml-lang/toml +# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml +modLoader="javafml" #mandatory +# A version range to match for said mod loader - for regular FML @Mod it will be the forge version +loaderVersion="[33,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions. +license="https://raw.githubusercontent.com/cabaletta/baritone/1.16.2/LICENSE" +# A URL to refer people to when problems occur with this mod +issueTrackerURL="https://github.com/cabaletta/baritone/issues" #optional +# A list of mods - how many allowed here is determined by the individual mod loader +[[mods]] #mandatory +# The modid of the mod +modId="baritoe" #mandatory +# The version number of the mod - there's a few well known ${} variables useable here or just hardcode it +version="${version}" #mandatory + # A display name for the mod +displayName="Baritone" #mandatory +# A URL for the "homepage" for this mod, displayed in the mod UI +displayURL="https://github.com/cabaletta/baritone" #optional +# A file name (in the root of the mod JAR) containing a logo for display +#logoFile="examplemod.png" #optional +# A text field displayed in the mod UI +credits="Hat Gamers" #optional +# A text field displayed in the mod UI +authors="leijurv, Brady" #optional +# The description text for the mod (multi line!) (#mandatory) +description=''' +A Minecraft pathfinder bot. +''' + +[[dependencies.baritoe]] +modId="minecraft" +mandatory=true +# This version range declares a minimum of the current minecraft version up to but not including the next major version +versionRange="[1.12.2]" +ordering="NONE" +side="BOTH" \ No newline at end of file diff --git a/forge/src/main/resources/pack.mcmeta b/forge/src/main/resources/pack.mcmeta new file mode 100644 index 000000000..663d1787a --- /dev/null +++ b/forge/src/main/resources/pack.mcmeta @@ -0,0 +1,6 @@ +{ + "pack": { + "description": "null", + "pack_format": 8 + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 000000000..056708b19 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,13 @@ +org.gradle.jvmargs=-Xmx4G + +mod_version=1.2.17 +maven_group=baritone +archives_base_name=baritone + +mcp_channel=stable +mcp_version=39-1.12 + +minecraft_version=1.12.2 + +forge_version=1.12.2-14.23.5.2860 +fabric_version=0.14.12 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 4c5670a15..e708b1c02 100755 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 599a02b7a..00e33edef 100755 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Tue Jul 31 21:56:56 PDT 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 000000000..577b01763 --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,4 @@ +before_install: + - curl -s "https://get.sdkman.io" | bash + - sdk install java 17.0.5-tem + - sdk use java 17.0.5-tem diff --git a/scripts/proguard.pro b/scripts/proguard.pro index cc3130081..50118a16b 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -15,7 +15,16 @@ # lwjgl is weird -dontwarn org.lwjgl.** +# also lwjgl lol +-dontwarn module-info +# we dont have forge +-dontwarn baritone.launch.BaritoneForgeModXD +# to shade mixin on forge +-keep class org.spongepowered.** { *; } +-dontwarn org.spongepowered.** + +# please do not change the comment below -keep class baritone.api.** { *; } # this is the keep api # service provider needs these class names @@ -34,7 +43,7 @@ # setting names are reflected from field names, so keep field names -keepclassmembers class baritone.api.Settings { - public ; + public ; } # need to keep mixin names @@ -47,56 +56,6 @@ -dontwarn baritone.utils.schematic.schematica.** -dontwarn baritone.utils.schematic.litematica.** -# copy all necessary libraries into tempLibraries to build - -# The correct jar will be copied from the forgegradle cache based on the mapping type being compiled with --libraryjars 'tempLibraries/minecraft.jar' - --libraryjars 'tempLibraries/SimpleTweaker-1.2.jar' - --libraryjars 'tempLibraries/authlib-1.5.25.jar' --libraryjars 'tempLibraries/codecjorbis-20101023.jar' --libraryjars 'tempLibraries/codecwav-20101023.jar' --libraryjars 'tempLibraries/commons-codec-1.10.jar' --libraryjars 'tempLibraries/commons-compress-1.8.1.jar' --libraryjars 'tempLibraries/commons-io-2.5.jar' --libraryjars 'tempLibraries/commons-lang3-3.5.jar' --libraryjars 'tempLibraries/commons-logging-1.1.3.jar' --libraryjars 'tempLibraries/fastutil-7.1.0.jar' --libraryjars 'tempLibraries/gson-2.8.0.jar' --libraryjars 'tempLibraries/guava-21.0.jar' --libraryjars 'tempLibraries/httpclient-4.3.3.jar' --libraryjars 'tempLibraries/httpcore-4.3.2.jar' --libraryjars 'tempLibraries/icu4j-core-mojang-51.2.jar' --libraryjars 'tempLibraries/jinput-2.0.5.jar' --libraryjars 'tempLibraries/jna-4.4.0.jar' --libraryjars 'tempLibraries/jopt-simple-5.0.3.jar' --libraryjars 'tempLibraries/jsr305-3.0.1.jar' --libraryjars 'tempLibraries/jutils-1.0.0.jar' --libraryjars 'tempLibraries/libraryjavasound-20101123.jar' --libraryjars 'tempLibraries/librarylwjglopenal-20100824.jar' --libraryjars 'tempLibraries/log4j-api-2.8.1.jar' --libraryjars 'tempLibraries/log4j-core-2.8.1.jar' - -# startsWith is used to check the library, and mac/linux differ in which version they use -# this is FINE --libraryjars 'tempLibraries/lwjgl-.jar' --libraryjars 'tempLibraries/lwjgl_util-.jar' - --libraryjars 'tempLibraries/netty-all-4.1.9.Final.jar' --libraryjars 'tempLibraries/oshi-core-1.1.jar' --libraryjars 'tempLibraries/patchy-1.3.9.jar' --libraryjars 'tempLibraries/platform-3.4.0.jar' --libraryjars 'tempLibraries/realms-1.10.22.jar' --libraryjars 'tempLibraries/soundsystem-20120107.jar' --libraryjars 'tempLibraries/text2speech-1.10.3.jar' - --libraryjars 'tempLibraries/mixin-0.7.11-SNAPSHOT.jar' --libraryjars 'tempLibraries/launchwrapper-1.11.jar' # TODO why does only 1.11.jar exist? - - - - # Keep - Applications. Keep all application classes, along with their 'main' # methods. -keepclasseswithmembers public class * { @@ -384,6 +343,4 @@ public int length(); public java.lang.String substring(int); public java.lang.String substring(int,int); -} - --printmapping mapping.txt +} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index 567f84110..7809c35c6 100755 --- a/settings.gradle +++ b/settings.gradle @@ -15,5 +15,37 @@ * along with Baritone. If not, see . */ +pluginManagement { + repositories { + mavenLocal() + maven { + name = 'WagYourMaven' + url = 'https://maven.wagyourtail.xyz/snapshots' + } + maven { + name = 'ForgeMaven' + url = 'https://maven.minecraftforge.net/' + } + maven { + name = 'FabricMaven' + url = 'https://maven.fabricmc.net/' + } + mavenCentral() + gradlePluginPortal() { + content { + excludeGroup "org.apache.logging.log4j" + } + } + } +} + rootProject.name = 'baritone' +include("tweaker") +if (System.getProperty("Baritone.enabled_platforms") == null) { + System.setProperty("Baritone.enabled_platforms", "fabric,forge") +// System.setProperty("Baritone.enabled_platforms", "fabric") +} +for (platform in System.getProperty("Baritone.enabled_platforms").split(",")) { + include(platform) +} diff --git a/src/api/java/baritone/api/command/datatypes/EntityClassById.java b/src/api/java/baritone/api/command/datatypes/EntityClassById.java index c7ce2128d..a834622d5 100644 --- a/src/api/java/baritone/api/command/datatypes/EntityClassById.java +++ b/src/api/java/baritone/api/command/datatypes/EntityClassById.java @@ -30,19 +30,7 @@ public enum EntityClassById implements IDatatypeFor> { @Override public Class get(IDatatypeContext ctx) throws CommandException { - ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString()); - Class entity; - try { - entity = EntityList.REGISTRY.getObject(id); - } catch (NoSuchFieldError e) { - // Forge removes EntityList.REGISTRY field and provides the getClass method as a replacement - // See https://github.com/MinecraftForge/MinecraftForge/blob/1.12.x/patches/minecraft/net/minecraft/entity/EntityList.java.patch - try { - entity = (Class) EntityList.class.getMethod("getClass", ResourceLocation.class).invoke(null, id); - } catch (Exception ex) { - throw new RuntimeException("EntityList.REGISTRY does not exist and failed to call the Forge-replacement method", ex); - } - } + Class entity = EntityList.getClassFromName(ctx.getConsumer().getString()); if (entity == null) { throw new IllegalArgumentException("no entity found by that id"); diff --git a/src/main/java/baritone/utils/schematic/format/defaults/LitematicaSchematic.java b/src/main/java/baritone/utils/schematic/format/defaults/LitematicaSchematic.java index 7ff737ebc..b89d1b962 100644 --- a/src/main/java/baritone/utils/schematic/format/defaults/LitematicaSchematic.java +++ b/src/main/java/baritone/utils/schematic/format/defaults/LitematicaSchematic.java @@ -93,7 +93,7 @@ private static IBlockState[] getBlockList(NBTTagList blockStatePalette) { IBlockState[] blockList = new IBlockState[blockStatePalette.tagCount()]; for (int i = 0; i < blockStatePalette.tagCount(); i++) { - Block block = Block.REGISTRY.getObject(new ResourceLocation((((NBTTagCompound) blockStatePalette.get(i)).getString("Name")))); + Block block = Block.getBlockFromName(((NBTTagCompound) blockStatePalette.get(i)).getString("Name")); NBTTagCompound properties = ((NBTTagCompound) blockStatePalette.get(i)).getCompoundTag("Properties"); blockList[i] = getBlockState(block, properties); @@ -123,7 +123,7 @@ private static IBlockState getBlockState(Block block, NBTTagCompound properties) * @author Emerson */ private static > IBlockState setPropertyValue(IBlockState state, IProperty property, String value) { - Optional parsed = property.parseValue(value).toJavaUtil(); + Optional parsed = Optional.ofNullable(property.parseValue(value).orNull()); if (parsed.isPresent()) { return state.withProperty(property, parsed.get()); } else { diff --git a/src/main/java/baritone/utils/schematic/format/defaults/MCEditSchematic.java b/src/main/java/baritone/utils/schematic/format/defaults/MCEditSchematic.java index 08e571c96..7e2ce81af 100644 --- a/src/main/java/baritone/utils/schematic/format/defaults/MCEditSchematic.java +++ b/src/main/java/baritone/utils/schematic/format/defaults/MCEditSchematic.java @@ -59,7 +59,7 @@ public MCEditSchematic(NBTTagCompound schematic) { // additional is 0 through 15 inclusive since it's & 0xF above blockID |= additional[blockInd] << 8; } - Block block = Block.REGISTRY.getObjectById(blockID); + Block block = Block.getBlockById(blockID); int meta = metadata[blockInd] & 0xFF; this.states[x][z][y] = block.getStateFromMeta(meta); } diff --git a/src/main/java/baritone/utils/schematic/format/defaults/SpongeSchematic.java b/src/main/java/baritone/utils/schematic/format/defaults/SpongeSchematic.java index 8de038f5a..dedf62220 100644 --- a/src/main/java/baritone/utils/schematic/format/defaults/SpongeSchematic.java +++ b/src/main/java/baritone/utils/schematic/format/defaults/SpongeSchematic.java @@ -146,7 +146,7 @@ private static SerializedBlockState getFromString(String s) { } private static > IBlockState setPropertyValue(IBlockState state, IProperty property, String value) { - Optional parsed = property.parseValue(value).toJavaUtil(); + Optional parsed = Optional.ofNullable(property.parseValue(value).orNull()); if (parsed.isPresent()) { return state.withProperty(property, parsed.get()); } else { diff --git a/tweaker/build.gradle b/tweaker/build.gradle new file mode 100644 index 000000000..21e7ca045 --- /dev/null +++ b/tweaker/build.gradle @@ -0,0 +1,115 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +import baritone.gradle.task.CreateDistTask +import baritone.gradle.task.ProguardTask +//import baritone.gradle.task.TweakerJsonAssembler + +plugins { + id "com.github.johnrengelman.shadow" version "7.0.0" +} + +minecraft { + runs.client = { + mainClass = "net.minecraft.launchwrapper.Launch" + args.addAll(["--tweakClass", "baritone.launch.BaritoneTweaker"]) + } +} + +configurations { + common + shadowCommon // Don't use shadow from the shadow plugin because we don't want IDEA to index this. + compileClasspath.extendsFrom common + runtimeClasspath.extendsFrom common +} + +dependencies { + implementation "org.spongepowered:mixin:0.7.11-SNAPSHOT", { + transitive = false + } + + implementation "org.ow2.asm:asm:9.3" + implementation "org.ow2.asm:asm-tree:9.3" + implementation "org.ow2.asm:asm-commons:9.3" + implementation "org.ow2.asm:asm-util:9.3" + implementation "org.ow2.asm:asm-analysis:9.3" + + + implementation 'com.github.ImpactDevelopment:SimpleTweaker:1.2' + implementation('net.minecraft:launchwrapper:of-2.3') { + exclude module: 'lwjgl' + exclude module: 'asm-debug-all' + } + + // because of multiple sourcesets `common project(":")` doesn't work + for (sourceSet in rootProject.sourceSets) { + if (sourceSet == rootProject.sourceSets.test) continue + if (sourceSet == rootProject.sourceSets.schematica_api) continue + common sourceSet.output + shadowCommon sourceSet.output + } +} + +shadowJar { + configurations = [project.configurations.shadowCommon] + classifier "dev-shadow" +} + + +remapJar { + inputFile.set shadowJar.archiveFile + dependsOn shadowJar + classifier null +} + +jar { + classifier "dev" + + preserveFileTimestamps = false + reproducibleFileOrder = true + + manifest { + attributes( + 'MixinConfigs': 'mixins.baritone.json', + 'Implementation-Title': 'Baritone', + 'Implementation-Version': version, + ) + } +} + +task proguard(type: ProguardTask) { + url 'https://github.com/Guardsquare/proguard/releases/download/v7.2.1/proguard-7.2.1.zip' + extract 'proguard-7.2.1/lib/proguard.jar' +} + +task createDist(type: CreateDistTask, dependsOn: proguard) + +build.finalizedBy(createDist) + +publishing { + publications { + mavenCommon(MavenPublication) { + artifactId = rootProject.archives_base_name + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + } +} \ No newline at end of file diff --git a/src/launch/java/baritone/launch/BaritoneTweaker.java b/tweaker/src/main/java/baritone/launch/BaritoneTweaker.java similarity index 100% rename from src/launch/java/baritone/launch/BaritoneTweaker.java rename to tweaker/src/main/java/baritone/launch/BaritoneTweaker.java diff --git a/tweaker/src/main/java/baritone/launch/LaunchTesting.java b/tweaker/src/main/java/baritone/launch/LaunchTesting.java new file mode 100644 index 000000000..21607ae34 --- /dev/null +++ b/tweaker/src/main/java/baritone/launch/LaunchTesting.java @@ -0,0 +1,105 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.launch; + +import com.google.common.base.Strings; +import com.google.gson.GsonBuilder; +import com.mojang.authlib.Agent; +import com.mojang.authlib.exceptions.AuthenticationException; +import com.mojang.authlib.properties.PropertyMap; +import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; +import com.mojang.authlib.yggdrasil.YggdrasilUserAuthentication; +import net.minecraft.launchwrapper.Launch; + +import java.io.File; +import java.lang.reflect.Field; +import java.net.Proxy; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Based on GradleStart from ForgeGradle 2.3 + * + * @author Brady + * @since 3/11/2019 + */ +public class LaunchTesting { + + public static void main(String[] args) { + Map arguments = new HashMap<>(); + + hackNatives(); + arguments.put("version", "BaritownedDeveloperEnvironment"); + arguments.put("assetIndex", System.getenv("assetIndex")); + arguments.put("assetsDir", System.getenv().getOrDefault("assetDirectory", "assets")); + arguments.put("accessToken", "FML"); + arguments.put("userProperties", "{}"); + arguments.put("tweakClass", System.getenv("tweakClass")); + String password = System.getenv("password"); + if (password != null && !password.isEmpty()) { + attemptLogin(arguments, System.getenv("username"), System.getenv("password")); + } + + List argsArray = new ArrayList<>(); + arguments.forEach((k, v) -> { + argsArray.add("--" + k); + argsArray.add(v); + }); + + Launch.main(argsArray.toArray(new String[0])); + } + + private static void hackNatives() { + String paths = System.getProperty("java.library.path"); + String nativesDir = System.getenv().get("nativesDirectory"); + + if (Strings.isNullOrEmpty(paths)) + paths = nativesDir; + else + paths += File.pathSeparator + nativesDir; + + System.setProperty("java.library.path", paths); + + // hack the classloader now. + try { + final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths"); + sysPathsField.setAccessible(true); + sysPathsField.set(null, null); + } catch (Throwable ignored) {} + } + + private static void attemptLogin(Map argMap, String username, String password) { + YggdrasilUserAuthentication auth = (YggdrasilUserAuthentication) (new YggdrasilAuthenticationService(Proxy.NO_PROXY, "1")).createUserAuthentication(Agent.MINECRAFT); + auth.setUsername(username); + auth.setPassword(password); + + try { + auth.logIn(); + } catch (AuthenticationException var4) { + throw new RuntimeException(var4); + } + + argMap.put("accessToken", auth.getAuthenticatedToken()); + argMap.put("uuid", auth.getSelectedProfile().getId().toString().replace("-", "")); + argMap.put("username", auth.getSelectedProfile().getName()); + argMap.put("userType", auth.getUserType().getName()); + argMap.put("userProperties", (new GsonBuilder()).registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(auth.getUserProperties())); + } +}