Compare commits

...

72 Commits

Author SHA1 Message Date
leijurv
ec57888ce1 Merge pull request #4451 from ZacSharp/1.21-update
Merge 1.20.5 into 1.21
2024-08-22 10:58:20 -07:00
ZacSharp
8867fb7010 Merge branch '1.20.5' into 1.21 2024-08-02 00:45:15 +02:00
leijurv
acdcbf5146 Merge pull request #4439 from ZacSharp/1.20.5-update
Merge 1.19.4 into 1.20.5
2024-07-28 00:39:51 -07:00
ZacSharp
6b2fd5acee Merge branch '1.19.4' into 1.20.5 2024-07-21 13:02:03 +02:00
leijurv
8786148fef Merge pull request #4394 from rfresh2/1.21
1.21
2024-07-20 11:52:24 -07:00
leijurv
edb433ea6e Merge pull request #4432 from ZacSharp/pr/1.19.4/build/fixClassloaderExclusion
Move `BaritoneTweaker` to its own package
2024-07-20 11:50:23 -07:00
leijurv
a02704e097 Merge pull request #4430 from ZacSharp/pr/1.19.4/farm/addBamboo
Add bamboo to `FarmProcess` targets
2024-07-20 11:50:12 -07:00
rfresh2
e66fdea500 update supported litematic version 2024-07-19 13:37:16 -07:00
ZacSharp
1947459acf Move tweak class to its own package
Launchwrapper automatically adds a classloader exclusion for every package containing a tweak class, forcing the whole package to load through the parent class loader.
2024-07-14 13:47:52 +02:00
ZacSharp
52aa609ac7 Add bamboo to FarmProcess targets 2024-07-14 10:37:31 +02:00
rfresh2
74f46cd6eb 1.21 2024-06-20 01:03:15 -07:00
leijurv
1704d56274 Merge pull request #4396 from wagyourtail/1.20/1.20.5-(neo)forge
fix neoforge and forge for 1.20.5+
2024-06-19 18:20:49 -07:00
leijurv
92bc067633 Merge pull request #4395 from wagyourtail/1.19/proguard-cleanup
clean up proguard task
2024-06-19 18:20:08 -07:00
leijurv
64639b377f Merge pull request #4385 from ZacSharp/pr/1.19.4/farm/unhardcodeScanLimit
Unhardcode farm scan limit
2024-06-19 18:18:29 -07:00
Wagyourtail
81f7375591 fix mixin eating my try-catch 2024-06-17 00:26:34 -05:00
Wagyourtail
74d82f2339 fix neoforge and forge for 1.20.5+ 2024-06-17 00:11:11 -05:00
Wagyourtail
42c62a0559 clean up proguard task 2024-06-16 23:46:27 -05:00
ZacSharp
b25a6305ce Don't bother testing reachability for far away blocks
This is a massive performance improvement for big farms.
2024-06-09 18:14:41 +02:00
ZacSharp
98e90e72f7 Make farm scan limit configurable 2024-06-09 18:14:41 +02:00
ZacSharp
10851ddf14 Only create scan list when needed 2024-06-09 18:14:40 +02:00
ZacSharp
402079d7db Fail if there is no target position 2024-06-09 18:14:35 +02:00
leijurv
b184141db2 Merge pull request #4374 from ZacSharp/pr/1.19.4/guiclick/removeLogspam
Remove logspam from `GuiClick`
2024-06-07 00:45:33 -07:00
leijurv
42c6abbf72 Merge pull request #4347 from wagyourtail/1.20/1.20.5
1.20.5/6
2024-06-07 00:45:20 -07:00
William Gray
8bb19797e1 Update neoforge/src/main/resources/META-INF/neoforge.mods.toml
Co-authored-by: ZacSharp <68165024+ZacSharp@users.noreply.github.com>
2024-05-27 05:13:47 -06:00
ZacSharp
f9a8aa0c2b Remove logspam 2024-05-26 03:19:35 +02:00
Wagyourtail
6b274b3f1e just work already 2024-05-07 13:25:34 -05:00
Wagyourtail
f02c3115d1 update proguard 2024-05-07 13:19:12 -05:00
Wagyourtail
ee9ca6dd49 fix gradle version not supporting 21 2024-05-07 13:10:54 -05:00
Wagyourtail
8a5e3f7009 fix unfixable conflicts 2024-05-07 13:07:02 -05:00
Wagyourtail
b29878d0f2 fix neoforge version 2024-05-07 13:04:28 -05:00
Wagyourtail
19c8194eae re-enable lexforge 2024-05-07 13:02:58 -05:00
Wagyourtail
d8381c71fd rebuild loot tables 2024-05-07 13:00:32 -05:00
Wagyourtail
4b76fa995c java 21 2024-04-28 09:59:04 -05:00
Wagyourtail
088056b3d0 port to 1.20.5 2024-04-28 08:32:18 -05:00
leijurv
0c09441154 Merge pull request #4324 from ZacSharp/pr/1.19.4/setting/fixRecursiveParserType
Fix recursive setting parsers
2024-04-24 12:50:21 -07:00
leijurv
69d3bc0c2e Merge pull request #4320 from rfresh2/instabreak-fix
don't apply block break delay to insta-breaks
2024-04-24 12:50:06 -07:00
leijurv
1018db797e Merge pull request #4315 from ZacSharp/1.20.4-update
Merge 1.19.4 into 1.20.4
2024-04-24 12:49:27 -07:00
leijurv
b31e0a87cb Merge pull request #4333 from ZacSharp/pr/1.19.4/misc/toolset/fixHardnessCrash
Fix NPE in break time calculation
2024-04-24 12:49:15 -07:00
ZacSharp
4572b75db7 Fix NPE in break time calculation 2024-04-10 14:03:48 +02:00
rfresh2
15fdbb2312 revert API renaming 2024-04-07 20:30:16 -07:00
ZacSharp
848b7c6de0 Fix recursive parsers
Does not affect existing parsers since all nested parameterized setting types
are `Map<String, List<String>>` so there is no difference between the first
parameter of the inner type and the first parameter of the outer type
2024-04-02 21:32:01 +02:00
rfresh2
2b96a2e463 don't apply block break delay to insta-breaks 2024-04-01 15:21:24 -07:00
ZacSharp
354b26b1da Merge branch '1.19.4' into 1.20.4 2024-03-29 03:30:39 +01:00
leijurv
62b2f81ba1 Merge pull request #4314 from ZacSharp/pr/1.19.4/builder/fixBuildSkipBlocksNPE
Fix NPE
2024-03-28 19:25:58 -07:00
ZacSharp
5826931eea Fix NPE 2024-03-29 03:17:00 +01:00
leijurv
a8119366a1 Merge pull request #4292 from rfresh2/place-delay-patch
align rightClickSpeed setting with actual delay
2024-03-28 16:53:33 -07:00
leijurv
b0575fbe0c Merge pull request #4291 from rfresh2/block-break-delay
Block break delay setting
2024-03-28 16:53:13 -07:00
leijurv
866cf34f50 Merge pull request #4303 from ZacSharp/pr/1.19.4/builder/placeIncorrectBlockPenaltyMultiplier
Add a `placeIncorrectBlockPenaltyMultiplier` setting
2024-03-28 16:52:31 -07:00
leijurv
23908ad14f Merge pull request #4289 from ZacSharp/pr/1.19.4/ci/updateWorkflows
Update workflows
2024-03-28 16:51:43 -07:00
leijurv
6d06713610 Merge pull request #4280 from ZacSharp/1.20.4-update
Merge 1.19.4 into 1.20.4
2024-03-28 16:51:28 -07:00
rfresh2
18d3c4c2bd align rightClickSpeed setting with actual delay 2024-03-10 21:05:30 -07:00
rfresh2
faece77e8c align setting value with actual tick delay between breaks 2024-03-10 16:49:59 -07:00
rfresh2
413c11a23e block break delay setting 2024-03-09 15:26:18 -08:00
ZacSharp
4c9253fa5e Add placeIncorrectBlockPenaltyMultiplier builder setting 2024-03-08 17:49:51 +01:00
ZacSharp
d86a34a527 Fix too low bound and log spam 2024-03-08 17:49:45 +01:00
ZacSharp
92aba1b78e Update workflows 2024-03-06 02:26:58 +01:00
ZacSharp
28ba97c3de Move up and fix access modifiers 2024-02-22 14:16:52 +01:00
ZacSharp
24c23e28ec Reduce recursion limit and fix visibility 2024-02-20 21:35:59 +01:00
ZacSharp
2a2842361b Consistently use helper method
and make a safe cast unnecessary
2024-02-20 21:33:53 +01:00
ZacSharp
632e05c4c2 Make buildSkipBlocks use a wrapper schematic 2024-02-20 21:32:55 +01:00
ZacSharp
980d68536c Merge branch '1.19.4' into 1.20.4 2024-02-20 15:24:50 +01:00
leijurv
4144344acd Merge pull request #4251 from wagyourtail/1.19/fix/feather-crash
Fix feather crashing by catching error
2024-01-23 14:40:28 -08:00
leijurv
e962c39506 Merge pull request #4248 from ZacSharp/pr/1.19.4/mine/unhardcodeMaxOreLocations
Unhardcode `ORE_LOCATIONS_COUNT`
2024-01-23 14:40:02 -08:00
leijurv
48f309ac05 Merge pull request #4247 from ZacSharp/pr/1.19.4/elytra/removeUnsafeCast
Remove unsafe generic cast
2024-01-23 14:39:44 -08:00
leijurv
0688a57a38 Merge pull request #4252 from wagyourtail/1.19/fix/build-fail
fix 1.19 build failing
2024-01-23 11:04:14 -08:00
Wagyourtail
078b3909b3 fix build failing, by making nether pathfinder version consistent 2024-01-23 08:18:58 -07:00
Wagyourtail
d51b23bd1e Fix feather crashing by catching error 2024-01-22 10:39:12 -07:00
ZacSharp
9378f7e8a0 Unhardcode ORE_LOCATIONS_COUNT 2024-01-21 01:32:30 +01:00
ZacSharp
e7e434a95b Remove unsafe generic cast 2024-01-20 23:35:54 +01:00
leijurv
be1203fabb Merge pull request #4244 from wagyourtail/1.19/fix/null-elytra
fix 🪨🧠 preventing null elytra process from working
2024-01-20 08:50:31 -08:00
Wagyourtail
340d2a1d54 fix 🪨🧠 preventing null elytra process from working 2024-01-20 07:53:11 -07:00
leijurv
f84b749ff4 Update README.md 2024-01-06 12:21:52 -08:00
60 changed files with 727 additions and 548 deletions

View File

@@ -13,14 +13,14 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up JDK 17
uses: actions/setup-java@v3
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
java-version: '17'
java-version: '21'
distribution: 'temurin'
cache: gradle
@@ -31,13 +31,13 @@ jobs:
run: ./gradlew build -Pmod_version="$(git describe --always --tags --first-parent | cut -c2-)"
- name: Archive Artifacts
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: Artifacts
path: dist/
- name: Archive mapping.txt
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: Mappings
path: mapping/

View File

@@ -11,11 +11,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
- uses: actions/checkout@v4
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
java-version: '17'
java-version: '21'
distribution: 'temurin'
- name: Grant execute permission for gradlew

View File

@@ -63,11 +63,13 @@ Baritone is the pathfinding system used in [Impact](https://impactclient.net/) s
| [1.12.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.2.19/baritone-api-forge-1.2.19.jar) | |
| [1.16.5 Forge](https://github.com/cabaletta/baritone/releases/download/v1.6.5/baritone-api-forge-1.6.5.jar) | [1.16.5 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.6.5/baritone-api-fabric-1.6.5.jar) |
| [1.17.1 Forge](https://github.com/cabaletta/baritone/releases/download/v1.7.3/baritone-api-forge-1.7.3.jar) | [1.17.1 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.7.3/baritone-api-fabric-1.7.3.jar) |
| [1.18.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.8.5/baritone-api-forge-1.8.5.jar) | [1.18.2 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.8.5/baritone-api-fabric-1.8.5.jar) |
| [1.18.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.8.6/baritone-api-forge-1.8.6.jar) | [1.18.2 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.8.6/baritone-api-fabric-1.8.6.jar) |
| [1.19.2 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.4/baritone-api-forge-1.9.4.jar) | [1.19.2 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.4/baritone-api-fabric-1.9.4.jar) |
| [1.19.3 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-forge-1.9.1.jar) | [1.19.3 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.1/baritone-api-fabric-1.9.1.jar) |
| [1.19.4 Forge](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-forge-1.9.3.jar) | [1.19.4 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.9.3/baritone-api-fabric-1.9.3.jar) |
| [1.20.1 Forge](https://github.com/cabaletta/baritone/releases/download/v1.10.1/baritone-api-forge-1.10.1.jar) | [1.20.1 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.10.1/baritone-api-fabric-1.10.1.jar) |
| [1.20.3 Forge](https://github.com/cabaletta/baritone/releases/download/v1.10.2/baritone-api-forge-1.10.2.jar) | [1.20.3 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.10.2/baritone-api-fabric-1.10.2.jar) |
| [1.20.4 Forge](https://github.com/cabaletta/baritone/releases/download/v1.10.2/baritone-api-forge-1.10.2.jar) | [1.20.4 Fabric](https://github.com/cabaletta/baritone/releases/download/v1.10.2/baritone-api-fabric-1.10.2.jar) |
**Message for 2b2t players looking for 1.19/1.20 Baritone** If you like, please try the beta for Baritone Elytra for 2b2t, find it in #announcements of [the Baritone discord](http://discord.gg/s6fRBAUpmr). It supports 1.19.4 and 1.20.1, Forge or Fabric. If you have to see it to believe it, watch [this YouTube video](https://youtu.be/NnSlQi-68eQ).

View File

@@ -37,7 +37,13 @@ allprojects {
}
group = rootProject.maven_group
sourceCompatibility = targetCompatibility = JavaVersion.VERSION_17
sourceCompatibility = targetCompatibility = JavaVersion.toVersion(project.java_version)
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(sourceCompatibility.majorVersion.toInteger()))
}
}
repositories {
maven {
@@ -72,12 +78,12 @@ allprojects {
}
dependencies {
implementation "org.spongepowered:mixin:0.8.5"
implementation "org.ow2.asm:asm:9.3"
compileOnly "org.spongepowered:mixin:0.8"
compileOnly "org.ow2.asm:asm:9.7"
// The following line declares the yarn mappings you may select this one as well.
// mappings "net.fabricmc:yarn:1.17.1+build.32:v2"
//launchImplementation('dev.babbaj:nether-pathfinder:1.3.0')
implementation "dev.babbaj:nether-pathfinder:${nether_pathfinder_version}"
implementation "dev.babbaj:nether-pathfinder:${project.nether_pathfinder_version}"
implementation 'com.google.code.findbugs:jsr305:3.0.2'
}
@@ -88,14 +94,16 @@ allprojects {
mappings {
intermediary()
mojmap()
parchment("1.20.2", "2023.10.22")
parchment("1.20.6", "2024.05.01")
devFallbackNamespace "official"
}
}
tasks.withType(JavaCompile).configureEach {
it.options.encoding = "UTF-8"
def targetVersion = 17
def targetVersion = project.java_version.toInteger()
if (JavaVersion.current().isJava9Compatible()) {
it.options.release = targetVersion
}

View File

@@ -40,5 +40,5 @@ dependencies {
implementation group: 'com.google.code.gson', name: 'gson', version: '2.9.0'
implementation group: 'commons-io', name: 'commons-io', version: '2.7'
implementation group: 'xyz.wagyourtail.unimined', name: 'xyz.wagyourtail.unimined.gradle.plugin', version: '1.1.0'
implementation group: 'xyz.wagyourtail.unimined', name: 'xyz.wagyourtail.unimined.gradle.plugin', version: '1.2.9'
}

View File

@@ -36,8 +36,8 @@ import java.nio.file.Paths;
class BaritoneGradleTask extends DefaultTask {
protected static final String
PROGUARD_ZIP = "proguard.zip",
PROGUARD_JAR = "proguard.jar",
PROGUARD_ZIP = "proguard-%s.zip",
PROGUARD_JAR = "proguard-%s.jar",
PROGUARD_CONFIG_TEMPLATE = "scripts/proguard.pro",
PROGUARD_CONFIG_DEST = "template.pro",
PROGUARD_API_CONFIG = "api.pro",

View File

@@ -26,6 +26,9 @@ import org.gradle.api.tasks.TaskCollection;
import org.gradle.api.tasks.compile.ForkOptions;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.internal.jvm.Jvm;
import org.gradle.jvm.toolchain.JavaLanguageVersion;
import org.gradle.jvm.toolchain.JavaLauncher;
import org.gradle.jvm.toolchain.JavaToolchainService;
import xyz.wagyourtail.unimined.api.UniminedExtension;
import xyz.wagyourtail.unimined.api.minecraft.MinecraftConfig;
@@ -47,17 +50,10 @@ import java.util.zip.ZipFile;
public class ProguardTask extends BaritoneGradleTask {
@Input
private String url;
private String proguardVersion;
public String getUrl() {
return url;
}
@Input
private String extract;
public String getExtract() {
return extract;
public String getProguardVersion() {
return proguardVersion;
}
private List<String> requiredLibraries;
@@ -99,98 +95,33 @@ public class ProguardTask extends BaritoneGradleTask {
}
private void downloadProguard() throws Exception {
Path proguardZip = getTemporaryFile(PROGUARD_ZIP);
Path proguardZip = getTemporaryFile(String.format(PROGUARD_ZIP, proguardVersion));
if (!Files.exists(proguardZip)) {
write(new URL(this.url).openStream(), proguardZip);
write(new URL(String.format("https://github.com/Guardsquare/proguard/releases/download/v%s/proguard-%s.zip", proguardVersion, proguardVersion)).openStream(), proguardZip);
}
}
private void extractProguard() throws Exception {
Path proguardJar = getTemporaryFile(PROGUARD_JAR);
Path proguardJar = getTemporaryFile(String.format(PROGUARD_JAR, proguardVersion));
if (!Files.exists(proguardJar)) {
ZipFile zipFile = new ZipFile(getTemporaryFile(PROGUARD_ZIP).toFile());
ZipEntry zipJarEntry = zipFile.getEntry(this.extract);
ZipFile zipFile = new ZipFile(getTemporaryFile(String.format(PROGUARD_ZIP, proguardVersion)).toFile());
ZipEntry zipJarEntry = zipFile.getEntry(String.format("proguard-%s/lib/proguard.jar", proguardVersion));
write(zipFile.getInputStream(zipJarEntry), proguardJar);
zipFile.close();
}
}
private String getJavaBinPathForProguard() throws Exception {
String path;
try {
path = findJavaPathByGradleConfig();
if (path != null) return path;
} catch (Exception ex) {
System.err.println("Unable to find java by javaCompile options");
ex.printStackTrace();
private JavaLauncher getJavaLauncherForProguard() {
var toolchains = getProject().getExtensions().getByType(JavaToolchainService.class);
var toolchain = toolchains.launcherFor((spec) -> {
spec.getLanguageVersion().set(JavaLanguageVersion.of(getProject().findProperty("java_version").toString()));
}).getOrNull();
if (toolchain == null) {
throw new IllegalStateException("Java toolchain not found");
}
path = findJavaByGradleCurrentRuntime();
if (path != null) return path;
try {
path = findJavaByJavaHome();
if (path != null) return path;
} catch (Exception ex) {
System.err.println("Unable to find java by JAVA_HOME");
ex.printStackTrace();
}
throw new Exception("Unable to find java to determine ProGuard libraryjars. Please specify forkOptions.executable in javaCompile," +
" JAVA_HOME environment variable, or make sure to run Gradle with the correct JDK (a v1.8 only)");
}
private String findJavaByGradleCurrentRuntime() {
String path = Jvm.current().getJavaExecutable().getAbsolutePath();
System.out.println("Using Gradle's runtime Java for ProGuard");
return path;
}
private String findJavaByJavaHome() {
final String javaHomeEnv = System.getenv("JAVA_HOME");
if (javaHomeEnv != null) {
String path = Jvm.forHome(new File(javaHomeEnv)).getJavaExecutable().getAbsolutePath();
System.out.println("Detected Java path by JAVA_HOME");
return path;
}
return null;
}
private String findJavaPathByGradleConfig() {
final TaskCollection<JavaCompile> javaCompiles = super.getProject().getTasks().withType(JavaCompile.class);
final JavaCompile compileTask = javaCompiles.iterator().next();
final ForkOptions forkOptions = compileTask.getOptions().getForkOptions();
if (forkOptions != null) {
String javacPath = forkOptions.getExecutable();
if (javacPath != null) {
File javacFile = new File(javacPath);
if (javacFile.exists()) {
File[] maybeJava = javacFile.getParentFile().listFiles((dir, name) -> name.equals("java"));
if (maybeJava != null && maybeJava.length > 0) {
String path = maybeJava[0].getAbsolutePath();
System.out.println("Detected Java path by forkOptions");
return path;
}
}
}
}
return null;
}
private boolean validateJavaVersion(String java) {
//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;
return toolchain;
}
private void generateConfigs() throws Exception {
@@ -284,13 +215,8 @@ public class ProguardTask extends BaritoneGradleTask {
} catch (IOException ignored) {}
}
public void setUrl(String url) {
this.url = url;
}
public void setExtract(String extract) {
this.extract = extract;
public void setProguardVersion(String url) {
this.proguardVersion = url;
}
private void runProguard(Path config) throws Exception {
@@ -299,39 +225,15 @@ public class ProguardTask extends BaritoneGradleTask {
Files.delete(this.proguardOut);
}
// Make paths relative to work directory; fixes spaces in path to config, @"" doesn't work
Path workingDirectory = getTemporaryFile("");
Path proguardJar = workingDirectory.relativize(getTemporaryFile(PROGUARD_JAR));
config = workingDirectory.relativize(config);
// Honestly, if you still have spaces in your path at this point, you're SOL.
getProject().javaexec(spec -> {
spec.workingDir(workingDirectory.toFile());
spec.args("@" + workingDirectory.relativize(config));
spec.classpath(getTemporaryFile(String.format(PROGUARD_JAR, proguardVersion)));
Process p = new ProcessBuilder("java", "-jar", proguardJar.toString(), "@" + config.toString())
.directory(workingDirectory.toFile()) // Set the working directory to the temporary folder]
.start();
// We can't do output inherit process I/O with gradle for some reason and have it work, so we have to do this
this.printOutputLog(p.getInputStream(), System.out);
this.printOutputLog(p.getErrorStream(), System.err);
// Halt the current thread until the process is complete, if the exit code isn't 0, throw an exception
int exitCode = p.waitFor();
if (exitCode != 0) {
Thread.sleep(1000);
throw new IllegalStateException("Proguard exited with code " + exitCode);
}
spec.executable(getJavaLauncherForProguard().getExecutablePath().getAsFile());
}).assertNormalExitValue().rethrowFailure();
}
private void printOutputLog(InputStream stream, PrintStream outerr) {
new Thread(() -> {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
String line;
while ((line = reader.readLine()) != null) {
outerr.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}

View File

@@ -71,10 +71,10 @@ public class Determinizer {
ByteArrayOutputStream cancer = new ByteArrayOutputStream();
copy(jarFile.getInputStream(entry), cancer);
String manifest = new String(cancer.toByteArray());
if (!manifest.contains("baritone.launch.BaritoneTweaker")) {
if (!manifest.contains("baritone.launch.tweaker.BaritoneTweaker")) {
throw new IllegalStateException("unable to replace");
}
manifest = manifest.replace("baritone.launch.BaritoneTweaker", "org.spongepowered.asm.launch.MixinTweaker");
manifest = manifest.replace("baritone.launch.tweaker.BaritoneTweaker", "org.spongepowered.asm.launch.MixinTweaker");
jos.write(manifest.getBytes());
} else {
copy(jarFile.getInputStream(entry), jos);

View File

@@ -45,7 +45,7 @@ dependencies {
common sourceSet.output
shadowCommon sourceSet.output
}
include "dev.babbaj:nether-pathfinder:${nether_pathfinder_version}"
include "dev.babbaj:nether-pathfinder:${project.nether_pathfinder_version}"
}
processResources {
@@ -78,8 +78,7 @@ components.java {
}
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'
proguardVersion "7.4.2"
compType "fabric"
}

View File

@@ -25,6 +25,6 @@
"depends": {
"fabricloader": ">=0.14.22",
"minecraft": ["1.20.3", "1.20.4"]
"minecraft": "1.21"
}
}

View File

@@ -25,11 +25,7 @@ plugins {
archivesBaseName = archivesBaseName + "-forge"
unimined.minecraft {
mappings {
devFallbackNamespace "intermediary"
}
forge {
minecraftForge {
loader project.forge_version
mixinConfig ["mixins.baritone.json"]
}
@@ -56,7 +52,7 @@ dependencies {
common sourceSet.output
shadowCommon sourceSet.output
}
shadowCommon "dev.babbaj:nether-pathfinder:${nether_pathfinder_version}"
shadowCommon "dev.babbaj:nether-pathfinder:${project.nether_pathfinder_version}"
}
processResources {
@@ -99,8 +95,7 @@ components.java {
}
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'
proguardVersion "7.4.2"
compType "forge"
}

View File

@@ -35,6 +35,6 @@ A Minecraft pathfinder bot.
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.20.3, 1.20.4]"
versionRange="[1.21]"
ordering="NONE"
side="BOTH"

View File

@@ -2,15 +2,18 @@ org.gradle.jvmargs=-Xmx4G
available_loaders=fabric,forge,neoforge,tweaker
mod_version=1.10.2
mod_version=1.11.0
maven_group=baritone
archives_base_name=baritone
minecraft_version=1.20.4
java_version=21
forge_version=49.0.3
neoforge_version=0-beta
minecraft_version=1.21
fabric_version=0.14.22
forge_version=51.0.16
nether_pathfinder_version=1.4.1
neoforge_version=20-beta
fabric_version=0.15.11
nether_pathfinder_version=1.4.1

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -25,9 +25,6 @@ plugins {
archivesBaseName = archivesBaseName + "-neoforge"
unimined.minecraft {
mappings {
devFallbackNamespace "intermediary"
}
neoForged {
loader project.neoforge_version
@@ -65,13 +62,13 @@ dependencies {
common sourceSet.output
shadowCommon sourceSet.output
}
shadowCommon "dev.babbaj:nether-pathfinder:${nether_pathfinder_version}"
shadowCommon "dev.babbaj:nether-pathfinder:${project.nether_pathfinder_version}"
}
processResources {
inputs.property "version", project.version
filesMatching("META-INF/mods.toml") {
filesMatching("META-INF/neoforge.mods.toml") {
expand "version": project.version
}
}
@@ -108,8 +105,7 @@ components.java {
}
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'
proguardVersion "7.4.2"
compType "neoforge"
}
@@ -131,4 +127,4 @@ publishing {
repositories {
// Add repositories to publish to here.
}
}
}

View File

@@ -17,8 +17,9 @@
package baritone.launch;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.fml.common.Mod;
@Mod("baritoe")
@Mod(value = "baritoe", dist = Dist.CLIENT)
public class BaritoneForgeModXD {
}

View File

@@ -1,4 +1,4 @@
# This is an example mods.toml file. It contains the data relating to the loading mods.
# This is an example neoforge.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.
@@ -33,8 +33,8 @@ A Minecraft pathfinder bot.
[[dependencies.baritoe]]
modId="minecraft"
mandatory=true
type="required"
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="[1.20.3, 1.20.4]"
versionRange="[1.21]"
ordering="NONE"
side="BOTH"

View File

@@ -29,6 +29,8 @@ import net.minecraft.network.chat.Component;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.lang.annotation.ElementType;
@@ -50,6 +52,7 @@ import java.util.function.Consumer;
* @author leijurv
*/
public final class Settings {
private static final Logger LOGGER = LoggerFactory.getLogger("Baritone");
/**
* Allow Baritone to break blocks
@@ -382,6 +385,12 @@ public final class Settings {
*/
public final Setting<Float> blockReachDistance = new Setting<>(4.5f);
/**
* How many ticks between breaking a block and starting to break the next block. Default in game is 6 ticks.
* Values under 1 will be clamped. The delay only applies to non-instant (1-tick) breaks.
*/
public final Setting<Integer> blockBreakSpeed = new Setting<>(6);
/**
* How many degrees to randomize the pitch and yaw every tick. Set to 0 to disable
*/
@@ -900,6 +909,13 @@ public final class Settings {
*/
public final Setting<Integer> maxCachedWorldScanCount = new Setting<>(10);
/**
* Mine will not scan for or remember more than this many target locations.
* Note that the number of locations retrieved from cache is additionaly
* limited by {@link #maxCachedWorldScanCount}.
*/
public final Setting<Integer> mineMaxOreLocationsCount = new Setting<>(64);
/**
* Sets the minimum y level whilst mining - set to 0 to turn off.
* if world has negative y values, subtract the min world height to get the value to put here
@@ -957,6 +973,11 @@ public final class Settings {
*/
public final Setting<Boolean> replantNetherWart = new Setting<>(false);
/**
* Farming will scan for at most this many blocks.
*/
public final Setting<Integer> farmMaxScanSize = new Setting<>(256);
/**
* When the cache scan gives less blocks than the maximum threshold (but still above zero), scan the main world too.
* <p>
@@ -1048,6 +1069,11 @@ public final class Settings {
*/
public final Setting<Double> breakCorrectBlockPenaltyMultiplier = new Setting<>(10d);
/**
* Multiply the cost of placing a block that's incorrect in the builder's schematic by this coefficient
*/
public final Setting<Double> placeIncorrectBlockPenaltyMultiplier = new Setting<>(2d);
/**
* When this setting is true, build a schematic with the highest X coordinate being the origin, instead of the lowest
*/
@@ -1209,8 +1235,12 @@ public final class Settings {
*/
@JavaOnly
public final Setting<Consumer<Component>> logger = new Setting<>((msg) -> {
final GuiMessageTag tag = useMessageTag.value ? Helper.MESSAGE_TAG : null;
Minecraft.getInstance().gui.getChat().addMessage(msg, null, tag);
try {
final GuiMessageTag tag = useMessageTag.value ? Helper.MESSAGE_TAG : null;
Minecraft.getInstance().gui.getChat().addMessage(msg, null, tag);
} catch (Throwable t) {
LOGGER.warn("Failed to log message to chat: " + msg.getString(), t);
}
});
/**

View File

@@ -36,7 +36,7 @@ public enum BlockById implements IDatatypeFor<Block> {
@Override
public Block get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
ResourceLocation id = ResourceLocation.parse(ctx.getConsumer().getString());
Block block;
if ((block = BuiltInRegistries.BLOCK.getOptional(id).orElse(null)) == null) {
throw new IllegalArgumentException("no block found by that id");

View File

@@ -30,7 +30,7 @@ public enum EntityClassById implements IDatatypeFor<EntityType> {
@Override
public EntityType get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
ResourceLocation id = ResourceLocation.parse(ctx.getConsumer().getString());
EntityType entity;
if ((entity = BuiltInRegistries.ENTITY_TYPE.getOptional(id).orElse(null)) == null) {
throw new IllegalArgumentException("no entity found by that id");

View File

@@ -77,7 +77,7 @@ public enum ForBlockOptionalMeta implements IDatatypeFor<BlockOptionalMeta> {
properties = parts[1];
}
Block block = BuiltInRegistries.BLOCK.getOptional(new ResourceLocation(blockId)).orElse(null);
Block block = BuiltInRegistries.BLOCK.getOptional(ResourceLocation.parse(blockId)).orElse(null);
if (block == null) {
// This block doesn't exist so there's no properties to complete.
return Stream.empty();

View File

@@ -212,7 +212,7 @@ public class TabCompleteHelper {
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper filterPrefixNamespaced(String prefix) {
return filterPrefix(new ResourceLocation(prefix).toString());
return filterPrefix(ResourceLocation.parse(prefix).toString());
}
/**

View File

@@ -18,28 +18,38 @@
package baritone.api.utils;
import baritone.api.utils.accessor.IItemStack;
import baritone.api.utils.accessor.ILootTable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.netty.util.concurrent.ThreadPerTaskExecutor;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.commands.Commands;
import net.minecraft.core.LayeredRegistryAccess;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.ReloadableServerRegistries;
import net.minecraft.server.ReloadableServerResources;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.VanillaPackResources;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.CloseableResourceManager;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.server.packs.resources.ReloadableResourceManager;
import net.minecraft.util.Unit;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.world.RandomSequences;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.CustomSpawner;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.WorldDataConfiguration;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Property;
@@ -48,8 +58,8 @@ import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.ServerLevelData;
import net.minecraft.world.level.storage.loot.BuiltInLootTables;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootDataManager;
import net.minecraft.world.level.storage.loot.LootParams;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.phys.Vec3;
@@ -75,7 +85,6 @@ public final class BlockOptionalMeta {
private final Set<BlockState> blockstates;
private final ImmutableSet<Integer> stateHashes;
private final ImmutableSet<Integer> stackHashes;
private static LootDataManager lootTables;
private static Map<Block, List<Item>> drops = new HashMap<>();
public BlockOptionalMeta(@Nonnull Block block) {
@@ -218,43 +227,21 @@ public final class BlockOptionalMeta {
return null;
}
public static LootDataManager getManager() {
if (lootTables == null) {
MultiPackResourceManager resources = new MultiPackResourceManager(PackType.SERVER_DATA, List.of(getVanillaServerPack()));
ReloadableResourceManager resourceManager = new ReloadableResourceManager(PackType.SERVER_DATA);
lootTables = new LootDataManager();
resourceManager.registerReloadListener(lootTables);
try {
resourceManager.createReload(new ThreadPerTaskExecutor(Thread::new), new ThreadPerTaskExecutor(Thread::new), CompletableFuture.completedFuture(Unit.INSTANCE), resources.listPacks().toList()).done().get();
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
return lootTables;
}
private static synchronized List<Item> drops(Block b) {
return drops.computeIfAbsent(b, block -> {
ResourceLocation lootTableLocation = block.getLootTable();
if (lootTableLocation == BuiltInLootTables.EMPTY) {
ResourceLocation lootTableLocation = block.getLootTable().location();
if (lootTableLocation.equals(BuiltInLootTables.EMPTY.location())) {
return Collections.emptyList();
} else {
List<Item> items = new ArrayList<>();
try {
ServerLevel lv2 = ServerLevelStub.fastCreate();
getManager().getLootTable(lootTableLocation).getRandomItemsRaw(
new LootContext.Builder(
new LootParams.Builder(ServerLevelStub.fastCreate())
.withParameter(LootContextParams.ORIGIN, Vec3.atLowerCornerOf(BlockPos.ZERO))
.withParameter(LootContextParams.TOOL, ItemStack.EMPTY)
.withOptionalParameter(LootContextParams.BLOCK_ENTITY, null)
.withParameter(LootContextParams.BLOCK_STATE, block.defaultBlockState())
.create(LootContextParamSets.BLOCK)
).withOptionalRandomSeed(1L)
.create(null),
stack -> items.add(stack.getItem())
);
LootParams.Builder lv5 = new LootParams.Builder(lv2)
.withParameter(LootContextParams.ORIGIN, Vec3.ZERO)
.withParameter(LootContextParams.BLOCK_STATE, b.defaultBlockState())
.withParameter(LootContextParams.TOOL, new ItemStack(Items.NETHERITE_PICKAXE, 1));
getDrops(block, lv5).stream().map(ItemStack::getItem).forEach(items::add);
} catch (Exception e) {
e.printStackTrace();
}
@@ -263,9 +250,22 @@ public final class BlockOptionalMeta {
});
}
private static class ServerLevelStub extends ServerLevel {
private static List<ItemStack> getDrops(Block state, LootParams.Builder params) {
ResourceKey<LootTable> lv = state.getLootTable();
if (lv == BuiltInLootTables.EMPTY) {
return Collections.emptyList();
} else {
LootParams lv2 = params.withParameter(LootContextParams.BLOCK_STATE, state.defaultBlockState()).create(LootContextParamSets.BLOCK);
ServerLevelStub lv3 = (ServerLevelStub) lv2.getLevel();
LootTable lv4 = lv3.holder().getLootTable(lv);
return((ILootTable) lv4).invokeGetRandomItems(new LootContext.Builder(lv2).withOptionalRandomSeed(1).create(null));
}
}
public static class ServerLevelStub extends ServerLevel {
private static Minecraft client = Minecraft.getInstance();
private static Unsafe unsafe = getUnsafe();
private static CompletableFuture<RegistryAccess> registryAccess = load();
public ServerLevelStub(MinecraftServer $$0, Executor $$1, LevelStorageSource.LevelStorageAccess $$2, ServerLevelData $$3, ResourceKey<Level> $$4, LevelStem $$5, ChunkProgressListener $$6, boolean $$7, long $$8, List<CustomSpawner> $$9, boolean $$10, @Nullable RandomSequences $$11) {
super($$0, $$1, $$2, $$3, $$4, $$5, $$6, $$7, $$8, $$9, $$10, $$11);
@@ -285,6 +285,15 @@ public final class BlockOptionalMeta {
}
}
@Override
public RegistryAccess registryAccess() {
return registryAccess.join();
}
public ReloadableServerRegistries.Holder holder() {
return new ReloadableServerRegistries.Holder(registryAccess().freeze());
}
public static Unsafe getUnsafe() {
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
@@ -295,5 +304,42 @@ public final class BlockOptionalMeta {
}
}
public static CompletableFuture<RegistryAccess> load() {
PackRepository packRepository = Minecraft.getInstance().getResourcePackRepository();
CloseableResourceManager closeableResourceManager = new MultiPackResourceManager(PackType.SERVER_DATA, packRepository.openAllSelected());
LayeredRegistryAccess<RegistryLayer> layeredRegistryAccess = loadAndReplaceLayer(
closeableResourceManager, RegistryLayer.createRegistryAccess(), RegistryLayer.WORLDGEN, RegistryDataLoader.WORLDGEN_REGISTRIES
);
return ReloadableServerResources.loadResources(
closeableResourceManager,
layeredRegistryAccess,
WorldDataConfiguration.DEFAULT.enabledFeatures(),
Commands.CommandSelection.INTEGRATED,
2,
Runnable::run,
Minecraft.getInstance()
).thenApply(reloadableServerResources -> reloadableServerResources.fullRegistries().get());
}
private static LayeredRegistryAccess<RegistryLayer> loadAndReplaceLayer(
ResourceManager resourceManager,
LayeredRegistryAccess<RegistryLayer> registryAccess,
RegistryLayer registryLayer,
List<RegistryDataLoader.RegistryData<?>> registryData
) {
RegistryAccess.Frozen frozen = loadLayer(resourceManager, registryAccess, registryLayer, registryData);
return registryAccess.replaceFrom(registryLayer, frozen);
}
private static RegistryAccess.Frozen loadLayer(
ResourceManager resourceManager,
LayeredRegistryAccess<RegistryLayer> registryAccess,
RegistryLayer registryLayer,
List<RegistryDataLoader.RegistryData<?>> registryData
) {
RegistryAccess.Frozen frozen = registryAccess.getAccessForLoading(registryLayer);
return RegistryDataLoader.load(resourceManager, frozen, registryData);
}
}
}

View File

@@ -149,7 +149,7 @@ public class SettingsUtil {
throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting.getName());
}
return io.toString(new ParserContext(setting), value);
return io.toString(setting.getType(), value);
}
public static String settingValueToString(Settings.Setting setting) throws IllegalArgumentException {
@@ -196,7 +196,7 @@ public class SettingsUtil {
}
Class intendedType = setting.getValueClass();
ISettingParser ioMethod = Parser.getParser(setting.getType());
Object parsed = ioMethod.parse(new ParserContext(setting), settingValue);
Object parsed = ioMethod.parse(setting.getType(), settingValue);
if (!intendedType.isInstance(parsed)) {
throw new IllegalStateException(ioMethod + " parser returned incorrect type, expected " + intendedType + " got " + parsed + " which is " + parsed.getClass());
}
@@ -205,26 +205,13 @@ public class SettingsUtil {
private interface ISettingParser<T> {
T parse(ParserContext context, String raw);
T parse(Type type, String raw);
String toString(ParserContext context, T value);
String toString(Type type, T value);
boolean accepts(Type type);
}
private static class ParserContext {
private final Settings.Setting<?> setting;
private ParserContext(Settings.Setting<?> setting) {
this.setting = setting;
}
private Settings.Setting<?> getSetting() {
return this.setting;
}
}
private enum Parser implements ISettingParser {
DOUBLE(Double.class, Double::parseDouble),
@@ -251,26 +238,26 @@ public class SettingsUtil {
),
ITEM(
Item.class,
str -> BuiltInRegistries.ITEM.get(new ResourceLocation(str.trim())), // TODO this now returns AIR on failure instead of null, is that an issue?
str -> BuiltInRegistries.ITEM.get(ResourceLocation.parse(str.trim())), // TODO this now returns AIR on failure instead of null, is that an issue?
item -> BuiltInRegistries.ITEM.getKey(item).toString()
),
LIST() {
@Override
public Object parse(ParserContext context, String raw) {
Type type = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0];
Parser parser = Parser.getParser(type);
public Object parse(Type type, String raw) {
Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
Parser parser = Parser.getParser(elementType);
return Stream.of(raw.split(","))
.map(s -> parser.parse(context, s))
.map(s -> parser.parse(elementType, s))
.collect(Collectors.toList());
}
@Override
public String toString(ParserContext context, Object value) {
Type type = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0];
Parser parser = Parser.getParser(type);
public String toString(Type type, Object value) {
Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
Parser parser = Parser.getParser(elementType);
return ((List<?>) value).stream()
.map(o -> parser.toString(context, o))
.map(o -> parser.toString(elementType, o))
.collect(Collectors.joining(","));
}
@@ -281,26 +268,26 @@ public class SettingsUtil {
},
MAPPING() {
@Override
public Object parse(ParserContext context, String raw) {
Type keyType = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0];
Type valueType = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[1];
public Object parse(Type type, String raw) {
Type keyType = ((ParameterizedType) type).getActualTypeArguments()[0];
Type valueType = ((ParameterizedType) type).getActualTypeArguments()[1];
Parser keyParser = Parser.getParser(keyType);
Parser valueParser = Parser.getParser(valueType);
return Stream.of(raw.split(",(?=[^,]*->)"))
.map(s -> s.split("->"))
.collect(Collectors.toMap(s -> keyParser.parse(context, s[0]), s -> valueParser.parse(context, s[1])));
.collect(Collectors.toMap(s -> keyParser.parse(keyType, s[0]), s -> valueParser.parse(valueType, s[1])));
}
@Override
public String toString(ParserContext context, Object value) {
Type keyType = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[0];
Type valueType = ((ParameterizedType) context.getSetting().getType()).getActualTypeArguments()[1];
public String toString(Type type, Object value) {
Type keyType = ((ParameterizedType) type).getActualTypeArguments()[0];
Type valueType = ((ParameterizedType) type).getActualTypeArguments()[1];
Parser keyParser = Parser.getParser(keyType);
Parser valueParser = Parser.getParser(valueType);
return ((Map<?, ?>) value).entrySet().stream()
.map(o -> keyParser.toString(context, o.getKey()) + "->" + valueParser.toString(context, o.getValue()))
.map(o -> keyParser.toString(keyType, o.getKey()) + "->" + valueParser.toString(valueType, o.getValue()))
.collect(Collectors.joining(","));
}
@@ -331,14 +318,14 @@ public class SettingsUtil {
}
@Override
public Object parse(ParserContext context, String raw) {
public Object parse(Type type, String raw) {
Object parsed = this.parser.apply(raw);
Objects.requireNonNull(parsed);
return parsed;
}
@Override
public String toString(ParserContext context, Object value) {
public String toString(Type type, Object value) {
return this.toString.apply(value);
}

View File

@@ -0,0 +1,28 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.api.utils.accessor;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
public interface ILootTable {
ObjectArrayList<ItemStack> invokeGetRandomItems(LootContext context);
}

View File

@@ -47,7 +47,7 @@ public class BaritoneToast implements Toast {
//TODO: check
gui.blit(new ResourceLocation("textures/gui/toasts.png"), 0, 0, 0, 32, 160, 32);
gui.blit(ResourceLocation.parse("textures/gui/toasts.png"), 0, 0, 0, 32, 160, 32);
if (this.subtitle == null) {
gui.drawString(toastGui.getMinecraft().font, this.title, 18, 12, -11534256);

View File

@@ -27,17 +27,37 @@ import net.minecraft.client.KeyMapping;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.world.entity.player.Abilities;
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.Group;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
/**
* @author Brady
* @since 8/1/2018
*/
@Mixin(LocalPlayer.class)
public class MixinClientPlayerEntity {
@Unique
private static final MethodHandle MAY_FLY = baritone$resolveMayFly();
@Unique
private static MethodHandle baritone$resolveMayFly() {
try {
var lookup = MethodHandles.publicLookup();
return lookup.findVirtual(LocalPlayer.class, "mayFly", MethodType.methodType(boolean.class));
} catch (NoSuchMethodException e) {
return null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Inject(
method = "tick",
@@ -61,6 +81,7 @@ public class MixinClientPlayerEntity {
target = "net/minecraft/world/entity/player/Abilities.mayfly:Z"
)
)
@Group(name = "mayFly", min = 1, max = 1)
private boolean isAllowFlying(Abilities capabilities) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((LocalPlayer) (Object) this);
if (baritone == null) {
@@ -69,6 +90,22 @@ public class MixinClientPlayerEntity {
return !baritone.getPathingBehavior().isPathing() && capabilities.mayfly;
}
@Redirect(
method = "aiStep",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/client/player/LocalPlayer;mayFly()Z"
)
)
@Group(name = "mayFly", min = 1, max = 1)
private boolean onMayFlyNeoforge(LocalPlayer instance) throws Throwable {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((LocalPlayer) (Object) this);
if (baritone == null) {
return (boolean) MAY_FLY.invokeExact(instance);
}
return !baritone.getPathingBehavior().isPathing() && (boolean) MAY_FLY.invokeExact(instance);
}
@Redirect(
method = "aiStep",
at = @At(

View File

@@ -19,41 +19,28 @@ package baritone.launch.mixins;
import baritone.api.utils.BlockOptionalMeta;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.ReloadableServerRegistries;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootDataManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(LootContext.Builder.class)
public class MixinLootContext {
public abstract class MixinLootContextBuilder {
@Redirect(
method = "create",
at = @At(
value = "INVOKE",
target = "net/minecraft/server/level/ServerLevel.getServer()Lnet/minecraft/server/MinecraftServer;"
)
)
private MinecraftServer getServer(ServerLevel world) {
if (world == null) {
return null;
@Shadow public abstract ServerLevel getLevel();
@Redirect(method = "create", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;reloadableRegistries()Lnet/minecraft/server/ReloadableServerRegistries$Holder;"))
private ReloadableServerRegistries.Holder create(MinecraftServer instance) {
if (instance != null) {
return instance.reloadableRegistries();
}
return world.getServer();
if (getLevel() instanceof BlockOptionalMeta.ServerLevelStub sls) {
return sls.holder();
}
return null;
}
@Redirect(
method = "create",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/server/MinecraftServer;getLootData()Lnet/minecraft/world/level/storage/loot/LootDataManager;"
)
)
private LootDataManager getLootTableManager(MinecraftServer server) {
if (server == null) {
return BlockOptionalMeta.getManager();
}
return server.getLootData();
}
}

View File

@@ -0,0 +1,34 @@
/*
* 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 <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.api.utils.accessor.ILootTable;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootTable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(LootTable.class)
public abstract class MixinLootTable implements ILootTable {
@Invoker
public abstract ObjectArrayList<ItemStack> invokeGetRandomItems(LootContext context);
}

View File

@@ -24,6 +24,7 @@ import baritone.api.event.events.TickEvent;
import baritone.api.event.events.WorldEvent;
import baritone.api.event.events.type.EventState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.ReceivingLevelScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
@@ -130,7 +131,7 @@ public class MixinMinecraft {
method = "setLevel",
at = @At("HEAD")
)
private void preLoadWorld(ClientLevel world, CallbackInfo ci) {
private void preLoadWorld(ClientLevel world, ReceivingLevelScreen.Reason arg2, CallbackInfo ci) {
// If we're unloading the world but one doesn't exist, ignore it
if (this.level == null && world == null) {
return;
@@ -150,7 +151,7 @@ public class MixinMinecraft {
method = "setLevel",
at = @At("RETURN")
)
private void postLoadWorld(ClientLevel world, CallbackInfo ci) {
private void postLoadWorld(ClientLevel world, ReceivingLevelScreen.Reason arg2, CallbackInfo ci) {
// still fire event for both null, as that means we've just finished exiting a world
// mc.world changing is only the primary baritone

View File

@@ -31,6 +31,10 @@ public abstract class MixinPlayerController implements IPlayerControllerMP {
@Override
public abstract void setIsHittingBlock(boolean isHittingBlock);
@Accessor("isDestroying")
@Override
public abstract boolean isHittingBlock();
@Accessor("destroyBlockPos")
@Override
public abstract BlockPos getCurrentBlock();
@@ -38,4 +42,8 @@ public abstract class MixinPlayerController implements IPlayerControllerMP {
@Invoker("ensureHasSentCarriedItem")
@Override
public abstract void callSyncCurrentPlayItem();
@Accessor("destroyDelay")
@Override
public abstract void setDestroyDelay(int destroyDelay);
}

View File

@@ -35,11 +35,6 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(Screen.class)
public abstract class MixinScreen implements IGuiScreen {
@Override
@Invoker("openLink")
public abstract void openLinkInvoker(URI url);
//TODO: switch to enum extention with mixin 9.0 or whenever Mumfrey gets around to it
@Inject(at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;error(Ljava/lang/String;Ljava/lang/Object;)V", remap = false, ordinal = 1), method = "handleComponentClicked", cancellable = true)
public void handleCustomClickEvent(Style style, CallbackInfoReturnable<Boolean> cir) {

View File

@@ -22,6 +22,7 @@ import baritone.api.IBaritone;
import baritone.api.event.events.RenderEvent;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Camera;
import net.minecraft.client.DeltaTracker;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.LightTexture;
@@ -41,12 +42,13 @@ public class MixinWorldRenderer {
@Inject(
method = "renderLevel",
at = @At("RETURN"),
locals = LocalCapture.CAPTURE_FAILSOFT
at = @At("RETURN")
)
private void onStartHand(PoseStack matrixStackIn, float partialTicks, long finishTimeNano, boolean drawBlockOutline, Camera activeRenderInfoIn, GameRenderer gameRendererIn, LightTexture lightmapIn, Matrix4f projectionIn, CallbackInfo ci) {
private void onStartHand(final DeltaTracker deltaTracker, final boolean bl, final Camera camera, final GameRenderer gameRenderer, final LightTexture lightTexture, final Matrix4f matrix4f, final Matrix4f matrix4f2, final CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks, matrixStackIn, projectionIn));
PoseStack poseStack = new PoseStack();
poseStack.mulPose(matrix4f);
ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(deltaTracker.getGameTimeDeltaPartialTick(false), poseStack, matrix4f2));
}
}
}
}

View File

@@ -18,7 +18,8 @@
"MixinFireworkRocketEntity",
"MixinItemStack",
"MixinLivingEntity",
"MixinLootContext",
"MixinLootContextBuilder",
"MixinLootTable",
"MixinMinecraft",
"MixinNetworkManager",
"MixinPalettedContainer",
@@ -26,5 +27,7 @@
"MixinPlayerController",
"MixinScreen",
"MixinWorldRenderer"
],
"mixins": [
]
}

View File

@@ -79,7 +79,7 @@ public class Baritone implements IBaritone {
private final ExploreProcess exploreProcess;
private final FarmProcess farmProcess;
private final InventoryPauserProcess inventoryPauserProcess;
private final ElytraProcess elytraProcess;
private final IElytraProcess elytraProcess;
private final PathingControlManager pathingControlManager;
private final SelectionManager selectionManager;

View File

@@ -35,6 +35,7 @@ import baritone.command.argument.CommandArguments;
import baritone.command.manager.CommandManager;
import baritone.utils.accessor.IGuiScreen;
import net.minecraft.ChatFormatting;
import net.minecraft.Util;
import net.minecraft.network.chat.*;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.util.Tuple;
@@ -97,8 +98,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return false;
} else if (msg.trim().equalsIgnoreCase("orderpizza")) {
try {
((IGuiScreen) ctx.minecraft().screen).openLinkInvoker(new URI("https://www.dominos.com/en/pages/order/"));
} catch (NullPointerException | URISyntaxException ignored) {}
Util.getPlatform().openUri("https://www.dominos.com/en/pages/order/");
} catch (Exception ignored) {}
return false;
}
if (msg.isEmpty()) {

View File

@@ -42,6 +42,7 @@ import baritone.api.utils.BlockOptionalMetaLookup;
import baritone.utils.BlockStateInterface;
import baritone.utils.IRenderer;
import baritone.utils.schematic.StaticSchematic;
import com.mojang.blaze3d.vertex.BufferBuilder;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Vec3i;
@@ -75,9 +76,9 @@ public class SelCommand extends Command {
float opacity = Baritone.settings().selectionOpacity.value;
float lineWidth = Baritone.settings().selectionLineWidth.value;
boolean ignoreDepth = Baritone.settings().renderSelectionIgnoreDepth.value;
IRenderer.startLines(color, opacity, lineWidth, ignoreDepth);
IRenderer.emitAABB(event.getModelViewStack(), new AABB(pos1));
IRenderer.endLines(ignoreDepth);
BufferBuilder bufferBuilder = IRenderer.startLines(color, opacity, lineWidth, ignoreDepth);
IRenderer.emitAABB(bufferBuilder, event.getModelViewStack(), new AABB(pos1));
IRenderer.endLines(bufferBuilder, ignoreDepth);
}
});
}

View File

@@ -27,11 +27,14 @@ import baritone.utils.ToolSet;
import baritone.utils.pathing.BetterWorldBorder;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.item.enchantment.*;
import net.minecraft.world.item.enchantment.effects.EnchantmentAttributeEffect;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
@@ -108,19 +111,44 @@ public class CalculationContext {
this.allowParkourAscend = Baritone.settings().allowParkourAscend.value;
this.assumeWalkOnWater = Baritone.settings().assumeWalkOnWater.value;
this.allowFallIntoLava = false; // Super secret internal setting for ElytraBehavior
this.frostWalker = EnchantmentHelper.getEnchantmentLevel(Enchantments.FROST_WALKER, baritone.getPlayerContext().player());
// todo: technically there can now be datapack enchants that replace blocks with any other at any range
int frostWalkerLevel = 0;
for (EquipmentSlot slot : EquipmentSlot.values()) {
ItemEnchantments itemEnchantments = baritone.getPlayerContext()
.player()
.getItemBySlot(slot)
.getEnchantments();
for (Holder<Enchantment> enchant : itemEnchantments.keySet()) {
if (enchant.is(Enchantments.FROST_WALKER)) {
frostWalkerLevel = itemEnchantments.getLevel(enchant);
}
}
}
this.frostWalker = frostWalkerLevel;
this.allowDiagonalDescend = Baritone.settings().allowDiagonalDescend.value;
this.allowDiagonalAscend = Baritone.settings().allowDiagonalAscend.value;
this.allowDownward = Baritone.settings().allowDownward.value;
this.minFallHeight = 3; // Minimum fall height used by MovementFall
this.maxFallHeightNoWater = Baritone.settings().maxFallHeightNoWater.value;
this.maxFallHeightBucket = Baritone.settings().maxFallHeightBucket.value;
int depth = EnchantmentHelper.getDepthStrider(player);
if (depth > 3) {
depth = 3;
float waterSpeedMultiplier = 1.0f;
OUTER: for (EquipmentSlot slot : EquipmentSlot.values()) {
ItemEnchantments itemEnchantments = baritone.getPlayerContext()
.player()
.getItemBySlot(slot)
.getEnchantments();
for (Holder<Enchantment> enchant : itemEnchantments.keySet()) {
List<EnchantmentAttributeEffect> effects = enchant.value()
.getEffects(EnchantmentEffectComponents.ATTRIBUTES);
for (EnchantmentAttributeEffect effect : effects) {
if (effect.attribute().is(Attributes.WATER_MOVEMENT_EFFICIENCY.unwrapKey().get())) {
waterSpeedMultiplier = effect.amount().calculate(itemEnchantments.getLevel(enchant));
break OUTER;
}
}
}
}
float mult = depth / 3.0F;
this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - mult) + ActionCosts.WALK_ONE_BLOCK_COST * mult;
this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - waterSpeedMultiplier) + ActionCosts.WALK_ONE_BLOCK_COST * waterSpeedMultiplier;
this.breakBlockAdditionalCost = Baritone.settings().blockBreakAdditionalPenalty.value;
this.backtrackCostFavoringCoefficient = Baritone.settings().backtrackCostFavoringCoefficient.value;
this.jumpPenalty = Baritone.settings().jumpPenalty.value;

View File

@@ -31,7 +31,11 @@ import baritone.utils.BlockStateInterface;
import baritone.utils.ToolSet;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.core.Holder;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.item.enchantment.ItemEnchantments;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.piston.MovingPistonBlock;
import net.minecraft.world.level.block.state.BlockState;
@@ -177,15 +181,10 @@ public interface MovementHelper extends ActionCosts, Helper {
if (block instanceof CauldronBlock) {
return NO;
}
try { // A dodgy catch-all at the end, for most blocks with default behaviour this will work, however where blocks are special this will error out, and we can handle it when we have this information
if (state.isPathfindable(null, null, PathComputationType.LAND)) {
return YES;
} else {
return NO;
}
} catch (Throwable exception) {
System.out.println("The block " + state.getBlock().getName().getString() + " requires a special case due to the exception " + exception.getMessage());
return MAYBE;
if (state.isPathfindable(PathComputationType.LAND)) {
return YES;
} else {
return NO;
}
}
@@ -228,10 +227,7 @@ public interface MovementHelper extends ActionCosts, Helper {
return fluidState.getType() instanceof WaterFluid;
}
// every block that overrides isPassable with anything more complicated than a "return true;" or "return false;"
// has already been accounted for above
// therefore it's safe to not construct a blockpos from our x, y, z ints and instead just pass null
return state.isPathfindable(bsi.access, BlockPos.ZERO, PathComputationType.LAND); // workaround for future compatibility =P
return state.isPathfindable(PathComputationType.LAND);
}
static Ternary fullyPassableBlockState(BlockState state) {
@@ -259,16 +255,10 @@ public interface MovementHelper extends ActionCosts, Helper {
}
// door, fence gate, liquid, trapdoor have been accounted for, nothing else uses the world or pos parameters
// at least in 1.12.2 vanilla, that is.....
try { // A dodgy catch-all at the end, for most blocks with default behaviour this will work, however where blocks are special this will error out, and we can handle it when we have this information
if (state.isPathfindable(null, null, PathComputationType.LAND)) {
return YES;
} else {
return NO;
}
} catch (Throwable exception) {
// see PR #1087 for why
System.out.println("The block " + state.getBlock().getName().getString() + " requires a special case due to the exception " + exception.getMessage());
return MAYBE;
if (state.isPathfindable(PathComputationType.LAND)) {
return YES;
} else {
return NO;
}
}
@@ -293,11 +283,14 @@ public interface MovementHelper extends ActionCosts, Helper {
if (fullyPassable == NO) {
return false;
}
return fullyPassablePosition(new BlockStateInterface(ctx), pos.getX(), pos.getY(), pos.getZ(), state); // meh
return state.isPathfindable(PathComputationType.LAND);
}
/**
* params retained for backwards compatibility
*/
static boolean fullyPassablePosition(BlockStateInterface bsi, int x, int y, int z, BlockState state) {
return state.isPathfindable(bsi.access, bsi.isPassableBlockPos.set(x, y, z), PathComputationType.LAND);
return state.isPathfindable(PathComputationType.LAND);
}
static boolean isReplaceable(int x, int y, int z, BlockState state, BlockStateInterface bsi) {
@@ -511,14 +504,27 @@ public interface MovementHelper extends ActionCosts, Helper {
static boolean canUseFrostWalker(CalculationContext context, BlockState state) {
return context.frostWalker != 0
&& state == FrostedIceBlock.meltsInto()
&& ((Integer) state.getValue(LiquidBlock.LEVEL)) == 0;
&& state.getValue(LiquidBlock.LEVEL) == 0;
}
static boolean canUseFrostWalker(IPlayerContext ctx, BlockPos pos) {
boolean hasFrostWalker = false;
OUTER: for (EquipmentSlot slot : EquipmentSlot.values()) {
ItemEnchantments itemEnchantments = ctx
.player()
.getItemBySlot(slot)
.getEnchantments();
for (Holder<Enchantment> enchant : itemEnchantments.keySet()) {
if (enchant.is(Enchantments.FROST_WALKER)) {
hasFrostWalker = true;
break OUTER;
}
}
}
BlockState state = BlockStateInterface.get(ctx, pos);
return EnchantmentHelper.hasFrostWalker(ctx.player())
return hasFrostWalker
&& state == FrostedIceBlock.meltsInto()
&& ((Integer) state.getValue(LiquidBlock.LEVEL)) == 0;
&& state.getValue(LiquidBlock.LEVEL) == 0;
}
/**

View File

@@ -28,6 +28,7 @@ import baritone.api.process.PathingCommandType;
import baritone.api.schematic.FillSchematic;
import baritone.api.schematic.ISchematic;
import baritone.api.schematic.IStaticSchematic;
import baritone.api.schematic.MaskSchematic;
import baritone.api.schematic.SubstituteSchematic;
import baritone.api.schematic.format.ISchematicFormat;
import baritone.api.utils.*;
@@ -85,6 +86,14 @@ import static baritone.api.pathing.movement.ActionCosts.COST_INF;
public final class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess {
private static final Set<Property<?>> ORIENTATION_PROPS =
ImmutableSet.of(
RotatedPillarBlock.AXIS, HorizontalDirectionalBlock.FACING,
StairBlock.FACING, StairBlock.HALF, StairBlock.SHAPE,
PipeBlock.NORTH, PipeBlock.EAST, PipeBlock.SOUTH, PipeBlock.WEST, PipeBlock.UP,
TrapDoorBlock.OPEN, TrapDoorBlock.HALF
);
private HashSet<BetterBlockPos> incorrectPositions;
private LongOpenHashSet observedCompleted; // positions that are completed even if they're out of render distance and we can't make sure right now
private String name;
@@ -111,6 +120,14 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (!Baritone.settings().buildSubstitutes.value.isEmpty()) {
this.schematic = new SubstituteSchematic(this.schematic, Baritone.settings().buildSubstitutes.value);
}
// TODO this preserves the old behavior, but maybe we should bake the setting value right here
this.schematic = new MaskSchematic(this.schematic) {
@Override
public boolean partOfMask(int x, int y, int z, BlockState current) {
// partOfMask is only called inside the schematic so desiredState is not null
return !Baritone.settings().buildSkipBlocks.value.contains(this.desiredState(x, y, z, current, Collections.emptyList()).getBlock());
}
};
int x = origin.getX();
int y = origin.getY();
int z = origin.getZ();
@@ -169,15 +186,15 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (!format.isPresent()) {
return false;
}
ISchematic parsed;
IStaticSchematic parsed;
try {
parsed = format.get().parse(new FileInputStream(schematic));
} catch (Exception e) {
e.printStackTrace();
return false;
}
parsed = applyMapArtAndSelection(origin, (IStaticSchematic) parsed);
build(name, parsed, origin);
ISchematic schem = applyMapArtAndSelection(origin, parsed);
build(name, schem, origin);
return true;
}
@@ -197,17 +214,10 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (SchematicaHelper.isSchematicaPresent()) {
Optional<Tuple<IStaticSchematic, BlockPos>> schematic = SchematicaHelper.getOpenSchematic();
if (schematic.isPresent()) {
IStaticSchematic s = schematic.get().getA();
IStaticSchematic raw = schematic.get().getA();
BlockPos origin = schematic.get().getB();
ISchematic schem = Baritone.settings().mapArtMode.value ? new MapArtSchematic(s) : s;
if (Baritone.settings().buildOnlySelection.value) {
schem = new SelectionSchematic(schem, origin, baritone.getSelectionManager().getSelections());
}
this.build(
schematic.get().getA().toString(),
schem,
origin
);
ISchematic schem = applyMapArtAndSelection(origin, raw);
this.build(raw.toString(), schem, origin);
} else {
logDirect("No schematic currently open");
}
@@ -439,8 +449,8 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return onTick(calcFailed, isSafeToCancel, 0);
}
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel, int recursions) {
if (recursions > 1000) { // onTick calls itself, don't crash
private PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel, int recursions) {
if (recursions > 100) { // onTick calls itself, don't crash
return new PathingCommand(null, PathingCommandType.SET_GOAL_AND_PATH);
}
approxPlaceable = approxPlaceable(36);
@@ -684,8 +694,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
continue;
}
// this is not in render distance
if (!observedCompleted.contains(BetterBlockPos.longHash(blockX, blockY, blockZ))
&& !Baritone.settings().buildSkipBlocks.value.contains(schematic.desiredState(x, y, z, current, this.approxPlaceable).getBlock())) {
if (!observedCompleted.contains(BetterBlockPos.longHash(blockX, blockY, blockZ))) {
// and we've never seen this position be correct
// therefore mark as incorrect
incorrectPositions.add(new BetterBlockPos(blockX, blockY, blockZ));
@@ -1010,15 +1019,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return result;
}
public static final Set<Property<?>> orientationProps =
ImmutableSet.of(
RotatedPillarBlock.AXIS, HorizontalDirectionalBlock.FACING,
StairBlock.FACING, StairBlock.HALF, StairBlock.SHAPE,
PipeBlock.NORTH, PipeBlock.EAST, PipeBlock.SOUTH, PipeBlock.WEST, PipeBlock.UP,
TrapDoorBlock.OPEN, TrapDoorBlock.HALF
);
private boolean sameBlockstate(BlockState first, BlockState second) {
private static boolean sameBlockstate(BlockState first, BlockState second) {
if (first.getBlock() != second.getBlock()) {
return false;
}
@@ -1027,11 +1028,11 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (!ignoreDirection && ignoredProps.isEmpty()) {
return first.equals(second); // early return if no properties are being ignored
}
ImmutableMap<Property<?>, Comparable<?>> map1 = first.getValues();
ImmutableMap<Property<?>, Comparable<?>> map2 = second.getValues();
Map<Property<?>, Comparable<?>> map1 = first.getValues();
Map<Property<?>, Comparable<?>> map2 = second.getValues();
for (Property<?> prop : map1.keySet()) {
if (map1.get(prop) != map2.get(prop)
&& !(ignoreDirection && orientationProps.contains(prop))
&& !(ignoreDirection && ORIENTATION_PROPS.contains(prop))
&& !ignoredProps.contains(prop.getName())) {
return false;
}
@@ -1039,7 +1040,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return true;
}
private boolean containsBlockState(Collection<BlockState> states, BlockState state) {
private static boolean containsBlockState(Collection<BlockState> states, BlockState state) {
for (BlockState testee : states) {
if (sameBlockstate(testee, state)) {
return true;
@@ -1048,7 +1049,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return false;
}
private boolean valid(BlockState current, BlockState desired, boolean itemVerify) {
private static boolean valid(BlockState current, BlockState desired, boolean itemVerify) {
if (desired == null) {
return true;
}
@@ -1067,9 +1068,6 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (!(current.getBlock() instanceof AirBlock) && Baritone.settings().buildIgnoreExisting.value && !itemVerify) {
return true;
}
if (Baritone.settings().buildSkipBlocks.value.contains(desired.getBlock()) && !itemVerify) {
return true;
}
if (Baritone.settings().buildValidSubstitutes.value.getOrDefault(desired.getBlock(), Collections.emptyList()).contains(current.getBlock()) && !itemVerify) {
return true;
}
@@ -1113,12 +1111,12 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return COST_INF;
}
BlockState sch = getSchematic(x, y, z, current);
if (sch != null && !Baritone.settings().buildSkipBlocks.value.contains(sch.getBlock())) {
if (sch != null) {
// TODO this can return true even when allowPlace is off.... is that an issue?
if (sch.getBlock() instanceof AirBlock) {
// we want this to be air, but they're asking if they can place here
// this won't be a schematic block, this will be a throwaway
return placeBlockCost * 2; // we're going to have to break it eventually
return placeBlockCost * Baritone.settings().placeIncorrectBlockPenaltyMultiplier.value; // we're going to have to break it eventually
}
if (placeable.contains(sch)) {
return 0; // thats right we gonna make it FREE to place a block where it should go in a structure
@@ -1131,7 +1129,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
}
// we want it to be something that we don't have
// even more of a pain to place something wrong
return placeBlockCost * 3;
return placeBlockCost * 1.5 * Baritone.settings().placeIncorrectBlockPenaltyMultiplier.value;
} else {
if (hasThrowaway) {
return placeBlockCost;
@@ -1147,7 +1145,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return COST_INF;
}
BlockState sch = getSchematic(x, y, z, current);
if (sch != null && !Baritone.settings().buildSkipBlocks.value.contains(sch.getBlock())) {
if (sch != null) {
if (sch.getBlock() instanceof AirBlock) {
// it should be air
// regardless of current contents, we can break it

View File

@@ -84,10 +84,10 @@ public class ElytraProcess extends BaritoneProcessHelper implements IBaritonePro
baritone.getGameEventHandler().registerEventListener(this);
}
public static <T extends IElytraProcess> T create(final Baritone baritone) {
return (T) (NetherPathfinderContext.isSupported()
public static IElytraProcess create(final Baritone baritone) {
return NetherPathfinderContext.isSupported()
? new ElytraProcess(baritone)
: new NullElytraProcess(baritone));
: new NullElytraProcess(baritone);
}
@Override
@@ -360,7 +360,7 @@ public class ElytraProcess extends BaritoneProcessHelper implements IBaritonePro
private boolean shouldLandForSafety() {
ItemStack chest = ctx.player().getItemBySlot(EquipmentSlot.CHEST);
if (chest.getItem() != Items.ELYTRA || chest.getItem().getMaxDamage() - chest.getDamageValue() < Baritone.settings().elytraMinimumDurability.value) {
if (chest.getItem() != Items.ELYTRA || chest.getMaxDamage() - chest.getDamageValue() < Baritone.settings().elytraMinimumDurability.value) {
// elytrabehavior replaces when durability <= minimumDurability, so if durability < minimumDurability then we can reasonably assume that the elytra will soon be broken without replacement
return true;
}

View File

@@ -42,6 +42,7 @@ import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.AirBlock;
import net.minecraft.world.level.block.BambooStalkBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.BonemealableBlock;
@@ -95,6 +96,7 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
Items.NETHER_WART,
Items.COCOA_BEANS,
Blocks.SUGAR_CANE.asItem(),
Blocks.BAMBOO.asItem(),
Blocks.CACTUS.asItem()
);
@@ -137,6 +139,15 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
return true;
}
},
BAMBOO(Blocks.BAMBOO, null) {
@Override
public boolean readyToHarvest(Level world, BlockPos pos, BlockState state) {
if (Baritone.settings().replantCrops.value) {
return world.getBlockState(pos.below()).getBlock() instanceof BambooStalkBlock;
}
return true;
}
},
CACTUS(Blocks.CACTUS, null) {
@Override
public boolean readyToHarvest(Level world, BlockPos pos, BlockState state) {
@@ -191,20 +202,20 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
@Override
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
ArrayList<Block> scan = new ArrayList<>();
for (Harvest harvest : Harvest.values()) {
scan.add(harvest.block);
}
if (Baritone.settings().replantCrops.value) {
scan.add(Blocks.FARMLAND);
scan.add(Blocks.JUNGLE_LOG);
if (Baritone.settings().replantNetherWart.value) {
scan.add(Blocks.SOUL_SAND);
}
}
if (Baritone.settings().mineGoalUpdateInterval.value != 0 && tickCount++ % Baritone.settings().mineGoalUpdateInterval.value == 0) {
Baritone.getExecutor().execute(() -> locations = BaritoneAPI.getProvider().getWorldScanner().scanChunkRadius(ctx, scan, 256, 10, 10));
ArrayList<Block> scan = new ArrayList<>();
for (Harvest harvest : Harvest.values()) {
scan.add(harvest.block);
}
if (Baritone.settings().replantCrops.value) {
scan.add(Blocks.FARMLAND);
scan.add(Blocks.JUNGLE_LOG);
if (Baritone.settings().replantNetherWart.value) {
scan.add(Blocks.SOUL_SAND);
}
}
Baritone.getExecutor().execute(() -> locations = BaritoneAPI.getProvider().getWorldScanner().scanChunkRadius(ctx, scan, Baritone.settings().farmMaxScanSize.value, 10, 10));
}
if (locations == null) {
return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE);
@@ -256,7 +267,12 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
}
baritone.getInputOverrideHandler().clearAllKeys();
BetterBlockPos playerPos = ctx.playerFeet();
double blockReachDistance = ctx.playerController().getBlockReachDistance();
for (BlockPos pos : toBreak) {
if (playerPos.distSqr(pos) > blockReachDistance * blockReachDistance) {
continue;
}
Optional<Rotation> rot = RotationUtils.reachable(ctx, pos);
if (rot.isPresent() && isSafeToCancel) {
baritone.getLookBehavior().updateTarget(rot.get(), true);
@@ -270,10 +286,13 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
ArrayList<BlockPos> both = new ArrayList<>(openFarmland);
both.addAll(openSoulsand);
for (BlockPos pos : both) {
if (playerPos.distSqr(pos) > blockReachDistance * blockReachDistance) {
continue;
}
boolean soulsand = openSoulsand.contains(pos);
Optional<Rotation> rot = RotationUtils.reachableOffset(ctx, pos, new Vec3(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), ctx.playerController().getBlockReachDistance(), false);
Optional<Rotation> rot = RotationUtils.reachableOffset(ctx, pos, new Vec3(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), blockReachDistance, false);
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, soulsand ? this::isNetherWart : this::isPlantable)) {
HitResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance());
HitResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), blockReachDistance);
if (result instanceof BlockHitResult && ((BlockHitResult) result).getDirection() == Direction.UP) {
baritone.getLookBehavior().updateTarget(rot.get(), true);
if (ctx.isLookingAt(pos)) {
@@ -284,14 +303,17 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
}
}
for (BlockPos pos : openLog) {
if (playerPos.distSqr(pos) > blockReachDistance * blockReachDistance) {
continue;
}
for (Direction dir : Direction.Plane.HORIZONTAL) {
if (!(ctx.world().getBlockState(pos.relative(dir)).getBlock() instanceof AirBlock)) {
continue;
}
Vec3 faceCenter = Vec3.atCenterOf(pos).add(Vec3.atLowerCornerOf(dir.getNormal()).scale(0.5));
Optional<Rotation> rot = RotationUtils.reachableOffset(ctx, pos, faceCenter, ctx.playerController().getBlockReachDistance(), false);
Optional<Rotation> rot = RotationUtils.reachableOffset(ctx, pos, faceCenter, blockReachDistance, false);
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, this::isCocoa)) {
HitResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance());
HitResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), blockReachDistance);
if (result instanceof BlockHitResult && ((BlockHitResult) result).getDirection() == dir) {
baritone.getLookBehavior().updateTarget(rot.get(), true);
if (ctx.isLookingAt(pos)) {
@@ -303,6 +325,9 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
}
}
for (BlockPos pos : bonemealable) {
if (playerPos.distSqr(pos) > blockReachDistance * blockReachDistance) {
continue;
}
Optional<Rotation> rot = RotationUtils.reachable(ctx, pos);
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, this::isBoneMeal)) {
baritone.getLookBehavior().updateTarget(rot.get(), true);
@@ -359,6 +384,14 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
}
}
}
if (goalz.isEmpty()) {
logDirect("Farm failed");
if (Baritone.settings().notificationOnFarmFail.value) {
logNotification("Farm failed", true);
}
onLostControl();
return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE);
}
return new PathingCommand(new GoalComposite(goalz.toArray(new Goal[0])), PathingCommandType.SET_GOAL_AND_PATH);
}

View File

@@ -53,8 +53,6 @@ import static baritone.api.pathing.movement.ActionCosts.COST_INF;
*/
public final class MineProcess extends BaritoneProcessHelper implements IMineProcess {
private static final int ORE_LOCATIONS_COUNT = 64;
private BlockOptionalMetaLookup filter;
private List<BlockPos> knownOreLocations;
private List<BlockPos> blacklist; // inaccessible
@@ -186,7 +184,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
List<BlockPos> locs = knownOreLocations;
if (!locs.isEmpty()) {
CalculationContext context = new CalculationContext(baritone);
List<BlockPos> locs2 = prune(context, new ArrayList<>(locs), filter, ORE_LOCATIONS_COUNT, blacklist, droppedItemsScan());
List<BlockPos> locs2 = prune(context, new ArrayList<>(locs), filter, Baritone.settings().mineMaxOreLocationsCount.value, blacklist, droppedItemsScan());
// can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final
Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2, context)).toArray(Goal[]::new));
knownOreLocations = locs2;
@@ -235,7 +233,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
return;
}
List<BlockPos> dropped = droppedItemsScan();
List<BlockPos> locs = searchWorld(context, filter, ORE_LOCATIONS_COUNT, already, blacklist, dropped);
List<BlockPos> locs = searchWorld(context, filter, Baritone.settings().mineMaxOreLocationsCount.value, already, blacklist, dropped);
locs.addAll(dropped);
if (locs.isEmpty() && !Baritone.settings().exploreForBlocks.value) {
logDirect("No locations for " + filter + " known, cancelling");
@@ -425,7 +423,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
}
}
}
knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, filter, ORE_LOCATIONS_COUNT, blacklist, dropped);
knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, filter, Baritone.settings().mineMaxOreLocationsCount.value, blacklist, dropped);
return true;
}

View File

@@ -31,10 +31,12 @@ import baritone.utils.BlockStateInterface;
import baritone.utils.IRenderer;
import baritone.utils.PathRenderer;
import baritone.utils.accessor.IFireworkRocketEntity;
import com.mojang.blaze3d.vertex.BufferBuilder;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import it.unimi.dsi.fastutil.floats.FloatIterator;
import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList;
import net.minecraft.core.component.DataComponents;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
import net.minecraft.util.Mth;
@@ -44,6 +46,7 @@ import net.minecraft.world.entity.projectile.FireworkRocketEntity;
import net.minecraft.world.inventory.ClickType;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.component.Fireworks;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.block.AirBlock;
@@ -422,28 +425,28 @@ public final class ElytraBehavior implements Helper {
PathRenderer.drawGoal(event.getModelViewStack(), ctx, new GoalBlock(this.aimPos), event.getPartialTicks(), Color.GREEN);
}
if (!this.clearLines.isEmpty() && settings.elytraRenderRaytraces.value) {
IRenderer.startLines(Color.GREEN, settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
BufferBuilder bufferBuilder = IRenderer.startLines(Color.GREEN, settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
for (Pair<Vec3, Vec3> line : this.clearLines) {
IRenderer.emitLine(event.getModelViewStack(), line.first(), line.second());
IRenderer.emitLine(bufferBuilder, event.getModelViewStack(), line.first(), line.second());
}
IRenderer.endLines(settings.renderPathIgnoreDepth.value);
IRenderer.endLines(bufferBuilder, settings.renderPathIgnoreDepth.value);
}
if (!this.blockedLines.isEmpty() && Baritone.settings().elytraRenderRaytraces.value) {
IRenderer.startLines(Color.BLUE, settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
BufferBuilder bufferBuilder = IRenderer.startLines(Color.BLUE, settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
for (Pair<Vec3, Vec3> line : this.blockedLines) {
IRenderer.emitLine(event.getModelViewStack(), line.first(), line.second());
IRenderer.emitLine(bufferBuilder, event.getModelViewStack(), line.first(), line.second());
}
IRenderer.endLines(settings.renderPathIgnoreDepth.value);
IRenderer.endLines(bufferBuilder, settings.renderPathIgnoreDepth.value);
}
if (this.simulationLine != null && Baritone.settings().elytraRenderSimulation.value) {
IRenderer.startLines(new Color(0x36CCDC), settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
BufferBuilder bufferBuilder = IRenderer.startLines(new Color(0x36CCDC), settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
final Vec3 offset = ctx.player().getPosition(event.getPartialTicks());
for (int i = 0; i < this.simulationLine.size() - 1; i++) {
final Vec3 src = this.simulationLine.get(i).add(offset);
final Vec3 dst = this.simulationLine.get(i + 1).add(offset);
IRenderer.emitLine(event.getModelViewStack(), src, dst);
IRenderer.emitLine(bufferBuilder, event.getModelViewStack(), src, dst);
}
IRenderer.endLines(settings.renderPathIgnoreDepth.value);
IRenderer.endLines(bufferBuilder, settings.renderPathIgnoreDepth.value);
}
}
@@ -922,9 +925,8 @@ public final class ElytraBehavior implements Helper {
if (itemStack.getItem() != Items.FIREWORK_ROCKET) {
return false;
}
// If it has NBT data, make sure it won't cause us to explode.
final CompoundTag compound = itemStack.getTagElement("Fireworks");
return compound == null || !compound.getAllKeys().contains("Explosions");
Fireworks fw = itemStack.get(DataComponents.FIREWORKS);
return fw != null && fw.explosions().isEmpty();
}
private static boolean isBoostingFireworks(final ItemStack itemStack) {
@@ -932,11 +934,9 @@ public final class ElytraBehavior implements Helper {
}
private static OptionalInt getFireworkBoost(final ItemStack itemStack) {
if (isFireworks(itemStack)) {
final CompoundTag compound = itemStack.getTagElement("Fireworks");
if (compound != null && compound.getAllKeys().contains("Flight")) {
return OptionalInt.of(compound.getByte("Flight"));
}
Fireworks fw = itemStack.get(DataComponents.FIREWORKS);
if (fw != null && fw.explosions().isEmpty()) {
return OptionalInt.of(fw.flightDuration());
}
return OptionalInt.empty();
}
@@ -1292,7 +1292,7 @@ public final class ElytraBehavior implements Helper {
NonNullList<ItemStack> invy = ctx.player().getInventory().items;
for (int i = 0; i < invy.size(); i++) {
ItemStack slot = invy.get(i);
if (slot.getItem() == Items.ELYTRA && (slot.getItem().getMaxDamage() - slot.getDamageValue()) > Baritone.settings().elytraMinimumDurability.value) {
if (slot.getItem() == Items.ELYTRA && (slot.getMaxDamage() - slot.getDamageValue()) > Baritone.settings().elytraMinimumDurability.value) {
return i;
}
}
@@ -1306,7 +1306,7 @@ public final class ElytraBehavior implements Helper {
ItemStack chest = ctx.player().getItemBySlot(EquipmentSlot.CHEST);
if (chest.getItem() != Items.ELYTRA
|| chest.getItem().getMaxDamage() - chest.getDamageValue() > Baritone.settings().elytraMinimumDurability.value) {
|| chest.getMaxDamage() - chest.getDamageValue() > Baritone.settings().elytraMinimumDurability.value) {
return;
}

View File

@@ -5,6 +5,7 @@ import baritone.api.event.events.RenderEvent;
import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.selection.ISelection;
import baritone.utils.IRenderer;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.world.phys.AABB;
@@ -28,27 +29,27 @@ public class SelectionRenderer implements IRenderer, AbstractGameEventListener {
return;
}
IRenderer.startLines(settings.colorSelection.value, opacity, lineWidth, ignoreDepth);
BufferBuilder bufferBuilder = IRenderer.startLines(settings.colorSelection.value, opacity, lineWidth, ignoreDepth);
for (ISelection selection : selections) {
IRenderer.emitAABB(stack, selection.aabb(), SELECTION_BOX_EXPANSION);
IRenderer.emitAABB(bufferBuilder, stack, selection.aabb(), SELECTION_BOX_EXPANSION);
}
if (settings.renderSelectionCorners.value) {
IRenderer.glColor(settings.colorSelectionPos1.value, opacity);
for (ISelection selection : selections) {
IRenderer.emitAABB(stack, new AABB(selection.pos1()));
IRenderer.emitAABB(bufferBuilder, stack, new AABB(selection.pos1()));
}
IRenderer.glColor(settings.colorSelectionPos2.value, opacity);
for (ISelection selection : selections) {
IRenderer.emitAABB(stack, new AABB(selection.pos2()));
IRenderer.emitAABB(bufferBuilder, stack, new AABB(selection.pos2()));
}
}
IRenderer.endLines(ignoreDepth);
IRenderer.endLines(bufferBuilder, ignoreDepth);
}
@Override

View File

@@ -17,7 +17,9 @@
package baritone.utils;
import baritone.api.BaritoneAPI;
import baritone.api.utils.IPlayerContext;
import baritone.utils.accessor.IPlayerControllerMP;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
@@ -27,9 +29,12 @@ import net.minecraft.world.phys.HitResult;
* @since 8/25/2018
*/
public final class BlockBreakHelper {
// base ticks between block breaks caused by tick logic
private static final int BASE_BREAK_DELAY = 1;
private final IPlayerContext ctx;
private boolean didBreakLastTick;
private boolean wasHitting;
private int breakDelayTimer = 0;
BlockBreakHelper(IPlayerContext ctx) {
this.ctx = ctx;
@@ -37,38 +42,46 @@ public final class BlockBreakHelper {
public void stopBreakingBlock() {
// The player controller will never be null, but the player can be
if (ctx.player() != null && didBreakLastTick) {
if (!ctx.playerController().hasBrokenBlock()) {
// insane bypass to check breaking succeeded
ctx.playerController().setHittingBlock(true);
}
if (ctx.player() != null && wasHitting) {
ctx.playerController().setHittingBlock(false);
ctx.playerController().resetBlockRemoving();
didBreakLastTick = false;
wasHitting = false;
}
}
public void tick(boolean isLeftClick) {
if (breakDelayTimer > 0) {
breakDelayTimer--;
return;
}
HitResult trace = ctx.objectMouseOver();
boolean isBlockTrace = trace != null && trace.getType() == HitResult.Type.BLOCK;
if (isLeftClick && isBlockTrace) {
if (!didBreakLastTick) {
ctx.playerController().setHittingBlock(wasHitting);
if (ctx.playerController().hasBrokenBlock()) {
ctx.playerController().syncHeldItem();
ctx.playerController().clickBlock(((BlockHitResult) trace).getBlockPos(), ((BlockHitResult) trace).getDirection());
ctx.player().swing(InteractionHand.MAIN_HAND);
} else {
if (ctx.playerController().onPlayerDamageBlock(((BlockHitResult) trace).getBlockPos(), ((BlockHitResult) trace).getDirection())) {
ctx.player().swing(InteractionHand.MAIN_HAND);
}
if (ctx.playerController().hasBrokenBlock()) { // block broken this tick
// break delay timer only applies for multi-tick block breaks like vanilla
breakDelayTimer = BaritoneAPI.getSettings().blockBreakSpeed.value - BASE_BREAK_DELAY;
// must reset controller's destroy delay to prevent the client from delaying itself unnecessarily
((IPlayerControllerMP) ctx.minecraft().gameMode).setDestroyDelay(0);
}
}
// Attempt to break the block
if (ctx.playerController().onPlayerDamageBlock(((BlockHitResult) trace).getBlockPos(), ((BlockHitResult) trace).getDirection())) {
ctx.player().swing(InteractionHand.MAIN_HAND);
}
// if true, we're breaking a block. if false, we broke the block this tick
wasHitting = !ctx.playerController().hasBrokenBlock();
// this value will be reset by the MC client handling mouse keys
// since we're not spoofing the click keybind to the client, the client will stop the break if isDestroyingBlock is true
// we store and restore this value on the next tick to determine if we're breaking a block
ctx.playerController().setHittingBlock(false);
didBreakLastTick = true;
} else if (didBreakLastTick) {
stopBreakingBlock();
didBreakLastTick = false;
} else {
wasHitting = false;
}
}
}

View File

@@ -25,6 +25,8 @@ import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
public class BlockPlaceHelper {
// base ticks between places caused by tick logic
private static final int BASE_PLACE_DELAY = 1;
private final IPlayerContext ctx;
private int rightClickTimer;
@@ -42,7 +44,7 @@ public class BlockPlaceHelper {
if (!rightClickRequested || ctx.player().isHandsBusy() || mouseOver == null || mouseOver.getType() != HitResult.Type.BLOCK) {
return;
}
rightClickTimer = Baritone.settings().rightClickSpeed.value;
rightClickTimer = Baritone.settings().rightClickSpeed.value - BASE_PLACE_DELAY;
for (InteractionHand hand : InteractionHand.values()) {
if (ctx.playerController().processRightClickBlock(ctx.player(), ctx.world(), hand, (BlockHitResult) mouseOver) == InteractionResult.SUCCESS) {
ctx.player().swing(hand);

View File

@@ -30,9 +30,9 @@ import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.status.ChunkStatus;
/**
* Wraps get for chuck caching capability

View File

@@ -22,6 +22,7 @@ import baritone.api.BaritoneAPI;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.Helper;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.GuiGraphics;
@@ -74,13 +75,11 @@ public class GuiClick extends Screen implements Helper {
Vec3 far = toWorld(mx, my, 1); // "Use 0.945 that's what stack overflow says" - leijurv
if (near != null && far != null) {
///
Vec3 viewerPos = new Vec3(PathRenderer.posX(), PathRenderer.posY(), PathRenderer.posZ());
LocalPlayer player = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().player();
HitResult result = player.level().clip(new ClipContext(near.add(viewerPos), far.add(viewerPos), ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, player));
if (result != null && result.getType() == HitResult.Type.BLOCK) {
currentMouseOver = ((BlockHitResult) result).getBlockPos();
System.out.println("currentMouseOver = " + currentMouseOver);
}
}
}
@@ -128,11 +127,11 @@ public class GuiClick extends Screen implements Helper {
// drawSingleSelectionBox WHEN?
PathRenderer.drawManySelectionBoxes(modelViewStack, e, Collections.singletonList(currentMouseOver), Color.CYAN);
if (clickStart != null && !clickStart.equals(currentMouseOver)) {
IRenderer.startLines(Color.RED, Baritone.settings().pathRenderLineWidthPixels.value, true);
BufferBuilder bufferBuilder = IRenderer.startLines(Color.RED, Baritone.settings().pathRenderLineWidthPixels.value, true);
BetterBlockPos a = new BetterBlockPos(currentMouseOver);
BetterBlockPos b = new BetterBlockPos(clickStart);
IRenderer.emitAABB(modelViewStack, new AABB(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z), Math.max(a.x, b.x) + 1, Math.max(a.y, b.y) + 1, Math.max(a.z, b.z) + 1));
IRenderer.endLines(true);
IRenderer.emitAABB(bufferBuilder, modelViewStack, new AABB(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z), Math.max(a.x, b.x) + 1, Math.max(a.y, b.y) + 1, Math.max(a.z, b.z) + 1));
IRenderer.endLines(bufferBuilder, true);
}
}
}

View File

@@ -28,15 +28,12 @@ import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import org.joml.Matrix3f;
import org.joml.Matrix4f;
import java.awt.*;
public interface IRenderer {
Tesselator tessellator = Tesselator.getInstance();
BufferBuilder buffer = tessellator.getBuilder();
IEntityRenderManager renderManager = (IEntityRenderManager) Minecraft.getInstance().getEntityRenderDispatcher();
TextureManager textureManager = Minecraft.getInstance().getTextureManager();
Settings settings = BaritoneAPI.getSettings();
@@ -51,7 +48,7 @@ public interface IRenderer {
IRenderer.color[3] = alpha;
}
static void startLines(Color color, float alpha, float lineWidth, boolean ignoreDepth) {
static BufferBuilder startLines(Color color, float alpha, float lineWidth, boolean ignoreDepth) {
RenderSystem.enableBlend();
RenderSystem.setShader(GameRenderer::getPositionColorShader);
RenderSystem.blendFuncSeparate(
@@ -69,15 +66,19 @@ public interface IRenderer {
RenderSystem.disableDepthTest();
}
RenderSystem.setShader(GameRenderer::getRendertypeLinesShader);
buffer.begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL);
return tessellator.begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL);
}
static void startLines(Color color, float lineWidth, boolean ignoreDepth) {
startLines(color, .4f, lineWidth, ignoreDepth);
static BufferBuilder startLines(Color color, float lineWidth, boolean ignoreDepth) {
return startLines(color, .4f, lineWidth, ignoreDepth);
}
static void endLines(boolean ignoredDepth) {
tessellator.end();
static void endLines(BufferBuilder bufferBuilder, boolean ignoredDepth) {
MeshData meshData = bufferBuilder.build();
if (meshData != null) {
BufferUploader.drawWithShader(meshData);
}
if (ignoredDepth) {
RenderSystem.enableDepthTest();
}
@@ -87,7 +88,7 @@ public interface IRenderer {
RenderSystem.disableBlend();
}
static void emitLine(PoseStack stack, double x1, double y1, double z1, double x2, double y2, double z2) {
static void emitLine(BufferBuilder bufferBuilder, PoseStack stack, double x1, double y1, double z1, double x2, double y2, double z2) {
final double dx = x2 - x1;
final double dy = y2 - y1;
final double dz = z2 - z1;
@@ -97,60 +98,59 @@ public interface IRenderer {
final float ny = (float) (dy * invMag);
final float nz = (float) (dz * invMag);
emitLine(stack, x1, y1, z1, x2, y2, z2, nx, ny, nz);
emitLine(bufferBuilder, stack, x1, y1, z1, x2, y2, z2, nx, ny, nz);
}
static void emitLine(PoseStack stack,
static void emitLine(BufferBuilder bufferBuilder, PoseStack stack,
double x1, double y1, double z1,
double x2, double y2, double z2,
double nx, double ny, double nz) {
emitLine(stack,
emitLine(bufferBuilder, stack,
(float) x1, (float) y1, (float) z1,
(float) x2, (float) y2, (float) z2,
(float) nx, (float) ny, (float) nz
);
}
static void emitLine(PoseStack stack,
static void emitLine(BufferBuilder bufferBuilder, PoseStack stack,
float x1, float y1, float z1,
float x2, float y2, float z2,
float nx, float ny, float nz) {
final Matrix4f matrix4f = stack.last().pose();
final Matrix3f normal = stack.last().normal();
PoseStack.Pose pose = stack.last();
buffer.vertex(matrix4f, x1, y1, z1).color(color[0], color[1], color[2], color[3]).normal(normal, nx, ny, nz).endVertex();
buffer.vertex(matrix4f, x2, y2, z2).color(color[0], color[1], color[2], color[3]).normal(normal, nx, ny, nz).endVertex();
bufferBuilder.addVertex(pose, x1, y1, z1).setColor(color[0], color[1], color[2], color[3]).setNormal(pose, nx, ny, nz);
bufferBuilder.addVertex(pose, x2, y2, z2).setColor(color[0], color[1], color[2], color[3]).setNormal(pose, nx, ny, nz);
}
static void emitAABB(PoseStack stack, AABB aabb) {
static void emitAABB(BufferBuilder bufferBuilder, PoseStack stack, AABB aabb) {
AABB toDraw = aabb.move(-renderManager.renderPosX(), -renderManager.renderPosY(), -renderManager.renderPosZ());
// bottom
emitLine(stack, toDraw.minX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.minY, toDraw.minZ, 1.0, 0.0, 0.0);
emitLine(stack, toDraw.maxX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.minY, toDraw.maxZ, 0.0, 0.0, 1.0);
emitLine(stack, toDraw.maxX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.minY, toDraw.maxZ, -1.0, 0.0, 0.0);
emitLine(stack, toDraw.minX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.minY, toDraw.minZ, 0.0, 0.0, -1.0);
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.minY, toDraw.minZ, 1.0, 0.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.minY, toDraw.maxZ, 0.0, 0.0, 1.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.minY, toDraw.maxZ, -1.0, 0.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.minY, toDraw.minZ, 0.0, 0.0, -1.0);
// top
emitLine(stack, toDraw.minX, toDraw.maxY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.minZ, 1.0, 0.0, 0.0);
emitLine(stack, toDraw.maxX, toDraw.maxY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.maxZ, 0.0, 0.0, 1.0);
emitLine(stack, toDraw.maxX, toDraw.maxY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.maxZ, -1.0, 0.0, 0.0);
emitLine(stack, toDraw.minX, toDraw.maxY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.minZ, 0.0, 0.0, -1.0);
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.maxY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.minZ, 1.0, 0.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.maxY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.maxZ, 0.0, 0.0, 1.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.maxY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.maxZ, -1.0, 0.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.maxY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.minZ, 0.0, 0.0, -1.0);
// corners
emitLine(stack, toDraw.minX, toDraw.minY, toDraw.minZ, toDraw.minX, toDraw.maxY, toDraw.minZ, 0.0, 1.0, 0.0);
emitLine(stack, toDraw.maxX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.minZ, 0.0, 1.0, 0.0);
emitLine(stack, toDraw.maxX, toDraw.minY, toDraw.maxZ, toDraw.maxX, toDraw.maxY, toDraw.maxZ, 0.0, 1.0, 0.0);
emitLine(stack, toDraw.minX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.maxZ, 0.0, 1.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.minY, toDraw.minZ, toDraw.minX, toDraw.maxY, toDraw.minZ, 0.0, 1.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.minY, toDraw.minZ, toDraw.maxX, toDraw.maxY, toDraw.minZ, 0.0, 1.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.maxX, toDraw.minY, toDraw.maxZ, toDraw.maxX, toDraw.maxY, toDraw.maxZ, 0.0, 1.0, 0.0);
emitLine(bufferBuilder, stack, toDraw.minX, toDraw.minY, toDraw.maxZ, toDraw.minX, toDraw.maxY, toDraw.maxZ, 0.0, 1.0, 0.0);
}
static void emitAABB(PoseStack stack, AABB aabb, double expand) {
emitAABB(stack, aabb.inflate(expand, expand, expand));
static void emitAABB(BufferBuilder bufferBuilder, PoseStack stack, AABB aabb, double expand) {
emitAABB(bufferBuilder, stack, aabb.inflate(expand, expand, expand));
}
static void emitLine(PoseStack stack, Vec3 start, Vec3 end) {
static void emitLine(BufferBuilder bufferBuilder, PoseStack stack, Vec3 start, Vec3 end) {
double vpX = renderManager.renderPosX();
double vpY = renderManager.renderPosY();
double vpZ = renderManager.renderPosZ();
emitLine(stack, start.x - vpX, start.y - vpY, start.z - vpZ, end.x - vpX, end.y - vpY, end.z - vpZ);
emitLine(bufferBuilder, stack, start.x - vpX, start.y - vpY, start.z - vpZ, end.x - vpX, end.y - vpY, end.z - vpZ);
}
}

View File

@@ -26,6 +26,7 @@ import baritone.api.utils.interfaces.IGoalRenderPos;
import baritone.behavior.PathingBehavior;
import baritone.pathing.path.PathExecutor;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.renderer.blockentity.BeaconRenderer;
import net.minecraft.core.BlockPos;
@@ -37,6 +38,7 @@ import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.Arrays;
@@ -50,7 +52,7 @@ import java.util.List;
*/
public final class PathRenderer implements IRenderer {
private static final ResourceLocation TEXTURE_BEACON_BEAM = new ResourceLocation("textures/entity/beacon_beam.png");
private static final ResourceLocation TEXTURE_BEACON_BEAM = ResourceLocation.parse("textures/entity/beacon_beam.png");
private PathRenderer() {}
@@ -133,7 +135,7 @@ public final class PathRenderer implements IRenderer {
}
public static void drawPath(PoseStack stack, List<BetterBlockPos> positions, int startIndex, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0, double offset) {
IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
BufferBuilder bufferBuilder = IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value, settings.renderPathIgnoreDepth.value);
int fadeStart = fadeStart0 + startIndex;
int fadeEnd = fadeEnd0 + startIndex;
@@ -167,13 +169,13 @@ public final class PathRenderer implements IRenderer {
IRenderer.glColor(color, alpha);
}
emitPathLine(stack, start.x, start.y, start.z, end.x, end.y, end.z, offset);
emitPathLine(bufferBuilder, stack, start.x, start.y, start.z, end.x, end.y, end.z, offset);
}
IRenderer.endLines(settings.renderPathIgnoreDepth.value);
IRenderer.endLines(bufferBuilder, settings.renderPathIgnoreDepth.value);
}
private static void emitPathLine(PoseStack stack, double x1, double y1, double z1, double x2, double y2, double z2, double offset) {
private static void emitPathLine(BufferBuilder bufferBuilder, PoseStack stack, double x1, double y1, double z1, double x2, double y2, double z2, double offset) {
final double extraOffset = offset + 0.03D;
double vpX = posX();
@@ -181,20 +183,20 @@ public final class PathRenderer implements IRenderer {
double vpZ = posZ();
boolean renderPathAsFrickinThingy = !settings.renderPathAsLine.value;
IRenderer.emitLine(stack,
IRenderer.emitLine(bufferBuilder, stack,
x1 + offset - vpX, y1 + offset - vpY, z1 + offset - vpZ,
x2 + offset - vpX, y2 + offset - vpY, z2 + offset - vpZ
);
if (renderPathAsFrickinThingy) {
IRenderer.emitLine(stack,
IRenderer.emitLine(bufferBuilder, stack,
x2 + offset - vpX, y2 + offset - vpY, z2 + offset - vpZ,
x2 + offset - vpX, y2 + extraOffset - vpY, z2 + offset - vpZ
);
IRenderer.emitLine(stack,
IRenderer.emitLine(bufferBuilder, stack,
x2 + offset - vpX, y2 + extraOffset - vpY, z2 + offset - vpZ,
x1 + offset - vpX, y1 + extraOffset - vpY, z1 + offset - vpZ
);
IRenderer.emitLine(stack,
IRenderer.emitLine(bufferBuilder, stack,
x1 + offset - vpX, y1 + extraOffset - vpY, z1 + offset - vpZ,
x1 + offset - vpX, y1 + offset - vpY, z1 + offset - vpZ
);
@@ -202,7 +204,7 @@ public final class PathRenderer implements IRenderer {
}
public static void drawManySelectionBoxes(PoseStack stack, Entity player, Collection<BlockPos> positions, Color color) {
IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value, settings.renderSelectionBoxesIgnoreDepth.value);
BufferBuilder bufferBuilder = IRenderer.startLines(color, settings.pathRenderLineWidthPixels.value, settings.renderSelectionBoxesIgnoreDepth.value);
//BlockPos blockpos = movingObjectPositionIn.getBlockPos();
BlockStateInterface bsi = new BlockStateInterface(BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext()); // TODO this assumes same dimension between primary baritone and render view? is this safe?
@@ -212,17 +214,20 @@ public final class PathRenderer implements IRenderer {
VoxelShape shape = state.getShape(player.level(), pos);
AABB toDraw = shape.isEmpty() ? Shapes.block().bounds() : shape.bounds();
toDraw = toDraw.move(pos);
IRenderer.emitAABB(stack, toDraw, .002D);
IRenderer.emitAABB(bufferBuilder, stack, toDraw, .002D);
});
IRenderer.endLines(settings.renderSelectionBoxesIgnoreDepth.value);
IRenderer.endLines(bufferBuilder, settings.renderSelectionBoxesIgnoreDepth.value);
}
public static void drawGoal(PoseStack stack, IPlayerContext ctx, Goal goal, float partialTicks, Color color) {
drawGoal(stack, ctx, goal, partialTicks, color, true);
drawGoal(null, stack, ctx, goal, partialTicks, color, true);
}
private static void drawGoal(PoseStack stack, IPlayerContext ctx, Goal goal, float partialTicks, Color color, boolean setupRender) {
private static void drawGoal(@Nullable BufferBuilder bufferBuilder, PoseStack stack, IPlayerContext ctx, Goal goal, float partialTicks, Color color, boolean setupRender) {
if (!setupRender && bufferBuilder == null) {
throw new RuntimeException("BufferBuilder must not be null if setupRender is false");
}
double renderPosX = posX();
double renderPosY = posY();
double renderPosZ = posZ();
@@ -254,7 +259,7 @@ public final class PathRenderer implements IRenderer {
y2 -= 0.5;
maxY--;
}
drawDankLitGoalBox(stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
drawDankLitGoalBox(bufferBuilder, stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
} else if (goal instanceof GoalXZ) {
GoalXZ goalPos = (GoalXZ) goal;
minY = ctx.world().getMinBuildHeight();
@@ -280,7 +285,7 @@ public final class PathRenderer implements IRenderer {
settings.renderGoalAnimated.value ? ctx.world().getGameTime() : 0,
(int) minY,
(int) maxY,
color.getColorComponents(null),
color.getRGB(),
// Arguments filled by the private method lol
0.2F,
@@ -304,19 +309,19 @@ public final class PathRenderer implements IRenderer {
y2 = 0;
minY -= renderPosY;
maxY -= renderPosY;
drawDankLitGoalBox(stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
drawDankLitGoalBox(bufferBuilder, stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
} else if (goal instanceof GoalComposite) {
// Simple way to determine if goals can be batched, without having some sort of GoalRenderer
boolean batch = Arrays.stream(((GoalComposite) goal).goals()).allMatch(IGoalRenderPos.class::isInstance);
BufferBuilder buf = bufferBuilder;
if (batch) {
IRenderer.startLines(color, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value);
buf = IRenderer.startLines(color, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value);
}
for (Goal g : ((GoalComposite) goal).goals()) {
drawGoal(stack, ctx, g, partialTicks, color, !batch);
drawGoal(buf, stack, ctx, g, partialTicks, color, !batch);
}
if (batch) {
IRenderer.endLines(settings.renderGoalIgnoreDepth.value);
IRenderer.endLines(buf, settings.renderGoalIgnoreDepth.value);
}
} else if (goal instanceof GoalInverted) {
drawGoal(stack, ctx, ((GoalInverted) goal).origin, partialTicks, settings.colorInvertedGoalBox.value);
@@ -330,37 +335,37 @@ public final class PathRenderer implements IRenderer {
maxY = minY + 2;
y1 = 1 + y + goalpos.level - renderPosY;
y2 = 1 - y + goalpos.level - renderPosY;
drawDankLitGoalBox(stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
drawDankLitGoalBox(bufferBuilder, stack, color, minX, maxX, minZ, maxZ, minY, maxY, y1, y2, setupRender);
}
}
private static void drawDankLitGoalBox(PoseStack stack, Color colorIn, double minX, double maxX, double minZ, double maxZ, double minY, double maxY, double y1, double y2, boolean setupRender) {
private static void drawDankLitGoalBox(BufferBuilder bufferBuilder, PoseStack stack, Color colorIn, double minX, double maxX, double minZ, double maxZ, double minY, double maxY, double y1, double y2, boolean setupRender) {
if (setupRender) {
IRenderer.startLines(colorIn, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value);
bufferBuilder = IRenderer.startLines(colorIn, settings.goalRenderLineWidthPixels.value, settings.renderGoalIgnoreDepth.value);
}
renderHorizontalQuad(stack, minX, maxX, minZ, maxZ, y1);
renderHorizontalQuad(stack, minX, maxX, minZ, maxZ, y2);
renderHorizontalQuad(bufferBuilder, stack, minX, maxX, minZ, maxZ, y1);
renderHorizontalQuad(bufferBuilder, stack, minX, maxX, minZ, maxZ, y2);
for (double y = minY; y < maxY; y += 16) {
double max = Math.min(maxY, y + 16);
IRenderer.emitLine(stack, minX, y, minZ, minX, max, minZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(stack, maxX, y, minZ, maxX, max, minZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(stack, maxX, y, maxZ, maxX, max, maxZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(stack, minX, y, maxZ, minX, max, maxZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(bufferBuilder, stack, minX, y, minZ, minX, max, minZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(bufferBuilder, stack, maxX, y, minZ, maxX, max, minZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(bufferBuilder, stack, maxX, y, maxZ, maxX, max, maxZ, 0.0, 1.0, 0.0);
IRenderer.emitLine(bufferBuilder, stack, minX, y, maxZ, minX, max, maxZ, 0.0, 1.0, 0.0);
}
if (setupRender) {
IRenderer.endLines(settings.renderGoalIgnoreDepth.value);
IRenderer.endLines(bufferBuilder, settings.renderGoalIgnoreDepth.value);
}
}
private static void renderHorizontalQuad(PoseStack stack, double minX, double maxX, double minZ, double maxZ, double y) {
private static void renderHorizontalQuad(BufferBuilder bufferBuilder, PoseStack stack, double minX, double maxX, double minZ, double maxZ, double y) {
if (y != 0) {
IRenderer.emitLine(stack, minX, y, minZ, maxX, y, minZ, 1.0, 0.0, 0.0);
IRenderer.emitLine(stack, maxX, y, minZ, maxX, y, maxZ, 0.0, 0.0, 1.0);
IRenderer.emitLine(stack, maxX, y, maxZ, minX, y, maxZ, -1.0, 0.0, 0.0);
IRenderer.emitLine(stack, minX, y, maxZ, minX, y, minZ, 0.0, 0.0, -1.0);
IRenderer.emitLine(bufferBuilder, stack, minX, y, minZ, maxX, y, minZ, 1.0, 0.0, 0.0);
IRenderer.emitLine(bufferBuilder, stack, maxX, y, minZ, maxX, y, maxZ, 0.0, 0.0, 1.0);
IRenderer.emitLine(bufferBuilder, stack, maxX, y, maxZ, minX, y, maxZ, -1.0, 0.0, 0.0);
IRenderer.emitLine(bufferBuilder, stack, minX, y, maxZ, minX, y, minZ, 0.0, 0.0, -1.0);
}
}
}

View File

@@ -19,16 +19,19 @@ package baritone.utils;
import baritone.Baritone;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.Holder;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.SwordItem;
import net.minecraft.world.item.TieredItem;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.item.enchantment.*;
import net.minecraft.world.item.enchantment.effects.EnchantmentAttributeEffect;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
@@ -86,14 +89,22 @@ public class ToolSet {
private int getMaterialCost(ItemStack itemStack) {
if (itemStack.getItem() instanceof TieredItem) {
TieredItem tool = (TieredItem) itemStack.getItem();
return tool.getTier().getLevel();
return (int) tool.getTier().getAttackDamageBonus();
} else {
return -1;
}
}
public boolean hasSilkTouch(ItemStack stack) {
return EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, stack) > 0;
ItemEnchantments enchantments = stack.getEnchantments();
for (Holder<Enchantment> enchant : enchantments.keySet()) {
// silk touch enchantment is still special cased as affecting block drops
// not possible to add custom attribute via datapack
if (enchant.is(Enchantments.SILK_TOUCH) && enchantments.getLevel(enchant) > 0) {
return true;
}
}
return false;
}
/**
@@ -177,16 +188,28 @@ public class ToolSet {
* @return how long it would take in ticks
*/
public static double calculateSpeedVsBlock(ItemStack item, BlockState state) {
float hardness = state.getDestroySpeed(null, null);
float hardness;
try {
hardness = state.getDestroySpeed(null, null);
} catch (NullPointerException npe) {
// can't easily determine the hardness so treat it as unbreakable
return -1;
}
if (hardness < 0) {
return -1;
}
float speed = item.getDestroySpeed(state);
if (speed > 1) {
int effLevel = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_EFFICIENCY, item);
if (effLevel > 0 && !item.isEmpty()) {
speed += effLevel * effLevel + 1;
final ItemEnchantments itemEnchantments = item.getEnchantments();
OUTER: for (Holder<Enchantment> enchant : itemEnchantments.keySet()) {
List<EnchantmentAttributeEffect> effects = enchant.value().getEffects(EnchantmentEffectComponents.ATTRIBUTES);
for (EnchantmentAttributeEffect e : effects) {
if (e.attribute().is(Attributes.MINING_EFFICIENCY.unwrapKey().get())) {
speed += e.amount().calculate(itemEnchantments.getLevel(enchant));
break OUTER;
}
}
}
}

View File

@@ -23,7 +23,11 @@ public interface IPlayerControllerMP {
void setIsHittingBlock(boolean isHittingBlock);
boolean isHittingBlock();
BlockPos getCurrentBlock();
void callSyncCurrentPlayItem();
void setDestroyDelay(int destroyDelay);
}

View File

@@ -20,7 +20,6 @@ package baritone.utils.player;
import baritone.api.utils.IPlayerController;
import baritone.utils.accessor.IPlayerControllerMP;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
@@ -54,7 +53,7 @@ public final class BaritonePlayerController implements IPlayerController {
@Override
public boolean hasBrokenBlock() {
return ((IPlayerControllerMP) mc.gameMode).getCurrentBlock().getY() == -1;
return !((IPlayerControllerMP) mc.gameMode).isHittingBlock();
}
@Override

View File

@@ -41,6 +41,7 @@ public class MapArtSchematic extends MaskSchematic {
private static int[][] generateHeightMap(IStaticSchematic schematic) {
int[][] heightMap = new int[schematic.widthX()][schematic.lengthZ()];
int missingColumns = 0;
for (int x = 0; x < schematic.widthX(); x++) {
for (int z = 0; z < schematic.lengthZ(); z++) {
BlockState[] column = schematic.getColumn(x, z);
@@ -48,12 +49,14 @@ public class MapArtSchematic extends MaskSchematic {
if (lowestBlockY.isPresent()) {
heightMap[x][z] = lowestBlockY.getAsInt();
} else {
System.out.println("Column " + x + "," + z + " has no blocks, but it's apparently map art? wtf");
System.out.println("Letting it be whatever");
heightMap[x][z] = 256;
missingColumns++;
heightMap[x][z] = Integer.MAX_VALUE;
}
}
}
if (missingColumns != 0) {
System.out.println(missingColumns + " columns had no block despite being in a map art, letting them be whatever");
}
return heightMap;
}

View File

@@ -81,7 +81,9 @@ public enum DefaultSchematicFormats implements ISchematicFormat {
case 4: //1.12
case 5: //1.13-1.17
throw new UnsupportedOperationException("This litematic Version is too old.");
case 6: //1.18+
case 6: //1.18-1.20
throw new UnsupportedOperationException("This litematic Version is too old.");
case 7: //1.21+
return new LitematicaSchematic(nbt, false);
default:
throw new UnsupportedOperationException("Unsuported Version of a Litematica Schematic");

View File

@@ -94,7 +94,7 @@ public final class LitematicaSchematic extends StaticSchematic {
BlockState[] blockList = new BlockState[blockStatePalette.size()];
for (int i = 0; i < blockStatePalette.size(); i++) {
Block block = BuiltInRegistries.BLOCK.get(new ResourceLocation((((CompoundTag) blockStatePalette.get(i)).getString("Name"))));
Block block = BuiltInRegistries.BLOCK.get(ResourceLocation.parse((((CompoundTag) blockStatePalette.get(i)).getString("Name"))));
CompoundTag properties = ((CompoundTag) blockStatePalette.get(i)).getCompound("Properties");
blockList[i] = getBlockState(block, properties);
@@ -345,4 +345,4 @@ public final class LitematicaSchematic extends StaticSchematic {
return this.arraySize;
}
}
}
}

View File

@@ -130,7 +130,7 @@ public final class SpongeSchematic extends StaticSchematic {
String location = m.group("location");
String properties = m.group("properties");
ResourceLocation resourceLocation = new ResourceLocation(location);
ResourceLocation resourceLocation = ResourceLocation.parse(location);
Map<String, String> propertiesMap = new HashMap<>();
if (properties != null) {
for (String property : properties.split(",")) {

View File

@@ -26,7 +26,7 @@ plugins {
unimined.minecraft {
runs.client = {
mainClass = "net.minecraft.launchwrapper.Launch"
args.addAll(["--tweakClass", "baritone.launch.BaritoneTweaker"])
args.addAll(["--tweakClass", "baritone.launch.tweaker.BaritoneTweaker"])
}
}
@@ -94,8 +94,7 @@ jar {
}
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'
proguardVersion "7.4.2"
}
task createDist(type: CreateDistTask, dependsOn: proguard)

View File

@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch;
package baritone.launch.tweaker;
import io.github.impactdevelopment.simpletweaker.SimpleTweaker;
import net.minecraft.launchwrapper.Launch;