Compare commits

...

80 Commits

Author SHA1 Message Date
Leijurv 600c5b77ad v1.2.0 2019-02-23 20:43:29 -08:00
Leijurv f1084fab76 come 2019-02-23 20:33:00 -08:00
Brady bd65e32407 Fix the failing build 2019-02-23 17:04:14 -06:00
Leijurv e4416f424a interesting 2019-02-23 14:13:27 -08:00
Leijurv 73ec110b22 not every player is a baritone 2019-02-23 14:03:47 -08:00
Brady 0bce801a3f Minor javadoc changes 2019-02-23 14:32:10 -06:00
Brady e8e00e8dfb CRLF -> LF
It was inconsistent across the board
2019-02-23 12:27:24 -06:00
Leijurv cc4335e48e better links 2019-02-22 23:32:23 -08:00
Leijurv 5427911da3 only api in javadoc i guess 2019-02-22 23:29:08 -08:00
Brady c808d5a42d Small build.gradle cleanup and README update 2019-02-22 18:12:04 -06:00
Leijurv 3b46dbd6a1 appease codacy 2019-02-22 14:05:29 -08:00
Leijurv e63b2f1bf1 unused arg 2019-02-22 13:58:03 -08:00
Leijurv d32e822057 settings overhaul 2019-02-22 12:13:19 -08:00
Leijurv 16dcd2f44d blocks on top of chests, fixes #299 2019-02-21 11:25:03 -08:00
Leijurv eb9f755b54 disable rendercachedchunks in singleplayer, fixes #331 2019-02-21 10:03:03 -08:00
Leijurv 29a9e6e1d1 fine, forward alias to thisway 2019-02-21 09:45:01 -08:00
Leijurv 1f52f706ed should fix anticheatcompat off on forge 2019-02-20 23:41:29 -08:00
Leijurv a72040f83d imagine breaking the build 2019-02-19 19:52:11 -08:00
Leijurv 84d8f826ff fine lol, fixes #340 2019-02-19 19:41:26 -08:00
Brady 70d216b29f Fix renderGoalXZBeacon path rendering incorrect color 2019-02-19 21:00:14 -06:00
Leijurv 66356d5334 hmm 2019-02-19 18:27:05 -08:00
Leijurv d9625dfe78 no longer needed crab rave 2019-02-19 18:24:12 -08:00
Leijurv 6d847577d8 somehow missed those 2019-02-19 18:22:59 -08:00
Leijurv 8fd687f9d7 more usage help 2019-02-19 15:04:18 -08:00
Leijurv f7a9380b9d v1.1.6 2019-02-19 14:53:43 -08:00
Leijurv 5617c595b2 public init 2019-02-19 14:43:48 -08:00
Leijurv 8770524679 fix weird angle forcing behavior, fixes #341 2019-02-19 14:29:08 -08:00
Leijurv a8ddb2fcf1 also disallow while breaking 2019-02-19 13:28:58 -08:00
Leijurv 76c4ca9ba6 fix path reliability after lateral movement 2019-02-19 12:55:58 -08:00
Leijurv ed2b0f0bb9 fix jump before place ascend 2019-02-19 12:44:29 -08:00
Leijurv 6702b44b3e reformatted and fixed stuck on break fall 2019-02-19 12:43:44 -08:00
Leijurv c486d8241e continue 2019-02-19 07:53:36 -08:00
Leijurv d2bb8c374e explain 2019-02-18 21:18:37 -08:00
Leijurv 530cecea5b it flows better this way 2019-02-17 21:41:54 -08:00
Leijurv 266e2dada9 cleanup 2019-02-16 20:49:38 -08:00
Leijurv 11af0a7aac v1.1.5 2019-02-15 21:36:34 -08:00
Leijurv 46c2d8f7c7 unneeded 2019-02-15 21:35:52 -08:00
Leijurv 38127011fb Merge pull request #336 from babbaj/master
Fix potential problems
2019-02-14 14:48:48 -08:00
Leijurv 89b5ce4b63 properly detect failure 2019-02-14 14:47:38 -08:00
babbaj 4fe9c180d5 Fix potential problems 2019-02-14 07:03:22 -05:00
Leijurv f094e83e4d codacy 2019-02-13 22:41:18 -08:00
Leijurv 5b6c9fc348 blacklist unreachable gettoblocks 2019-02-13 22:39:43 -08:00
Leijurv 3f1ee100bf only sprint ascends that are followed in the same direction 2019-02-13 22:39:34 -08:00
Leijurv 41b1106c72 sprint in water for real 2019-02-13 21:20:06 -08:00
Leijurv b27d95a615 proper fall overshooting 2019-02-13 21:11:13 -08:00
Leijurv 5b8a83853d add setting to sprint in water 2019-02-13 19:23:16 -08:00
Leijurv d0548b2715 add a warning 2019-02-13 18:39:26 -08:00
Leijurv bffeb9c862 forgot one extra check 2019-02-13 18:38:46 -08:00
Leijurv dbd760fbcb some polish on ascend sprinting 2019-02-13 18:26:30 -08:00
Leijurv a84b3bfc7a sprint through ascends whenever possible, fixes #149 2019-02-13 16:55:08 -08:00
Leijurv e8d3bf509c clarify 2019-02-13 16:33:27 -08:00
Leijurv b2583773d5 discard next segment properly 2019-02-13 16:30:53 -08:00
Leijurv 9ecd24c755 remove toxic cloud 2019-02-13 16:30:41 -08:00
Leijurv f1bacd6210 fix cancellation of unusable segments 2019-02-13 16:22:49 -08:00
Leijurv a21ec54d4f stop breaking block when you let go of left click lol 2019-02-13 14:05:14 -08:00
Leijurv 0b4efb24ae momentous occasion: turning that crap off 2019-02-13 13:57:33 -08:00
Leijurv c473914d05 fix flashing backwards, fixes #265 2019-02-13 13:54:50 -08:00
Leijurv 90a1fa8337 lol 2019-02-12 22:06:13 -08:00
Leijurv 99cb7f5142 crucial performance optimization 2019-02-12 21:36:53 -08:00
Leijurv 4026b850f8 dont spam debug chat 2019-02-12 18:34:58 -08:00
Leijurv aac7ebf6dd avoid creating callbackinfo at all costs 2019-02-12 18:32:03 -08:00
Leijurv 8d481ba394 lol 2019-02-12 09:58:44 -08:00
Leijurv 24fa75c24e did someone say more badges 2019-02-11 22:26:49 -08:00
Leijurv cf38d593b8 thanks leafeon 2019-02-11 22:20:59 -08:00
Leijurv 36f608c63c add epic gamer address 2019-02-11 19:21:08 -08:00
Leijurv 1d88564a72 clarify this setting since its got a similar name 2019-02-10 16:50:54 -08:00
Leijurv 503f2fb197 direct link to the top of the detail section since its not sorted alphabetically 2019-02-10 16:46:37 -08:00
Leijurv bb000c4e3f include diagonals, and better settings 2019-02-10 16:44:09 -08:00
Leijurv 4868ed7560 explain whats going on 2019-02-10 15:12:52 -08:00
Leijurv 7017e9e2ea crucial performance optimization 2019-02-10 15:10:44 -08:00
Leijurv a18eb90702 address glaring inconsistency 2019-02-10 13:49:28 -08:00
Leijurv 9d1d4fe0d9 typo 2019-02-10 10:44:04 -08:00
Leijurv 1a430dc2cf explain 2019-02-09 17:38:42 -08:00
Leijurv e37a09a1c8 makes mining faster, fixes #330 2019-02-08 12:08:34 -08:00
Leijurv d0d8b12fb8 add clickCancel, fixes #326 2019-02-07 17:18:14 -08:00
Leijurv 9a29f9ce57 better behavior on arrival and failure 2019-02-07 16:39:15 -08:00
Leijurv 42513e4b56 better check 2019-02-07 16:12:34 -08:00
Leijurv 67fa91abe8 fixes to descend, and goto coords 2019-02-07 15:55:39 -08:00
Leijurv 6faa7344aa properly discard orphan path segments 2019-02-07 14:11:18 -08:00
Leijurv c0761c0eef be more tolerant of alternate movement inputs 2019-02-07 10:46:32 -08:00
47 changed files with 1361 additions and 943 deletions
+15 -3
View File
@@ -11,6 +11,8 @@
[![Pull Requests](https://img.shields.io/github/issues-pr/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/pulls/) [![Pull Requests](https://img.shields.io/github/issues-pr/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/pulls/)
![Code size](https://img.shields.io/github/languages/code-size/cabaletta/baritone.svg) ![Code size](https://img.shields.io/github/languages/code-size/cabaletta/baritone.svg)
![GitHub repo size](https://img.shields.io/github/repo-size/cabaletta/baritone.svg) ![GitHub repo size](https://img.shields.io/github/repo-size/cabaletta/baritone.svg)
![](https://tokei.rs/b1/github/cabaletta/baritone?category=code)
![](https://tokei.rs/b1/github/cabaletta/baritone?category=files)
[![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2) [![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2)
[![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/)
[![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/)
@@ -30,6 +32,10 @@ the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone
Have committed at least once a day for the last 6 months =D 🦀 Have committed at least once a day for the last 6 months =D 🦀
1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2
# Getting Started
Here are some links to help to get started: Here are some links to help to get started:
- [Features](FEATURES.md) - [Features](FEATURES.md)
@@ -40,11 +46,17 @@ Here are some links to help to get started:
- [Javadocs](https://baritone.leijurv.com/) - [Javadocs](https://baritone.leijurv.com/)
# Chat control - [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#field.detail)
- [Baritone chat control usage](USAGE.md) - [Baritone chat control usage](USAGE.md)
# API example # API
The API is heavily documented, you can find the Javadocs for the latest release [here](https://baritone.leijurv.com/).
Please note that usage of anything located outside of the ``baritone.api`` package is not supported by the API release
jar.
Below is an example of basic usage for changing some settings, and then pathing to a X/Z goal.
``` ```
BaritoneAPI.getSettings().allowSprint.value = true; BaritoneAPI.getSettings().allowSprint.value = true;
@@ -57,7 +69,7 @@ BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAnd
## Can I use Baritone as a library in my custom utility client? ## Can I use Baritone as a library in my custom utility client?
Sure! (As long as usage is in compliance with the LGPL 3 License) That's what it's for, sure! (As long as usage is in compliance with the LGPL 3 License)
## How is it so fast? ## How is it so fast?
+2 -2
View File
@@ -21,7 +21,7 @@ Other clients like Kami and Asuna have their own custom things (like `-path`), a
`help` for (rudimentary) help. You can see what it says [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java#L53). `help` for (rudimentary) help. You can see what it says [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java#L53).
To toggle a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `primaryTimeoutMS 250`). It's case insensitive. To toggle a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `primaryTimeoutMS 250`). It's case insensitive. To reset a setting to its default value, say `acceptableThrowawayItems reset`. To reset all settings, say `reset`. To see all settings that have been modified from their default values, say `modified`.
@@ -43,7 +43,7 @@ Some common examples:
For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java). For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java).
All the settings and documentation are <a href="https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/Settings.java">here</a>. If you find HTML easier to read than Javadoc, you can look <a href="https://baritone.leijurv.com/">here</a> and navigate to Settings in the left sidebar. All the settings and documentation are <a href="https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/Settings.java">here</a>. If you find HTML easier to read than Javadoc, you can look <a href="https://baritone.leijurv.com/baritone/api/Settings.html#field.detail">here</a>.
There are about a hundred settings, but here are some fun / interesting / important ones that you might want to look at changing in normal usage of Baritone. The documentation for each can be found at the above links. There are about a hundred settings, but here are some fun / interesting / important ones that you might want to look at changing in normal usage of Baritone. The documentation for each can be found at the above links.
- `allowBreak` - `allowBreak`
+132 -134
View File
@@ -1,134 +1,132 @@
/* /*
* This file is part of Baritone. * This file is part of Baritone.
* *
* Baritone is free software: you can redistribute it and/or modify * 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 * 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 * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Baritone is distributed in the hope that it will be useful, * Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details. * GNU Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public License * You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>. * along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/ */
group 'baritone' group 'baritone'
version '1.1.4' version '1.2.0'
buildscript { buildscript {
repositories { repositories {
maven { maven {
name = 'forge' name = 'forge'
url = 'http://files.minecraftforge.net/maven' url = 'http://files.minecraftforge.net/maven'
} }
maven { maven {
name = 'SpongePowered' name = 'SpongePowered'
url = 'http://repo.spongepowered.org/maven' url = 'http://repo.spongepowered.org/maven'
} }
jcenter() jcenter()
} }
dependencies { dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT' classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT' classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT'
} }
} }
import baritone.gradle.task.CreateDistTask import baritone.gradle.task.CreateDistTask
import baritone.gradle.task.ProguardTask import baritone.gradle.task.ProguardTask
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'net.minecraftforge.gradle.tweaker-client' apply plugin: 'net.minecraftforge.gradle.tweaker-client'
apply plugin: 'org.spongepowered.mixin' apply plugin: 'org.spongepowered.mixin'
sourceCompatibility = targetCompatibility = '1.8' sourceCompatibility = targetCompatibility = '1.8'
compileJava { compileJava {
sourceCompatibility = targetCompatibility = '1.8' sourceCompatibility = targetCompatibility = '1.8'
options.encoding = "UTF-8" // allow emoji in comments :^) options.encoding = "UTF-8" // allow emoji in comments :^)
} }
sourceSets { sourceSets {
launch { launch {
compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output
} }
} }
minecraft { minecraft {
version = '1.12.2' version = '1.12.2'
mappings = 'stable_39' mappings = 'stable_39'
tweakClass = 'baritone.launch.BaritoneTweaker' tweakClass = 'baritone.launch.BaritoneTweaker'
runDir = 'run' runDir = 'run'
// The sources jar should use SRG names not MCP to ensure compatibility with all mappings // The sources jar should use SRG names not MCP to ensure compatibility with all mappings
makeObfSourceJar = true makeObfSourceJar = true
} }
repositories { repositories {
mavenCentral() mavenCentral()
maven { maven {
name = 'spongepowered-repo' name = 'spongepowered-repo'
url = 'http://repo.spongepowered.org/maven/' url = 'http://repo.spongepowered.org/maven/'
} }
maven { maven {
name = 'impactdevelopment-repo' name = 'impactdevelopment-repo'
url = 'https://impactdevelopment.github.io/maven/' url = 'https://impactdevelopment.github.io/maven/'
} }
} }
dependencies { dependencies {
runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.2') runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.2')
runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') { runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') {
// Mixin includes a lot of dependencies that are too up-to-date // Mixin includes a lot of dependencies that are too up-to-date
exclude module: 'launchwrapper' exclude module: 'launchwrapper'
exclude module: 'guava' exclude module: 'guava'
exclude module: 'gson' exclude module: 'gson'
exclude module: 'commons-io' exclude module: 'commons-io'
exclude module: 'log4j-core' exclude module: 'log4j-core'
} }
testImplementation 'junit:junit:4.12' testImplementation 'junit:junit:4.12'
} }
mixin { mixin {
defaultObfuscationEnv searge defaultObfuscationEnv searge
add sourceSets.launch, 'mixins.baritone.refmap.json' add sourceSets.launch, 'mixins.baritone.refmap.json'
} }
javadoc { javadoc {
options.addStringOption('Xwerror', '-quiet') // makes the build fail on travis when there is a javadoc error options.addStringOption('Xwerror', '-quiet') // makes the build fail on travis when there is a javadoc error
options.linkSource true options.linkSource true
options.encoding "UTF-8" // allow emoji in comments :^) options.encoding "UTF-8" // allow emoji in comments :^)
source += sourceSets.api.allJava source = sourceSets.api.allJava
classpath += sourceSets.api.compileClasspath classpath += sourceSets.api.compileClasspath
} }
jar { jar {
from sourceSets.launch.output, sourceSets.api.output from sourceSets.launch.output, sourceSets.api.output
preserveFileTimestamps = false preserveFileTimestamps = false
reproducibleFileOrder = true reproducibleFileOrder = true
}
manifest {
jar { attributes(
manifest { 'MixinConfigs': 'mixins.baritone.json',
attributes(
'MixinConfigs': 'mixins.baritone.json', 'Implementation-Title': 'Baritone',
'Implementation-Version': version
'Implementation-Title': 'Baritone', )
'Implementation-Version': version }
) }
}
} task proguard(type: ProguardTask) {
url 'https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip'
task proguard(type: ProguardTask) { extract 'proguard6.0.3/lib/proguard.jar'
url 'https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip' }
extract 'proguard6.0.3/lib/proguard.jar'
} task createDist(type: CreateDistTask, dependsOn: proguard)
task createDist(type: CreateDistTask, dependsOn: proguard) build.finalizedBy(createDist)
build.finalizedBy(createDist)
@@ -17,8 +17,6 @@
package baritone.gradle.task; package baritone.gradle.task;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.gradle.api.DefaultTask; import org.gradle.api.DefaultTask;
import java.io.File; import java.io.File;
@@ -26,7 +24,6 @@ import java.io.InputStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.List;
/** /**
* @author Brady * @author Brady
+6 -6
View File
@@ -1,6 +1,6 @@
#Tue Jul 31 21:56:56 PDT 2018 #Tue Jul 31 21:56:56 PDT 2018
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip
Vendored
+84 -84
View File
@@ -1,84 +1,84 @@
@if "%DEBUG%" == "" @echo off @if "%DEBUG%" == "" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@rem Gradle startup script for Windows @rem Gradle startup script for Windows
@rem @rem
@rem ########################################################################## @rem ##########################################################################
@rem Set local scope for the variables with windows NT shell @rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=. if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS= set DEFAULT_JVM_OPTS=
@rem Find java.exe @rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init if "%ERRORLEVEL%" == "0" goto init
echo. echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo. echo.
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation. echo location of your Java installation.
goto fail goto fail
:findJavaFromJavaHome :findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=% set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init if exist "%JAVA_EXE%" goto init
echo. echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo. echo.
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation. echo location of your Java installation.
goto fail goto fail
:init :init
@rem Get command-line arguments, handling Windows variants @rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args :win9xME_args
@rem Slurp the command line arguments. @rem Slurp the command line arguments.
set CMD_LINE_ARGS= set CMD_LINE_ARGS=
set _SKIP=2 set _SKIP=2
:win9xME_args_slurp :win9xME_args_slurp
if "x%~1" == "x" goto execute if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%* set CMD_LINE_ARGS=%*
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if "%ERRORLEVEL%"=="0" goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1 exit /b 1
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal
:omega :omega
+1 -3
View File
@@ -14,6 +14,7 @@
# lwjgl is weird # lwjgl is weird
-dontwarn org.lwjgl.opengl.GL14 -dontwarn org.lwjgl.opengl.GL14
-dontwarn org.lwjgl.opengl.GL11
-keep class baritone.api.** { *; } # this is the keep api -keep class baritone.api.** { *; } # this is the keep api
@@ -21,9 +22,6 @@
-keep class baritone.BaritoneProvider -keep class baritone.BaritoneProvider
-keep class baritone.api.IBaritoneProvider -keep class baritone.api.IBaritoneProvider
# hack
-keep class baritone.utils.ExampleBaritoneControl { *; } # have to include this string to remove this keep in the standalone build: # this is the keep api
# setting names are reflected from field names, so keep field names # setting names are reflected from field names, so keep field names
-keepclassmembers class baritone.api.Settings { -keepclassmembers class baritone.api.Settings {
public <fields>; public <fields>;
+19 -19
View File
@@ -1,19 +1,19 @@
/* /*
* This file is part of Baritone. * This file is part of Baritone.
* *
* Baritone is free software: you can redistribute it and/or modify * 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 * 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 * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Baritone is distributed in the hope that it will be useful, * Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details. * GNU Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public License * You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>. * along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/ */
rootProject.name = 'baritone' rootProject.name = 'baritone'
+1 -3
View File
@@ -23,9 +23,7 @@ import java.util.Iterator;
import java.util.ServiceLoader; import java.util.ServiceLoader;
/** /**
* API exposure for various things implemented in Baritone. * Exposes the {@link IBaritoneProvider} instance and the {@link Settings} instance for API usage.
* <p>
* W.I.P
* *
* @author Brady * @author Brady
* @since 9/23/2018 * @since 9/23/2018
+56 -23
View File
@@ -22,10 +22,7 @@ import baritone.api.behavior.IPathingBehavior;
import baritone.api.cache.IWorldProvider; import baritone.api.cache.IWorldProvider;
import baritone.api.event.listener.IEventBus; import baritone.api.event.listener.IEventBus;
import baritone.api.pathing.calc.IPathingControlManager; import baritone.api.pathing.calc.IPathingControlManager;
import baritone.api.process.ICustomGoalProcess; import baritone.api.process.*;
import baritone.api.process.IFollowProcess;
import baritone.api.process.IGetToBlockProcess;
import baritone.api.process.IMineProcess;
import baritone.api.utils.IInputOverrideHandler; import baritone.api.utils.IInputOverrideHandler;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
@@ -36,22 +33,13 @@ import baritone.api.utils.IPlayerContext;
public interface IBaritone { public interface IBaritone {
/** /**
* @return The {@link IFollowProcess} instance * Call as soon as Minecraft is ready, initializes all of the processes, behaviors, etc. This will
* @see IFollowProcess * only effectively be ran once, any additional calls are redundant because the initialization state
* is saved.
* <p>
* Or whenever your overeager utility client wants.
*/ */
IFollowProcess getFollowProcess(); void init();
/**
* @return The {@link ILookBehavior} instance
* @see ILookBehavior
*/
ILookBehavior getLookBehavior();
/**
* @return The {@link IMineProcess} instance
* @see IMineProcess
*/
IMineProcess getMineProcess();
/** /**
* @return The {@link IPathingBehavior} instance * @return The {@link IPathingBehavior} instance
@@ -59,21 +47,66 @@ public interface IBaritone {
*/ */
IPathingBehavior getPathingBehavior(); IPathingBehavior getPathingBehavior();
/**
* @return The {@link ILookBehavior} instance
* @see ILookBehavior
*/
ILookBehavior getLookBehavior();
/**
* @return The {@link IFollowProcess} instance
* @see IFollowProcess
*/
IFollowProcess getFollowProcess();
/**
* @return The {@link IMineProcess} instance
* @see IMineProcess
*/
IMineProcess getMineProcess();
/**
* @return The {@link ICustomGoalProcess} instance
* @see ICustomGoalProcess
*/
ICustomGoalProcess getCustomGoalProcess();
/**
* @return The {@link IGetToBlockProcess} instance
* @see IGetToBlockProcess
*/
IGetToBlockProcess getGetToBlockProcess();
/** /**
* @return The {@link IWorldProvider} instance * @return The {@link IWorldProvider} instance
* @see IWorldProvider * @see IWorldProvider
*/ */
IWorldProvider getWorldProvider(); IWorldProvider getWorldProvider();
/**
* Returns the {@link IPathingControlManager} for this {@link IBaritone} instance, which is responsible
* for managing the {@link IBaritoneProcess}es which control the {@link IPathingBehavior} state.
*
* @return The {@link IPathingControlManager} instance
* @see IPathingControlManager
*/
IPathingControlManager getPathingControlManager(); IPathingControlManager getPathingControlManager();
/**
* @return The {@link IInputOverrideHandler} instance
* @see IInputOverrideHandler
*/
IInputOverrideHandler getInputOverrideHandler(); IInputOverrideHandler getInputOverrideHandler();
ICustomGoalProcess getCustomGoalProcess(); /**
* @return The {@link IPlayerContext} instance
IGetToBlockProcess getGetToBlockProcess(); * @see IPlayerContext
*/
IPlayerContext getPlayerContext(); IPlayerContext getPlayerContext();
/**
* @return The {@link IEventBus} instance
* @see IEventBus
*/
IEventBus getGameEventHandler(); IEventBus getGameEventHandler();
} }
@@ -23,7 +23,9 @@ import net.minecraft.client.entity.EntityPlayerSP;
import java.util.List; import java.util.List;
/** /**
* @author Leijurv * Provides the present {@link IBaritone} instances
*
* @author leijurv
*/ */
public interface IBaritoneProvider { public interface IBaritoneProvider {
@@ -47,7 +49,8 @@ public interface IBaritoneProvider {
/** /**
* Provides the {@link IBaritone} instance for a given {@link EntityPlayerSP}. This will likely be * Provides the {@link IBaritone} instance for a given {@link EntityPlayerSP}. This will likely be
* replaced with {@code #getBaritoneForUser(IBaritoneUser)} when {@code bot-system} is merged. * replaced with or be overloaded in addition to {@code #getBaritoneForUser(IBaritoneUser)} when
* {@code bot-system} is merged into {@code master}.
* *
* @param player The player * @param player The player
* @return The {@link IBaritone} instance. * @return The {@link IBaritone} instance.
@@ -58,7 +61,7 @@ public interface IBaritoneProvider {
return baritone; return baritone;
} }
} }
throw new IllegalStateException("No baritone for player " + player); return null;
} }
/** /**
+50 -14
View File
@@ -17,6 +17,7 @@
package baritone.api; package baritone.api;
import baritone.api.utils.SettingsUtil;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.item.Item; import net.minecraft.item.Item;
@@ -29,7 +30,7 @@ import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
/** /**
* Baritone's settings * Baritone's settings. Settings apply to all Baritone instances.
* *
* @author leijurv * @author leijurv
*/ */
@@ -164,6 +165,11 @@ public final class Settings {
*/ */
public final Setting<Boolean> considerPotionEffects = new Setting<>(true); public final Setting<Boolean> considerPotionEffects = new Setting<>(true);
/**
* Sprint and jump a block early on ascends wherever possible
*/
public final Setting<Boolean> sprintAscends = new Setting<>(true);
/** /**
* This is the big A* setting. * This is the big A* setting.
* As long as your cost heuristic is an *underestimate*, it's guaranteed to find you the best path. * As long as your cost heuristic is an *underestimate*, it's guaranteed to find you the best path.
@@ -277,7 +283,7 @@ public final class Settings {
/** /**
* Start planning the next path once the remaining movements tick estimates sum up to less than this value * Start planning the next path once the remaining movements tick estimates sum up to less than this value
*/ */
public final Setting<Integer> planningTickLookAhead = new Setting<>(150); public final Setting<Integer> planningTickLookahead = new Setting<>(150);
/** /**
* Default size of the Long2ObjectOpenHashMap used in pathing * Default size of the Long2ObjectOpenHashMap used in pathing
@@ -308,6 +314,8 @@ public final class Settings {
* Is it okay to sprint through a descend followed by a diagonal? * Is it okay to sprint through a descend followed by a diagonal?
* The player overshoots the landing, but not enough to fall off. And the diagonal ensures that there isn't * The player overshoots the landing, but not enough to fall off. And the diagonal ensures that there isn't
* lava or anything that's !canWalkInto in that space, so it's technically safe, just a little sketchy. * lava or anything that's !canWalkInto in that space, so it's technically safe, just a little sketchy.
* <p>
* Note: this is *not* related to the allowDiagonalDescend setting, that is a completely different thing.
*/ */
public final Setting<Boolean> allowOvershootDiagonalDescend = new Setting<>(true); public final Setting<Boolean> allowOvershootDiagonalDescend = new Setting<>(true);
@@ -378,6 +386,11 @@ public final class Settings {
*/ */
public final Setting<Boolean> pruneRegionsFromRAM = new Setting<>(false); public final Setting<Boolean> pruneRegionsFromRAM = new Setting<>(false);
/**
* Cancel baritone on left click, as a form of "panic button"
*/
public final Setting<Boolean> clickCancel = new Setting<>(false);
/** /**
* Remember the contents of containers (chests, echests, furnaces) * Remember the contents of containers (chests, echests, furnaces)
* <p> * <p>
@@ -388,7 +401,7 @@ public final class Settings {
/** /**
* Print all the debug messages to chat * Print all the debug messages to chat
*/ */
public final Setting<Boolean> chatDebug = new Setting<>(true); public final Setting<Boolean> chatDebug = new Setting<>(false);
/** /**
* Allow chat based control of Baritone. Most likely should be disabled when Baritone is imported for use in * Allow chat based control of Baritone. Most likely should be disabled when Baritone is imported for use in
@@ -467,7 +480,18 @@ public final class Settings {
public final Setting<Boolean> pathThroughCachedOnly = new Setting<>(false); public final Setting<Boolean> pathThroughCachedOnly = new Setting<>(false);
/** /**
* 😎 Render cached chunks as semitransparent. Doesn't work with OptiFine 😭 * Continue sprinting while in water
*/
public final Setting<Boolean> sprintInWater = new Setting<>(true);
/**
* When GetToBlockProcess fails to calculate a path, instead of just giving up, mark the closest instances
* of that block as "unreachable" and go towards the next closest
*/
public final Setting<Boolean> blacklistOnGetToBlockFailure = new Setting<>(true);
/**
* 😎 Render cached chunks as semitransparent. Doesn't work with OptiFine 😭 Rarely randomly crashes, see <a href="https://github.com/cabaletta/baritone/issues/327">this issue</a>.
* <p> * <p>
* Can be very useful on servers with low render distance. After enabling, you may need to reload the world in order for it to have an effect * Can be very useful on servers with low render distance. After enabling, you may need to reload the world in order for it to have an effect
* (e.g. disconnect and reconnect, enter then exit the nether, die and respawn, etc). This may literally kill your FPS and CPU because * (e.g. disconnect and reconnect, enter then exit the nether, die and respawn, etc). This may literally kill your FPS and CPU because
@@ -477,18 +501,18 @@ public final class Settings {
* <p> * <p>
* SOLID is rendered as stone in the overworld, netherrack in the nether, and end stone in the end * SOLID is rendered as stone in the overworld, netherrack in the nether, and end stone in the end
*/ */
public Setting<Boolean> renderCachedChunks = new Setting<>(false); public final Setting<Boolean> renderCachedChunks = new Setting<>(false);
/** /**
* 0.0f = not visible, fully transparent * 0.0f = not visible, fully transparent
* 1.0f = fully opaque * 1.0f = fully opaque
*/ */
public Setting<Float> cachedChunksOpacity = new Setting<>(0.5f); public final Setting<Float> cachedChunksOpacity = new Setting<>(0.5f);
/** /**
* If true, Baritone will not allow you to left or right click while pathing * If true, Baritone will not allow you to left or right click while pathing
*/ */
public Setting<Boolean> suppressClicks = new Setting<>(false); public final Setting<Boolean> suppressClicks = new Setting<>(false);
/** /**
* Whether or not to use the "#" command prefix * Whether or not to use the "#" command prefix
@@ -558,6 +582,19 @@ public final class Settings {
*/ */
public final Setting<Integer> legitMineYLevel = new Setting<>(11); public final Setting<Integer> legitMineYLevel = new Setting<>(11);
/**
* Magically see ores that are separated diagonally from existing ores. Basically like mining around the ores that it finds
* in case there's one there touching it diagonally, except it checks it un-legit-ly without having the mine blocks to see it.
* You can decide whether this looks plausible or not.
* <p>
* This is disabled because it results in some weird behavior. For example, it can """see""" the top block of a vein of iron_ore
* through a lava lake. This isn't an issue normally since it won't consider anything touching lava, so it just ignores it.
* However, this setting expands that and allows it to see the entire vein so it'll mine under the lava lake to get the iron that
* it can reach without mining blocks adjacent to lava. This really defeats the purpose of legitMine since a player could never
* do that lol, so thats one reason why its disabled
*/
public final Setting<Boolean> legitMineIncludeDiagonals = new Setting<>(false);
/** /**
* When mining block of a certain type, try to mine two at once instead of one. * When mining block of a certain type, try to mine two at once instead of one.
* If the block above is also a goal block, set GoalBlock instead of GoalTwoBlocks * If the block above is also a goal block, set GoalBlock instead of GoalTwoBlocks
@@ -668,12 +705,6 @@ public final class Settings {
*/ */
public final List<Setting<?>> allSettings; public final List<Setting<?>> allSettings;
public void reset() {
for (Setting setting : allSettings) {
setting.value = setting.defaultValue;
}
}
public final class Setting<T> { public final class Setting<T> {
public T value; public T value;
public final T defaultValue; public final T defaultValue;
@@ -703,8 +734,13 @@ public final class Settings {
return klass; return klass;
} }
@Override
public String toString() { public String toString() {
return name + ": " + value; return SettingsUtil.settingToString(this);
}
public void reset() {
value = defaultValue;
} }
} }
@@ -18,8 +18,13 @@
package baritone.api.behavior; package baritone.api.behavior;
import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.event.listener.IGameEventListener;
/** /**
* A behavior is simply a type that is able to listen to events.
*
* @see IGameEventListener
*
* @author Brady * @author Brady
* @since 9/23/2018 * @since 9/23/2018
*/ */
+11 -2
View File
@@ -117,8 +117,12 @@ public class Rotation {
* @return are they really close * @return are they really close
*/ */
public boolean isReallyCloseTo(Rotation other) { public boolean isReallyCloseTo(Rotation other) {
float yawDiff = Math.abs(this.yaw - other.yaw); // you cant fool me return yawIsReallyClose(other) && Math.abs(this.pitch - other.pitch) < 0.01;
return (yawDiff < 0.01 || yawDiff > 359.9) && Math.abs(this.pitch - other.pitch) < 0.01; }
public boolean yawIsReallyClose(Rotation other) {
float yawDiff = Math.abs(normalizeYaw(yaw) - normalizeYaw(other.yaw)); // you cant fool me
return (yawDiff < 0.01 || yawDiff > 359.99);
} }
/** /**
@@ -147,4 +151,9 @@ public class Rotation {
} }
return newYaw; return newYaw;
} }
@Override
public String toString() {
return "Yaw: " + yaw + ", Pitch: " + pitch;
}
} }
@@ -78,6 +78,9 @@ public final class RotationUtils {
* @return The wrapped angles * @return The wrapped angles
*/ */
public static Rotation wrapAnglesToRelative(Rotation current, Rotation target) { public static Rotation wrapAnglesToRelative(Rotation current, Rotation target) {
if (current.yawIsReallyClose(target)) {
return new Rotation(current.getYaw(), target.getPitch());
}
return target.subtract(current).normalize().add(current); return target.subtract(current).normalize().add(current);
} }
@@ -102,7 +105,7 @@ public final class RotationUtils {
* @param dest The destination position * @param dest The destination position
* @return The rotation from the origin to the destination * @return The rotation from the origin to the destination
*/ */
public static Rotation calcRotationFromVec3d(Vec3d orig, Vec3d dest) { private static Rotation calcRotationFromVec3d(Vec3d orig, Vec3d dest) {
double[] delta = {orig.x - dest.x, orig.y - dest.y, orig.z - dest.z}; double[] delta = {orig.x - dest.x, orig.y - dest.y, orig.z - dest.z};
double yaw = MathHelper.atan2(delta[0], -delta[2]); double yaw = MathHelper.atan2(delta[0], -delta[2]);
double dist = Math.sqrt(delta[0] * delta[0] + delta[2] * delta[2]); double dist = Math.sqrt(delta[0] * delta[0] + delta[2] * delta[2]);
@@ -196,7 +199,7 @@ public final class RotationUtils {
* @return The optional rotation * @return The optional rotation
*/ */
public static Optional<Rotation> reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos, double blockReachDistance) { public static Optional<Rotation> reachableOffset(Entity entity, BlockPos pos, Vec3d offsetPos, double blockReachDistance) {
Rotation rotation = calcRotationFromVec3d(entity.getPositionEyes(1.0F), offsetPos); Rotation rotation = calcRotationFromVec3d(entity.getPositionEyes(1.0F), offsetPos, new Rotation(entity.rotationYaw, entity.rotationPitch));
RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance); RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance);
//System.out.println(result); //System.out.println(result);
if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) {
@@ -27,10 +27,8 @@ import java.io.BufferedWriter;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.*;
import java.util.Collections; import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@@ -89,22 +87,8 @@ public class SettingsUtil {
public static synchronized void save(Settings settings) { public static synchronized void save(Settings settings) {
try (BufferedWriter out = Files.newBufferedWriter(SETTINGS_PATH)) { try (BufferedWriter out = Files.newBufferedWriter(SETTINGS_PATH)) {
for (Settings.Setting setting : settings.allSettings) { for (Settings.Setting setting : modifiedSettings(settings)) {
if (setting.get() == null) { out.write(settingToString(setting) + "\n");
System.out.println("NULL SETTING?" + setting.getName());
continue;
}
if (setting.getName().equals("logger")) {
continue; // NO
}
if (setting.value == setting.defaultValue) {
continue;
}
SettingsIO io = map.get(setting.getValueClass());
if (io == null) {
throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting + " " + setting.getName());
}
out.write(setting.getName() + " " + io.toString.apply(setting.get()) + "\n");
} }
} catch (Exception ex) { } catch (Exception ex) {
System.out.println("Exception thrown while saving Baritone settings!"); System.out.println("Exception thrown while saving Baritone settings!");
@@ -112,7 +96,36 @@ public class SettingsUtil {
} }
} }
private static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException { public static List<Settings.Setting> modifiedSettings(Settings settings) {
List<Settings.Setting> modified = new ArrayList<>();
for (Settings.Setting setting : settings.allSettings) {
if (setting.get() == null) {
System.out.println("NULL SETTING?" + setting.getName());
continue;
}
if (setting.getName().equals("logger")) {
continue; // NO
}
if (setting.value == setting.defaultValue) {
continue;
}
modified.add(setting);
}
return modified;
}
public static String settingToString(Settings.Setting setting) throws IllegalStateException {
if (setting.getName().equals("logger")) {
return "logger";
}
SettingsIO io = map.get(setting.getValueClass());
if (io == null) {
throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting.getName());
}
return setting.getName() + " " + io.toString.apply(setting.get());
}
public static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException {
Settings.Setting setting = settings.byLowerName.get(settingName); Settings.Setting setting = settings.byLowerName.get(settingName);
if (setting == null) { if (setting == null) {
throw new IllegalStateException("No setting by that name"); throw new IllegalStateException("No setting by that name");
@@ -22,27 +22,31 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ChunkRenderContainer; import net.minecraft.client.renderer.ChunkRenderContainer;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.chunk.RenderChunk; import net.minecraft.client.renderer.chunk.RenderChunk;
import net.minecraft.util.math.BlockPos;
import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GL14;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL11.*;
@Mixin(ChunkRenderContainer.class) @Mixin(ChunkRenderContainer.class)
public class MixinChunkRenderContainer { public class MixinChunkRenderContainer {
@Inject( @Redirect( // avoid creating CallbackInfo at all costs; this is called 40k times per second
method = "preRenderChunk", method = "preRenderChunk",
at = @At("HEAD") at = @At(
value = "INVOKE",
target = "net/minecraft/client/renderer/chunk/RenderChunk.getPosition()Lnet/minecraft/util/math/BlockPos;"
)
) )
private void preRenderChunk(RenderChunk renderChunkIn, CallbackInfo ci) { private BlockPos getPosition(RenderChunk renderChunkIn) {
if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) { if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) {
GlStateManager.enableAlpha(); GlStateManager.enableAlpha();
GlStateManager.enableBlend(); GlStateManager.enableBlend();
GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.get()); GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.get());
GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO); GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO);
} }
return renderChunkIn.getPosition();
} }
} }
@@ -20,6 +20,7 @@ package baritone.launch.mixins;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.chunk.ChunkRenderWorker; import net.minecraft.client.renderer.chunk.ChunkRenderWorker;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World; import net.minecraft.world.World;
@@ -42,7 +43,7 @@ public abstract class MixinChunkRenderWorker {
) )
) )
private boolean isChunkExisting(ChunkRenderWorker worker, BlockPos pos, World world) { private boolean isChunkExisting(ChunkRenderWorker worker, BlockPos pos, World world) {
if (Baritone.settings().renderCachedChunks.get()) { if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) {
Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone();
IPlayerContext ctx = baritone.getPlayerContext(); IPlayerContext ctx = baritone.getPlayerContext();
if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) {
@@ -18,6 +18,7 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.RotationMoveEvent; import baritone.api.event.events.RotationMoveEvent;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
@@ -55,8 +56,11 @@ public abstract class MixinEntityLivingBase extends Entity {
private void preMoveRelative(CallbackInfo ci) { private void preMoveRelative(CallbackInfo ci) {
// noinspection ConstantConditions // noinspection ConstantConditions
if (EntityPlayerSP.class.isInstance(this)) { if (EntityPlayerSP.class.isInstance(this)) {
this.jumpRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.JUMP, this.rotationYaw); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent); if (baritone != null) {
this.jumpRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.JUMP, this.rotationYaw);
baritone.getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent);
}
} }
} }
@@ -69,7 +73,7 @@ public abstract class MixinEntityLivingBase extends Entity {
) )
) )
private float overrideYaw(EntityLivingBase self) { private float overrideYaw(EntityLivingBase self) {
if (self instanceof EntityPlayerSP) { if (self instanceof EntityPlayerSP && BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this) != null) {
return this.jumpRotationEvent.getYaw(); return this.jumpRotationEvent.getYaw();
} }
return self.rotationYaw; return self.rotationYaw;
@@ -84,7 +88,7 @@ public abstract class MixinEntityLivingBase extends Entity {
) )
private void travel(EntityLivingBase self, float strafe, float up, float forward, float friction) { private void travel(EntityLivingBase self, float strafe, float up, float forward, float friction) {
// noinspection ConstantConditions // noinspection ConstantConditions
if (!EntityPlayerSP.class.isInstance(this)) { if (!EntityPlayerSP.class.isInstance(this) || BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this) == null) {
moveRelative(strafe, up, forward, friction); moveRelative(strafe, up, forward, friction);
return; return;
} }
@@ -19,7 +19,6 @@ package baritone.launch.mixins;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.behavior.IPathingBehavior;
import baritone.api.event.events.ChatEvent; import baritone.api.event.events.ChatEvent;
import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.SprintStateEvent; import baritone.api.event.events.SprintStateEvent;
@@ -48,7 +47,11 @@ public class MixinEntityPlayerSP {
) )
private void sendChatMessage(String msg, CallbackInfo ci) { private void sendChatMessage(String msg, CallbackInfo ci) {
ChatEvent event = new ChatEvent(msg); ChatEvent event = new ChatEvent(msg);
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onSendChatMessage(event); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone == null) {
return;
}
baritone.getGameEventHandler().onSendChatMessage(event);
if (event.isCancelled()) { if (event.isCancelled()) {
ci.cancel(); ci.cancel();
} }
@@ -64,7 +67,10 @@ public class MixinEntityPlayerSP {
) )
) )
private void onPreUpdate(CallbackInfo ci) { private void onPreUpdate(CallbackInfo ci) {
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.PRE)); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone != null) {
baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.PRE));
}
} }
@Inject( @Inject(
@@ -77,7 +83,10 @@ public class MixinEntityPlayerSP {
) )
) )
private void onPostUpdate(CallbackInfo ci) { private void onPostUpdate(CallbackInfo ci) {
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST)); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone != null) {
baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST));
}
} }
@Redirect( @Redirect(
@@ -88,8 +97,11 @@ public class MixinEntityPlayerSP {
) )
) )
private boolean isAllowFlying(PlayerCapabilities capabilities) { private boolean isAllowFlying(PlayerCapabilities capabilities) {
IPathingBehavior pathingBehavior = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getPathingBehavior(); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
return !pathingBehavior.isPathing() && capabilities.allowFlying; if (baritone == null) {
return capabilities.allowFlying;
}
return !baritone.getPathingBehavior().isPathing() && capabilities.allowFlying;
} }
@Redirect( @Redirect(
@@ -100,8 +112,11 @@ public class MixinEntityPlayerSP {
) )
) )
private boolean isKeyDown(KeyBinding keyBinding) { private boolean isKeyDown(KeyBinding keyBinding) {
SprintStateEvent event = new SprintStateEvent();
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone == null) {
return keyBinding.isKeyDown();
}
SprintStateEvent event = new SprintStateEvent();
baritone.getGameEventHandler().onPlayerSprintState(event); baritone.getGameEventHandler().onPlayerSprintState(event);
if (event.getState() != null) { if (event.getState() != null) {
return event.getState(); return event.getState();
@@ -120,6 +135,9 @@ public class MixinEntityPlayerSP {
) )
) )
private void updateRidden(CallbackInfo cb) { private void updateRidden(CallbackInfo cb) {
((LookBehavior) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getLookBehavior()).pig(); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone != null) {
((LookBehavior) baritone.getLookBehavior()).pig();
}
} }
} }
@@ -20,6 +20,7 @@ package baritone.launch.mixins;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.utils.Helper; import baritone.utils.Helper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding; import net.minecraft.client.settings.KeyBinding;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
@@ -61,6 +62,11 @@ public class MixinKeyBinding {
private void isPressed(CallbackInfoReturnable<Boolean> cir) { private void isPressed(CallbackInfoReturnable<Boolean> cir) {
// only the primary baritone forces keys // only the primary baritone forces keys
Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this); Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this);
if (pressTime > 0 && (KeyBinding) (Object) this == Minecraft.getMinecraft().gameSettings.keyBindAttack && Baritone.settings().clickCancel.get() && BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().isPathing()) {
Helper.HELPER.logDirect("Cancelling path on left click since the clickCancel setting is enabled!");
BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().cancelEverything();
return;
}
if (force != null && !force && Baritone.settings().suppressClicks.get()) { // <-- cursed if (force != null && !force && Baritone.settings().suppressClicks.get()) { // <-- cursed
if (pressTime > 0) { if (pressTime > 0) {
Helper.HELPER.logDirect("You're trying to press this mouse button but I won't let you."); Helper.HELPER.logDirect("You're trying to press this mouse button but I won't let you.");
@@ -21,6 +21,7 @@ import baritone.Baritone;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.chunk.RenderChunk; import net.minecraft.client.renderer.chunk.RenderChunk;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.ChunkCache; import net.minecraft.world.ChunkCache;
@@ -46,7 +47,7 @@ public class MixinRenderChunk {
if (!chunkCache.isEmpty()) { if (!chunkCache.isEmpty()) {
return false; return false;
} }
if (Baritone.settings().renderCachedChunks.get()) { if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) {
Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone();
IPlayerContext ctx = baritone.getPlayerContext(); IPlayerContext ctx = baritone.getPlayerContext();
if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) {
@@ -75,7 +76,7 @@ public class MixinRenderChunk {
) )
) )
private IBlockState getBlockState(ChunkCache chunkCache, BlockPos pos) { private IBlockState getBlockState(ChunkCache chunkCache, BlockPos pos) {
if (Baritone.settings().renderCachedChunks.get()) { if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) {
Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone(); Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone();
IPlayerContext ctx = baritone.getPlayerContext(); IPlayerContext ctx = baritone.getPlayerContext();
if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) { if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) {
@@ -18,29 +18,30 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.Baritone; import baritone.Baritone;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderList; import net.minecraft.client.renderer.RenderList;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL11.*;
@Mixin(RenderList.class) @Mixin(RenderList.class)
public class MixinRenderList { public class MixinRenderList {
@Inject( @Redirect( // avoid creating CallbackInfo at all costs; this is called 40k times per second
method = "renderChunkLayer", method = "renderChunkLayer",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/renderer/GlStateManager.popMatrix()V" target = "net/minecraft/client/renderer/GlStateManager.popMatrix()V"
) )
) )
private void renderChunkLayer(CallbackInfo info) { private void popMatrix() {
if (Baritone.settings().renderCachedChunks.get()) { if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) {
// reset the blend func to normal (not dependent on constant alpha) // reset the blend func to normal (not dependent on constant alpha)
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
} }
GlStateManager.popMatrix();
} }
} }
@@ -18,29 +18,30 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.Baritone; import baritone.Baritone;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.VboRenderList; import net.minecraft.client.renderer.VboRenderList;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL11.*;
@Mixin(VboRenderList.class) @Mixin(VboRenderList.class)
public class MixinVboRenderList { public class MixinVboRenderList {
@Inject( @Redirect( // avoid creating CallbackInfo at all costs; this is called 40k times per second
method = "renderChunkLayer", method = "renderChunkLayer",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/renderer/GlStateManager.popMatrix()V" target = "net/minecraft/client/renderer/GlStateManager.popMatrix()V"
) )
) )
private void renderChunkLayer(CallbackInfo info) { private void popMatrix() {
if (Baritone.settings().renderCachedChunks.get()) { if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().getIntegratedServer() == null) {
// reset the blend func to normal (not dependent on constant alpha) // reset the blend func to normal (not dependent on constant alpha)
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
} }
GlStateManager.popMatrix();
} }
} }
+211 -210
View File
@@ -1,210 +1,211 @@
/* /*
* This file is part of Baritone. * This file is part of Baritone.
* *
* Baritone is free software: you can redistribute it and/or modify * 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 * 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 * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Baritone is distributed in the hope that it will be useful, * Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details. * GNU Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public License * You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>. * along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/ */
package baritone; package baritone;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.Settings; import baritone.api.Settings;
import baritone.api.event.listener.IEventBus; import baritone.api.event.listener.IEventBus;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import baritone.behavior.*; import baritone.behavior.*;
import baritone.cache.WorldProvider; import baritone.cache.WorldProvider;
import baritone.event.GameEventHandler; import baritone.event.GameEventHandler;
import baritone.process.CustomGoalProcess; import baritone.process.CustomGoalProcess;
import baritone.process.FollowProcess; import baritone.process.FollowProcess;
import baritone.process.GetToBlockProcess; import baritone.process.GetToBlockProcess;
import baritone.process.MineProcess; import baritone.process.MineProcess;
import baritone.utils.*; import baritone.utils.*;
import baritone.utils.player.PrimaryPlayerContext; import baritone.utils.player.PrimaryPlayerContext;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.SynchronousQueue; import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* @author Brady * @author Brady
* @since 7/31/2018 * @since 7/31/2018
*/ */
public class Baritone implements IBaritone { public class Baritone implements IBaritone {
private static ThreadPoolExecutor threadPool; private static ThreadPoolExecutor threadPool;
private static File dir; private static File dir;
static { static {
threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>());
dir = new File(Minecraft.getMinecraft().gameDir, "baritone"); dir = new File(Minecraft.getMinecraft().gameDir, "baritone");
if (!Files.exists(dir.toPath())) { if (!Files.exists(dir.toPath())) {
try { try {
Files.createDirectories(dir.toPath()); Files.createDirectories(dir.toPath());
} catch (IOException ignored) {} } catch (IOException ignored) {}
} }
} }
/** /**
* Whether or not {@link Baritone#init()} has been called yet * Whether or not {@link Baritone#init()} has been called yet
*/ */
private boolean initialized; private boolean initialized;
private GameEventHandler gameEventHandler; private GameEventHandler gameEventHandler;
private List<Behavior> behaviors; private List<Behavior> behaviors;
private PathingBehavior pathingBehavior; private PathingBehavior pathingBehavior;
private LookBehavior lookBehavior; private LookBehavior lookBehavior;
private MemoryBehavior memoryBehavior; private MemoryBehavior memoryBehavior;
private InputOverrideHandler inputOverrideHandler; private InputOverrideHandler inputOverrideHandler;
private FollowProcess followProcess; private FollowProcess followProcess;
private MineProcess mineProcess; private MineProcess mineProcess;
private GetToBlockProcess getToBlockProcess; private GetToBlockProcess getToBlockProcess;
private CustomGoalProcess customGoalProcess; private CustomGoalProcess customGoalProcess;
private PathingControlManager pathingControlManager; private PathingControlManager pathingControlManager;
private IPlayerContext playerContext; private IPlayerContext playerContext;
private WorldProvider worldProvider; private WorldProvider worldProvider;
public BlockStateInterface bsi; public BlockStateInterface bsi;
Baritone() { Baritone() {
this.gameEventHandler = new GameEventHandler(this); this.gameEventHandler = new GameEventHandler(this);
} }
public synchronized void init() { @Override
if (initialized) { public synchronized void init() {
return; if (initialized) {
} return;
}
// Define this before behaviors try and get it, or else it will be null and the builds will fail!
this.playerContext = PrimaryPlayerContext.INSTANCE; // Define this before behaviors try and get it, or else it will be null and the builds will fail!
this.playerContext = PrimaryPlayerContext.INSTANCE;
this.behaviors = new ArrayList<>();
{ this.behaviors = new ArrayList<>();
// the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist {
pathingBehavior = new PathingBehavior(this); // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist
lookBehavior = new LookBehavior(this); pathingBehavior = new PathingBehavior(this);
memoryBehavior = new MemoryBehavior(this); lookBehavior = new LookBehavior(this);
new InventoryBehavior(this); memoryBehavior = new MemoryBehavior(this);
inputOverrideHandler = new InputOverrideHandler(this); new InventoryBehavior(this);
new ExampleBaritoneControl(this); inputOverrideHandler = new InputOverrideHandler(this);
} new ExampleBaritoneControl(this);
}
this.pathingControlManager = new PathingControlManager(this);
{ this.pathingControlManager = new PathingControlManager(this);
followProcess = new FollowProcess(this); {
mineProcess = new MineProcess(this); followProcess = new FollowProcess(this);
customGoalProcess = new CustomGoalProcess(this); // very high iq mineProcess = new MineProcess(this);
getToBlockProcess = new GetToBlockProcess(this); customGoalProcess = new CustomGoalProcess(this); // very high iq
} getToBlockProcess = new GetToBlockProcess(this);
}
this.worldProvider = new WorldProvider();
this.worldProvider = new WorldProvider();
if (BaritoneAutoTest.ENABLE_AUTO_TEST) {
this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE); if (BaritoneAutoTest.ENABLE_AUTO_TEST) {
} this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE);
}
this.initialized = true;
} this.initialized = true;
}
@Override
public PathingControlManager getPathingControlManager() { @Override
return this.pathingControlManager; public PathingControlManager getPathingControlManager() {
} return this.pathingControlManager;
}
public List<Behavior> getBehaviors() {
return this.behaviors; public List<Behavior> getBehaviors() {
} return this.behaviors;
}
public void registerBehavior(Behavior behavior) {
this.behaviors.add(behavior); public void registerBehavior(Behavior behavior) {
this.gameEventHandler.registerEventListener(behavior); this.behaviors.add(behavior);
} this.gameEventHandler.registerEventListener(behavior);
}
@Override
public InputOverrideHandler getInputOverrideHandler() { @Override
return this.inputOverrideHandler; public InputOverrideHandler getInputOverrideHandler() {
} return this.inputOverrideHandler;
}
@Override
public CustomGoalProcess getCustomGoalProcess() { // Iffy @Override
return this.customGoalProcess; public CustomGoalProcess getCustomGoalProcess() { // Iffy
} return this.customGoalProcess;
}
@Override
public GetToBlockProcess getGetToBlockProcess() { // Iffy @Override
return this.getToBlockProcess; public GetToBlockProcess getGetToBlockProcess() { // Iffy
} return this.getToBlockProcess;
}
@Override
public IPlayerContext getPlayerContext() { @Override
return this.playerContext; public IPlayerContext getPlayerContext() {
} return this.playerContext;
}
public MemoryBehavior getMemoryBehavior() {
return this.memoryBehavior; public MemoryBehavior getMemoryBehavior() {
} return this.memoryBehavior;
}
@Override
public FollowProcess getFollowProcess() { @Override
return this.followProcess; public FollowProcess getFollowProcess() {
} return this.followProcess;
}
@Override
public LookBehavior getLookBehavior() { @Override
return this.lookBehavior; public LookBehavior getLookBehavior() {
} return this.lookBehavior;
}
@Override
public MineProcess getMineProcess() { @Override
return this.mineProcess; public MineProcess getMineProcess() {
} return this.mineProcess;
}
@Override
public PathingBehavior getPathingBehavior() { @Override
return this.pathingBehavior; public PathingBehavior getPathingBehavior() {
} return this.pathingBehavior;
}
@Override
public WorldProvider getWorldProvider() { @Override
return this.worldProvider; public WorldProvider getWorldProvider() {
} return this.worldProvider;
}
@Override
public IEventBus getGameEventHandler() { @Override
return this.gameEventHandler; public IEventBus getGameEventHandler() {
} return this.gameEventHandler;
}
public static Settings settings() {
return BaritoneAPI.getSettings(); public static Settings settings() {
} return BaritoneAPI.getSettings();
}
public static File getDir() {
return dir; public static File getDir() {
} return dir;
}
public static Executor getExecutor() {
return threadPool; public static Executor getExecutor() {
} return threadPool;
} }
}
@@ -103,13 +103,13 @@ public final class LookBehavior extends Behavior implements ILookBehavior {
@Override @Override
public void onPlayerRotationMove(RotationMoveEvent event) { public void onPlayerRotationMove(RotationMoveEvent event) {
if (this.target != null && !this.force) { if (this.target != null) {
event.setYaw(this.target.getYaw()); event.setYaw(this.target.getYaw());
// If we have antiCheatCompatibility on, we're going to use the target value later in onPlayerUpdate() // If we have antiCheatCompatibility on, we're going to use the target value later in onPlayerUpdate()
// Also the type has to be MOTION_UPDATE because that is called after JUMP // Also the type has to be MOTION_UPDATE because that is called after JUMP
if (!Baritone.settings().antiCheatCompatibility.get() && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE) { if (!Baritone.settings().antiCheatCompatibility.get() && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE && !this.force) {
this.target = null; this.target = null;
} }
} }
@@ -61,6 +61,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
private boolean lastAutoJump; private boolean lastAutoJump;
private BlockPos expectedSegmentStart;
private final LinkedBlockingQueue<PathEvent> toDispatch = new LinkedBlockingQueue<>(); private final LinkedBlockingQueue<PathEvent> toDispatch = new LinkedBlockingQueue<>();
public PathingBehavior(Baritone baritone) { public PathingBehavior(Baritone baritone) {
@@ -88,6 +90,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
baritone.getPathingControlManager().cancelEverything(); baritone.getPathingControlManager().cancelEverything();
return; return;
} }
expectedSegmentStart = pathStart();
baritone.getPathingControlManager().preTick(); baritone.getPathingControlManager().preTick();
tickPath(); tickPath();
dispatchEvents(); dispatchEvents();
@@ -111,11 +114,27 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
cancelRequested = false; cancelRequested = false;
baritone.getInputOverrideHandler().clearAllKeys(); baritone.getInputOverrideHandler().clearAllKeys();
} }
if (current == null) {
return;
}
safeToCancel = current.onTick();
synchronized (pathPlanLock) { synchronized (pathPlanLock) {
synchronized (pathCalcLock) {
if (inProgress != null) {
// we are calculating
// are we calculating the right thing though? 🤔
BetterBlockPos calcFrom = inProgress.getStart();
Optional<IPath> currentBest = inProgress.bestPathSoFar();
if ((current == null || !current.getPath().getDest().equals(calcFrom)) // if current ends in inProgress's start, then we're ok
&& !calcFrom.equals(ctx.playerFeet()) && !calcFrom.equals(expectedSegmentStart) // if current starts in our playerFeet or pathStart, then we're ok
&& (!currentBest.isPresent() || (!currentBest.get().positions().contains(ctx.playerFeet()) && !currentBest.get().positions().contains(expectedSegmentStart))) // if
) {
// when it was *just* started, currentBest will be empty so we need to also check calcFrom since that's always present
inProgress.cancel(); // cancellation doesn't dispatch any events
inProgress = null; // this is safe since we hold both locks
}
}
}
if (current == null) {
return;
}
safeToCancel = current.onTick();
if (current.failed() || current.finished()) { if (current.failed() || current.finished()) {
current = null; current = null;
if (goal == null || goal.isInGoal(ctx.playerFeet())) { if (goal == null || goal.isInGoal(ctx.playerFeet())) {
@@ -124,7 +143,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
next = null; next = null;
return; return;
} }
if (next != null && !next.getPath().positions().contains(ctx.playerFeet()) && !next.getPath().positions().contains(pathStart())) { // can contain either one if (next != null && !next.getPath().positions().contains(ctx.playerFeet()) && !next.getPath().positions().contains(expectedSegmentStart)) { // can contain either one
// if the current path failed, we may not actually be on the next one, so make sure // if the current path failed, we may not actually be on the next one, so make sure
logDebug("Discarding next path as it does not contain current position"); logDebug("Discarding next path as it does not contain current position");
// for example if we had a nicely planned ahead path that starts where current ends // for example if we had a nicely planned ahead path that starts where current ends
@@ -146,23 +165,12 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
// at this point, current just ended, but we aren't in the goal and have no plan for the future // at this point, current just ended, but we aren't in the goal and have no plan for the future
synchronized (pathCalcLock) { synchronized (pathCalcLock) {
if (inProgress != null) { if (inProgress != null) {
// we are calculating queuePathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING);
// are we calculating the right thing though? 🤔 return;
BetterBlockPos calcFrom = inProgress.getStart();
// if current just succeeded, we should be standing in calcFrom, so that's cool and good
// but if current just failed, we should discard this calculation since it doesn't start from where we're standing
if (calcFrom.equals(ctx.playerFeet()) || calcFrom.equals(pathStart())) {
// cool and good
queuePathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING);
return;
}
// oh noes
inProgress.cancel(); // cancellation doesn't dispatch any events
inProgress = null; // this is safe since we hold both locks
} }
// we aren't calculating // we aren't calculating
queuePathEvent(PathEvent.CALC_STARTED); queuePathEvent(PathEvent.CALC_STARTED);
findPathInNewThread(pathStart(), true); findPathInNewThread(expectedSegmentStart, true);
} }
return; return;
} }
@@ -193,7 +201,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
// and this path doesn't get us all the way there // and this path doesn't get us all the way there
return; return;
} }
if (ticksRemainingInSegment(false).get() < Baritone.settings().planningTickLookAhead.get()) { if (ticksRemainingInSegment(false).get() < Baritone.settings().planningTickLookahead.get()) {
// and this path has 7.5 seconds or less left // and this path has 7.5 seconds or less left
// don't include the current movement so a very long last movement (e.g. descend) doesn't trip it up // don't include the current movement so a very long last movement (e.g. descend) doesn't trip it up
// if we actually included current, it wouldn't start planning ahead until the last movement was done, if the last movement took more than 7.5 seconds on its own // if we actually included current, it wouldn't start planning ahead until the last movement was done, if the last movement took more than 7.5 seconds on its own
@@ -298,12 +306,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
public void secretInternalSegmentCancel() { public void secretInternalSegmentCancel() {
queuePathEvent(PathEvent.CANCELED); queuePathEvent(PathEvent.CANCELED);
synchronized (pathPlanLock) { synchronized (pathPlanLock) {
current = null; if (current != null) {
next = null; current = null;
next = null;
baritone.getInputOverrideHandler().clearAllKeys();
getInProgress().ifPresent(AbstractNodeCostSearch::cancel);
baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock();
}
} }
baritone.getInputOverrideHandler().clearAllKeys();
getInProgress().ifPresent(AbstractNodeCostSearch::cancel);
baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock();
} }
public void forceCancel() { // NOT exposed on public api public void forceCancel() { // NOT exposed on public api
@@ -335,7 +345,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
return false; return false;
} }
queuePathEvent(PathEvent.CALC_STARTED); queuePathEvent(PathEvent.CALC_STARTED);
findPathInNewThread(pathStart(), true); findPathInNewThread(expectedSegmentStart, true);
return true; return true;
} }
} }
@@ -375,7 +385,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
} }
if (MovementHelper.canWalkOn(ctx, possibleSupport.down()) && MovementHelper.canWalkThrough(ctx, possibleSupport) && MovementHelper.canWalkThrough(ctx, possibleSupport.up())) { if (MovementHelper.canWalkOn(ctx, possibleSupport.down()) && MovementHelper.canWalkThrough(ctx, possibleSupport) && MovementHelper.canWalkThrough(ctx, possibleSupport.up())) {
// this is plausible // this is plausible
logDebug("Faking path start assuming player is standing off the edge of a block"); //logDebug("Faking path start assuming player is standing off the edge of a block");
return possibleSupport; return possibleSupport;
} }
} }
@@ -384,7 +394,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
// !onGround // !onGround
// we're in the middle of a jump // we're in the middle of a jump
if (MovementHelper.canWalkOn(ctx, feet.down().down())) { if (MovementHelper.canWalkOn(ctx, feet.down().down())) {
logDebug("Faking path start assuming player is midair and falling"); //logDebug("Faking path start assuming player is midair and falling");
return feet.down(); return feet.down();
} }
} }
@@ -438,8 +448,12 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
Optional<PathExecutor> executor = calcResult.getPath().map(p -> new PathExecutor(PathingBehavior.this, p)); Optional<PathExecutor> executor = calcResult.getPath().map(p -> new PathExecutor(PathingBehavior.this, p));
if (current == null) { if (current == null) {
if (executor.isPresent()) { if (executor.isPresent()) {
queuePathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING); if (executor.get().getPath().positions().contains(expectedSegmentStart)) {
current = executor.get(); queuePathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING);
current = executor.get();
} else {
logDebug("Warning: discarding orphan path segment with incorrect start");
}
} else { } else {
if (calcResult.getType() != PathCalculationResult.Type.CANCELLATION && calcResult.getType() != PathCalculationResult.Type.EXCEPTION) { if (calcResult.getType() != PathCalculationResult.Type.CANCELLATION && calcResult.getType() != PathCalculationResult.Type.EXCEPTION) {
// don't dispatch CALC_FAILED on cancellation // don't dispatch CALC_FAILED on cancellation
@@ -449,8 +463,12 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
} else { } else {
if (next == null) { if (next == null) {
if (executor.isPresent()) { if (executor.isPresent()) {
queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_FINISHED); if (executor.get().getPath().getSrc().equals(current.getPath().getDest())) {
next = executor.get(); queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_FINISHED);
next = executor.get();
} else {
logDebug("Warning: discarding orphan next segment with incorrect start");
}
} else { } else {
queuePathEvent(PathEvent.NEXT_CALC_FAILED); queuePathEvent(PathEvent.NEXT_CALC_FAILED);
} }
+1
View File
@@ -85,6 +85,7 @@ public final class CachedChunk {
temp.add(Blocks.END_GATEWAY); temp.add(Blocks.END_GATEWAY);
temp.add(Blocks.WEB); temp.add(Blocks.WEB);
temp.add(Blocks.NETHER_WART); temp.add(Blocks.NETHER_WART);
temp.add(Blocks.LADDER);
BLOCKS_TO_KEEP_TRACK_OF = Collections.unmodifiableSet(temp); BLOCKS_TO_KEEP_TRACK_OF = Collections.unmodifiableSet(temp);
} }
+1 -1
View File
@@ -45,7 +45,7 @@ public final class CachedWorld implements ICachedWorld, Helper {
/** /**
* The maximum number of regions in any direction from (0,0) * The maximum number of regions in any direction from (0,0)
*/ */
private static final int REGION_MAX = 58594; private static final int REGION_MAX = 30_000_000 / 512 + 1;
/** /**
* A map of all of the cached regions. * A map of all of the cached regions.
@@ -50,7 +50,9 @@ public final class GameEventHandler implements IEventBus, Helper {
if (event.getType() == TickEvent.Type.IN) { if (event.getType() == TickEvent.Type.IN) {
try { try {
baritone.bsi = new BlockStateInterface(baritone.getPlayerContext(), true); baritone.bsi = new BlockStateInterface(baritone.getPlayerContext(), true);
} catch (Exception ex) {} } catch (Exception ex) {
baritone.bsi = null;
}
} else { } else {
baritone.bsi = null; baritone.bsi = null;
} }
@@ -160,7 +160,7 @@ public abstract class Movement implements IMovement, MovementHelper {
//i dont care if theres snow in the way!!!!!!! //i dont care if theres snow in the way!!!!!!!
//you dont own me!!!! //you dont own me!!!!
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.player().getPositionEyes(1.0F), state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.player().getPositionEyes(1.0F),
VecUtils.getBlockPosCenter(blockPos)), true) VecUtils.getBlockPosCenter(blockPos), ctx.playerRotations()), true)
); );
// don't check selectedblock on this one, this is a fallback when we can't see any face directly, it's intended to be breaking the "incorrect" block // don't check selectedblock on this one, this is a fallback when we can't see any face directly, it's intended to be breaking the "incorrect" block
state.setInput(Input.CLICK_LEFT, true); state.setInput(Input.CLICK_LEFT, true);
@@ -439,11 +439,10 @@ public interface MovementHelper extends ActionCosts, Helper {
} }
static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) { static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) {
EntityPlayerSP player = ctx.player();
state.setTarget(new MovementTarget( state.setTarget(new MovementTarget(
new Rotation(RotationUtils.calcRotationFromVec3d(player.getPositionEyes(1.0F), new Rotation(RotationUtils.calcRotationFromVec3d(ctx.playerHead(),
VecUtils.getBlockPosCenter(pos), VecUtils.getBlockPosCenter(pos),
new Rotation(player.rotationYaw, player.rotationPitch)).getYaw(), player.rotationPitch), ctx.playerRotations()).getYaw(), ctx.player().rotationPitch),
false false
)).setInput(Input.MOVE_FORWARD, true); )).setInput(Input.MOVE_FORWARD, true);
} }
@@ -181,14 +181,21 @@ public class MovementAscend extends Movement {
return state; return state;
} }
if (headBonkClear()) {
return state.setInput(Input.JUMP, true);
}
int xAxis = Math.abs(src.getX() - dest.getX()); // either 0 or 1 int xAxis = Math.abs(src.getX() - dest.getX()); // either 0 or 1
int zAxis = Math.abs(src.getZ() - dest.getZ()); // either 0 or 1 int zAxis = Math.abs(src.getZ() - dest.getZ()); // either 0 or 1
double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ); double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ); double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
double lateralMotion = xAxis * ctx.player().motionZ + zAxis * ctx.player().motionX;
if (Math.abs(lateralMotion) > 0.1) {
return state;
}
if (headBonkClear()) {
return state.setInput(Input.JUMP, true);
}
// System.out.println(flatDistToNext + " " + sideDist); // System.out.println(flatDistToNext + " " + sideDist);
if (flatDistToNext > 1.2 || sideDist > 0.2) { if (flatDistToNext > 1.2 || sideDist > 0.2) {
return state; return state;
@@ -200,7 +207,7 @@ public class MovementAscend extends Movement {
return state.setInput(Input.JUMP, true); return state.setInput(Input.JUMP, true);
} }
private boolean headBonkClear() { public boolean headBonkClear() {
BetterBlockPos startUp = src.up(2); BetterBlockPos startUp = src.up(2);
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
BetterBlockPos check = startUp.offset(EnumFacing.byHorizontalIndex(i)); BetterBlockPos check = startUp.offset(EnumFacing.byHorizontalIndex(i));
@@ -245,7 +245,7 @@ public class MovementDescend extends Movement {
// (dest - src) + dest is offset 1 more in the same direction // (dest - src) + dest is offset 1 more in the same direction
// so it's the block we'd need to worry about running into if we decide to sprint straight through this descend // so it's the block we'd need to worry about running into if we decide to sprint straight through this descend
BlockPos into = dest.subtract(src.down()).add(dest); BlockPos into = dest.subtract(src.down()).add(dest);
if (!MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into)) && MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into).up()) && MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into).up(2))) { if (skipToAscend()) {
// if dest extends into can't walk through, but the two above are can walk through, then we can overshoot and glitch in that weird way // if dest extends into can't walk through, but the two above are can walk through, then we can overshoot and glitch in that weird way
return true; return true;
} }
@@ -256,4 +256,9 @@ public class MovementDescend extends Movement {
} }
return false; return false;
} }
public boolean skipToAscend() {
BlockPos into = dest.subtract(src.down()).add(dest);
return !MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into)) && MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into).up()) && MovementHelper.canWalkThrough(ctx, new BetterBlockPos(into).up(2));
}
} }
@@ -17,6 +17,7 @@
package baritone.pathing.movement.movements; package baritone.pathing.movement.movements;
import baritone.Baritone;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus; import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
@@ -181,7 +182,7 @@ public class MovementDiagonal extends Movement {
} }
public boolean sprint() { public boolean sprint() {
if (MovementHelper.isLiquid(ctx, ctx.playerFeet())) { if (MovementHelper.isLiquid(ctx, ctx.playerFeet()) && !Baritone.settings().sprintInWater.get()) {
return false; return false;
} }
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
@@ -78,7 +78,7 @@ public class MovementFall extends Movement {
} }
BlockPos playerFeet = ctx.playerFeet(); BlockPos playerFeet = ctx.playerFeet();
Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)); Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations());
Rotation targetRotation = null; Rotation targetRotation = null;
Block destBlock = ctx.world().getBlockState(dest).getBlock(); Block destBlock = ctx.world().getBlockState(dest).getBlock();
boolean isWater = destBlock == Blocks.WATER || destBlock == Blocks.FLOWING_WATER; boolean isWater = destBlock == Blocks.WATER || destBlock == Blocks.FLOWING_WATER;
@@ -141,7 +141,7 @@ public class MovementFall extends Movement {
} }
if (targetRotation == null) { if (targetRotation == null) {
Vec3d destCenterOffset = new Vec3d(destCenter.x + 0.125 * avoid.getX(), destCenter.y, destCenter.z + 0.125 * avoid.getZ()); Vec3d destCenterOffset = new Vec3d(destCenter.x + 0.125 * avoid.getX(), destCenter.y, destCenter.z + 0.125 * avoid.getZ());
state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), destCenterOffset), false)); state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), destCenterOffset, ctx.playerRotations()), false));
} }
return state; return state;
} }
@@ -151,7 +151,7 @@ public class MovementPillar extends Movement {
IBlockState fromDown = BlockStateInterface.get(ctx, src); IBlockState fromDown = BlockStateInterface.get(ctx, src);
if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(ctx, dest)) { if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(ctx, dest)) {
// stay centered while swimming up a water column // stay centered while swimming up a water column
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)), false)); state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()), false));
Vec3d destCenter = VecUtils.getBlockPosCenter(dest); Vec3d destCenter = VecUtils.getBlockPosCenter(dest);
if (Math.abs(ctx.player().posX - destCenter.x) > 0.2 || Math.abs(ctx.player().posZ - destCenter.z) > 0.2) { if (Math.abs(ctx.player().posX - destCenter.x) > 0.2 || Math.abs(ctx.player().posZ - destCenter.z) > 0.2) {
state.setInput(Input.MOVE_FORWARD, true); state.setInput(Input.MOVE_FORWARD, true);
@@ -174,11 +174,11 @@ public class MovementTraverse extends Movement {
// combine the yaw to the center of the destination, and the pitch to the specific block we're trying to break // combine the yaw to the center of the destination, and the pitch to the specific block we're trying to break
// it's safe to do this since the two blocks we break (in a traverse) are right on top of each other and so will have the same yaw // it's safe to do this since the two blocks we break (in a traverse) are right on top of each other and so will have the same yaw
float yawToDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), dest)).getYaw(); float yawToDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), dest), ctx.playerRotations()).getYaw();
float pitchToBreak = state.getTarget().getRotation().get().getPitch(); float pitchToBreak = state.getTarget().getRotation().get().getPitch();
state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true)); state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true));
return state.setInput(Input.MOVE_FORWARD, true); return state.setInput(Input.MOVE_FORWARD, true).setInput(Input.SPRINT, true);
} }
//sneak may have been set to true in the PREPPING state while mining an adjacent block //sneak may have been set to true in the PREPPING state while mining an adjacent block
@@ -198,7 +198,7 @@ public class MovementTraverse extends Movement {
isDoorActuallyBlockingUs = true; isDoorActuallyBlockingUs = true;
} }
if (isDoorActuallyBlockingUs && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { if (isDoorActuallyBlockingUs && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) {
return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0])), true)) return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0]), ctx.playerRotations()), true))
.setInput(Input.CLICK_RIGHT, true); .setInput(Input.CLICK_RIGHT, true);
} }
} }
@@ -212,7 +212,7 @@ public class MovementTraverse extends Movement {
} }
if (blocked != null) { if (blocked != null) {
return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), blocked)), true)) return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), blocked), ctx.playerRotations()), true))
.setInput(Input.CLICK_RIGHT, true); .setInput(Input.CLICK_RIGHT, true);
} }
} }
@@ -234,7 +234,7 @@ public class MovementTraverse extends Movement {
BlockPos into = dest.subtract(src).add(dest); BlockPos into = dest.subtract(src).add(dest);
Block intoBelow = BlockStateInterface.get(ctx, into).getBlock(); Block intoBelow = BlockStateInterface.get(ctx, into).getBlock();
Block intoAbove = BlockStateInterface.get(ctx, into.up()).getBlock(); Block intoAbove = BlockStateInterface.get(ctx, into.up()).getBlock();
if (wasTheBridgeBlockAlwaysThere && !MovementHelper.isLiquid(ctx, ctx.playerFeet()) && !MovementHelper.avoidWalkingInto(intoBelow) && !MovementHelper.avoidWalkingInto(intoAbove)) { if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, ctx.playerFeet()) || Baritone.settings().sprintInWater.get()) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) {
state.setInput(Input.SPRINT, true); state.setInput(Input.SPRINT, true);
} }
Block destDown = BlockStateInterface.get(ctx, dest.down()).getBlock(); Block destDown = BlockStateInterface.get(ctx, dest.down()).getBlock();
@@ -25,6 +25,7 @@ import baritone.api.pathing.movement.MovementStatus;
import baritone.api.pathing.path.IPathExecutor; import baritone.api.pathing.path.IPathExecutor;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import baritone.api.utils.RotationUtils;
import baritone.api.utils.VecUtils; import baritone.api.utils.VecUtils;
import baritone.api.utils.input.Input; import baritone.api.utils.input.Input;
import baritone.behavior.PathingBehavior; import baritone.behavior.PathingBehavior;
@@ -39,6 +40,8 @@ import net.minecraft.block.BlockLiquid;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.util.Tuple; import net.minecraft.util.Tuple;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.Vec3i;
import java.util.*; import java.util.*;
@@ -103,39 +106,31 @@ public class PathExecutor implements IPathExecutor, Helper {
} }
BetterBlockPos whereShouldIBe = path.positions().get(pathPosition); BetterBlockPos whereShouldIBe = path.positions().get(pathPosition);
BetterBlockPos whereAmI = ctx.playerFeet(); BetterBlockPos whereAmI = ctx.playerFeet();
if (!whereShouldIBe.equals(whereAmI)) { if (!whereShouldIBe.equals(whereAmI) && !Blocks.AIR.equals(BlockStateInterface.getBlock(ctx, whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip
for (int i = 0; i < pathPosition - 1 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks
if (pathPosition == 0 && whereAmI.equals(whereShouldIBe.up()) && Math.abs(ctx.player().motionY) < 0.1 && !(path.movements().get(0) instanceof MovementAscend) && !(path.movements().get(0) instanceof MovementPillar)) { if (whereAmI.equals(path.positions().get(i))) {
// avoid the Wrong Y coordinate bug logDebug("Skipping back " + (pathPosition - i) + " steps, to " + i);
// TODO add a timer here int previousPos = pathPosition;
new MovementDownward(behavior.baritone, whereAmI, whereShouldIBe).update(); pathPosition = Math.max(i - 1, 0); // previous step might not actually be done
return false; for (int j = pathPosition; j <= previousPos; j++) {
} path.movements().get(j).reset();
if (!Blocks.AIR.equals(BlockStateInterface.getBlock(ctx, whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip
for (int i = 0; i < pathPosition - 1 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks
if (whereAmI.equals(path.positions().get(i))) {
logDebug("Skipping back " + (pathPosition - i) + " steps, to " + i);
int previousPos = pathPosition;
pathPosition = Math.max(i - 1, 0); // previous step might not actually be done
for (int j = pathPosition; j <= previousPos; j++) {
path.movements().get(j).reset();
}
onChangeInPathPosition();
return false;
} }
onChangeInPathPosition();
onTick();
return false;
} }
for (int i = pathPosition + 3; i < path.length(); i++) { //dont check pathPosition+1. the movement tells us when it's done (e.g. sneak placing) }
// also don't check pathPosition+2 because reasons for (int i = pathPosition + 3; i < path.length(); i++) { //dont check pathPosition+1. the movement tells us when it's done (e.g. sneak placing)
if (whereAmI.equals(path.positions().get(i))) { // also don't check pathPosition+2 because reasons
if (i - pathPosition > 2) { if (whereAmI.equals(path.positions().get(i))) {
logDebug("Skipping forward " + (i - pathPosition) + " steps, to " + i); if (i - pathPosition > 2) {
} logDebug("Skipping forward " + (i - pathPosition) + " steps, to " + i);
//System.out.println("Double skip sundae");
pathPosition = i - 1;
onChangeInPathPosition();
return false;
} }
//System.out.println("Double skip sundae");
pathPosition = i - 1;
onChangeInPathPosition();
onTick();
return false;
} }
} }
} }
@@ -195,17 +190,17 @@ public class PathExecutor implements IPathExecutor, Helper {
continue; continue;
} }
Movement m = (Movement) path.movements().get(i); Movement m = (Movement) path.movements().get(i);
HashSet<BlockPos> prevBreak = new HashSet<>(m.toBreak(bsi)); List<BlockPos> prevBreak = m.toBreak(bsi);
HashSet<BlockPos> prevPlace = new HashSet<>(m.toPlace(bsi)); List<BlockPos> prevPlace = m.toPlace(bsi);
HashSet<BlockPos> prevWalkInto = new HashSet<>(m.toWalkInto(bsi)); List<BlockPos> prevWalkInto = m.toWalkInto(bsi);
m.resetBlockCache(); m.resetBlockCache();
if (!prevBreak.equals(new HashSet<>(m.toBreak(bsi)))) { if (!prevBreak.equals(m.toBreak(bsi))) {
recalcBP = true; recalcBP = true;
} }
if (!prevPlace.equals(new HashSet<>(m.toPlace(bsi)))) { if (!prevPlace.equals(m.toPlace(bsi))) {
recalcBP = true; recalcBP = true;
} }
if (!prevWalkInto.equals(new HashSet<>(m.toWalkInto(bsi)))) { if (!prevWalkInto.equals(m.toWalkInto(bsi))) {
recalcBP = true; recalcBP = true;
} }
} }
@@ -388,17 +383,34 @@ public class PathExecutor implements IPathExecutor, Helper {
if (!new CalculationContext(behavior.baritone).canSprint) { if (!new CalculationContext(behavior.baritone).canSprint) {
return false; return false;
} }
IMovement current = path.movements().get(pathPosition);
// traverse requests sprinting, so we need to do this check first
if (current instanceof MovementTraverse && pathPosition < path.length() - 3) {
IMovement next = path.movements().get(pathPosition + 1);
if (next instanceof MovementAscend && sprintableAscend(ctx, (MovementTraverse) current, (MovementAscend) next, path.movements().get(pathPosition + 2))) {
if (skipNow(ctx, current)) {
logDebug("Skipping traverse to straight ascend");
pathPosition++;
onChangeInPathPosition();
onTick();
behavior.baritone.getInputOverrideHandler().setInputForceState(Input.JUMP, true);
return true;
} else {
logDebug("Too far to the side to safely sprint ascend");
}
}
}
// if the movement requested sprinting, then we're done // if the movement requested sprinting, then we're done
if (requested) { if (requested) {
return true; return true;
} }
// however, descend doesn't request sprinting, beceause it doesn't know the context of what movement comes after it // however, descend and ascend don't request sprinting, because they don't know the context of what movement comes after it
IMovement current = path.movements().get(pathPosition);
if (current instanceof MovementDescend) { if (current instanceof MovementDescend) {
if (((MovementDescend) current).safeMode()) { if (((MovementDescend) current).safeMode() && !((MovementDescend) current).skipToAscend()) {
logDebug("Sprinting would be unsafe"); logDebug("Sprinting would be unsafe");
return false; return false;
} }
@@ -408,11 +420,13 @@ public class PathExecutor implements IPathExecutor, Helper {
if (next instanceof MovementAscend && current.getDirection().up().equals(next.getDirection().down())) { if (next instanceof MovementAscend && current.getDirection().up().equals(next.getDirection().down())) {
// a descend then an ascend in the same direction // a descend then an ascend in the same direction
pathPosition++; pathPosition++;
onChangeInPathPosition();
onTick();
// okay to skip clearKeys and / or onChangeInPathPosition here since this isn't possible to repeat, since it's asymmetric // okay to skip clearKeys and / or onChangeInPathPosition here since this isn't possible to repeat, since it's asymmetric
logDebug("Skipping descend to straight ascend"); logDebug("Skipping descend to straight ascend");
return true; return true;
} }
if (canSprintInto(ctx, current, next)) { if (canSprintFromDescendInto(ctx, current, next)) {
if (ctx.playerFeet().equals(current.getDest())) { if (ctx.playerFeet().equals(current.getDest())) {
pathPosition++; pathPosition++;
onChangeInPathPosition(); onChangeInPathPosition();
@@ -432,11 +446,123 @@ public class PathExecutor implements IPathExecutor, Helper {
return true; return true;
} }
} }
if (pathPosition < path.length() - 2 && prev instanceof MovementTraverse && sprintableAscend(ctx, (MovementTraverse) prev, (MovementAscend) current, path.movements().get(pathPosition + 1))) {
return true;
}
}
if (current instanceof MovementFall) {
Tuple<Vec3d, BlockPos> data = overrideFall((MovementFall) current);
if (data != null) {
BlockPos fallDest = data.getSecond();
if (!path.positions().contains(fallDest)) {
throw new IllegalStateException();
}
if (ctx.playerFeet().equals(fallDest)) {
pathPosition = path.positions().indexOf(fallDest);
onChangeInPathPosition();
onTick();
return true;
}
clearKeys();
behavior.baritone.getLookBehavior().updateTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), data.getFirst(), ctx.playerRotations()), false);
behavior.baritone.getInputOverrideHandler().setInputForceState(Input.MOVE_FORWARD, true);
return true;
}
} }
return false; return false;
} }
private static boolean canSprintInto(IPlayerContext ctx, IMovement current, IMovement next) { private Tuple<Vec3d, BlockPos> overrideFall(MovementFall movement) {
Vec3i dir = movement.getDirection();
if (dir.getY() < -3) {
return null;
}
if (!movement.toBreakCached.isEmpty()) {
return null; // it's breaking
}
Vec3i flatDir = new Vec3i(dir.getX(), 0, dir.getZ());
int i;
outer:
for (i = pathPosition + 1; i < path.length() - 1 && i < pathPosition + 3; i++) {
IMovement next = path.movements().get(i);
if (!(next instanceof MovementTraverse)) {
break;
}
if (!flatDir.equals(next.getDirection())) {
break;
}
for (int y = next.getDest().y; y <= movement.getSrc().y + 1; y++) {
BlockPos chk = new BlockPos(next.getDest().x, y, next.getDest().z);
if (!MovementHelper.fullyPassable(ctx.world().getBlockState(chk))) {
break outer;
}
}
if (!MovementHelper.canWalkOn(ctx, next.getDest().down())) {
break;
}
}
i--;
if (i == pathPosition) {
return null; // no valid extension exists
}
double len = i - pathPosition - 0.4;
return new Tuple<>(
new Vec3d(flatDir.getX() * len + movement.getDest().x + 0.5, movement.getDest().y, flatDir.getZ() * len + movement.getDest().z + 0.5),
movement.getDest().add(flatDir.getX() * (i - pathPosition), 0, flatDir.getZ() * (i - pathPosition)));
}
private static boolean skipNow(IPlayerContext ctx, IMovement current) {
double offTarget = Math.abs(current.getDirection().getX() * (current.getSrc().z + 0.5D - ctx.player().posZ)) + Math.abs(current.getDirection().getZ() * (current.getSrc().x + 0.5D - ctx.player().posX));
if (offTarget > 0.1) {
return false;
}
// we are centered
BlockPos headBonk = current.getSrc().subtract(current.getDirection()).up(2);
if (MovementHelper.fullyPassable(ctx.world().getBlockState(headBonk))) {
return true;
}
// wait 0.3
double flatDist = Math.abs(current.getDirection().getX() * (headBonk.getX() + 0.5D - ctx.player().posX)) + Math.abs(current.getDirection().getZ() * (headBonk.getZ() + 0.5 - ctx.player().posZ));
return flatDist > 0.8;
}
private static boolean sprintableAscend(IPlayerContext ctx, MovementTraverse current, MovementAscend next, IMovement nextnext) {
if (!Baritone.settings().sprintAscends.get()) {
return false;
}
if (!current.getDirection().equals(next.getDirection().down())) {
return false;
}
if (nextnext.getDirection().getX() != next.getDirection().getX() || nextnext.getDirection().getZ() != next.getDirection().getZ()) {
return false;
}
if (!MovementHelper.canWalkOn(ctx, current.getDest().down())) {
return false;
}
if (!MovementHelper.canWalkOn(ctx, next.getDest().down())) {
return false;
}
if (!next.toBreakCached.isEmpty()) {
return false; // it's breaking
}
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 3; y++) {
BlockPos chk = current.getSrc().up(y);
if (x == 1) {
chk = chk.add(current.getDirection());
}
if (!MovementHelper.fullyPassable(ctx.world().getBlockState(chk))) {
return false;
}
}
}
if (MovementHelper.avoidWalkingInto(ctx.world().getBlockState(current.getSrc().up(3)).getBlock())) {
return false;
}
return !MovementHelper.avoidWalkingInto(ctx.world().getBlockState(next.getDest().up(2)).getBlock()); // codacy smh my head
}
private static boolean canSprintFromDescendInto(IPlayerContext ctx, IMovement current, IMovement next) {
if (next instanceof MovementDescend && next.getDirection().equals(current.getDirection())) { if (next instanceof MovementDescend && next.getDirection().equals(current.getDirection())) {
return true; return true;
} }
@@ -32,15 +32,13 @@ import net.minecraft.init.Blocks;
import net.minecraft.inventory.ContainerPlayer; import net.minecraft.inventory.ContainerPlayer;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import java.util.ArrayList; import java.util.*;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBlockProcess { public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBlockProcess {
private Block gettingTo; private Block gettingTo;
private List<BlockPos> knownLocations; private List<BlockPos> knownLocations;
private List<BlockPos> blacklist; // locations we failed to calc to
private BlockPos start; private BlockPos start;
private int tickCount = 0; private int tickCount = 0;
@@ -54,6 +52,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
onLostControl(); onLostControl();
gettingTo = block; gettingTo = block;
start = ctx.playerFeet(); start = ctx.playerFeet();
blacklist = new ArrayList<>();
rescan(new ArrayList<>(), new CalculationContext(baritone)); rescan(new ArrayList<>(), new CalculationContext(baritone));
} }
@@ -63,12 +62,12 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
} }
@Override @Override
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { public synchronized PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
if (knownLocations == null) { if (knownLocations == null) {
rescan(new ArrayList<>(), new CalculationContext(baritone)); rescan(new ArrayList<>(), new CalculationContext(baritone));
} }
if (knownLocations.isEmpty()) { if (knownLocations.isEmpty()) {
if (Baritone.settings().exploreForBlocks.get()) { if (Baritone.settings().exploreForBlocks.get() && !calcFailed) {
return new PathingCommand(new GoalRunAway(1, start) { return new PathingCommand(new GoalRunAway(1, start) {
@Override @Override
public boolean isInGoal(int x, int y, int z) { public boolean isInGoal(int x, int y, int z) {
@@ -82,12 +81,19 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
} }
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
} }
Goal goal = new GoalComposite(knownLocations.stream().map(this::createGoal).toArray(Goal[]::new));
if (calcFailed) { if (calcFailed) {
logDirect("Unable to find any path to " + gettingTo + ", canceling GetToBlock"); if (Baritone.settings().blacklistOnGetToBlockFailure.get()) {
if (isSafeToCancel) { logDirect("Unable to find any path to " + gettingTo + ", blacklisting presumably unreachable closest instances");
onLostControl(); blacklistClosest();
return onTick(false, isSafeToCancel); // gamer moment
} else {
logDirect("Unable to find any path to " + gettingTo + ", canceling GetToBlock");
if (isSafeToCancel) {
onLostControl();
}
return new PathingCommand(goal, PathingCommandType.CANCEL_AND_SET_GOAL);
} }
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
} }
int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get();
if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain
@@ -95,25 +101,61 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
CalculationContext context = new CalculationContext(baritone, true); CalculationContext context = new CalculationContext(baritone, true);
Baritone.getExecutor().execute(() -> rescan(current, context)); Baritone.getExecutor().execute(() -> rescan(current, context));
} }
Goal goal = new GoalComposite(knownLocations.stream().map(this::createGoal).toArray(Goal[]::new));
if (goal.isInGoal(ctx.playerFeet()) && isSafeToCancel) { if (goal.isInGoal(ctx.playerFeet()) && isSafeToCancel) {
// we're there // we're there
if (rightClickOnArrival(gettingTo)) { if (rightClickOnArrival(gettingTo)) {
if (rightClick()) { if (rightClick()) {
onLostControl(); onLostControl();
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
} }
} else { } else {
onLostControl(); onLostControl();
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
} }
} }
return new PathingCommand(goal, PathingCommandType.REVALIDATE_GOAL_AND_PATH); return new PathingCommand(goal, PathingCommandType.REVALIDATE_GOAL_AND_PATH);
} }
// blacklist the closest block and its adjacent blocks
public synchronized void blacklistClosest() {
List<BlockPos> newBlacklist = new ArrayList<>();
knownLocations.stream().min(Comparator.comparingDouble(ctx.player()::getDistanceSq)).ifPresent(newBlacklist::add);
outer:
while (true) {
for (BlockPos known : knownLocations) {
for (BlockPos blacklist : newBlacklist) {
if (areAdjacent(known, blacklist)) { // directly adjacent
newBlacklist.add(known);
knownLocations.remove(known);
continue outer;
}
}
}
// i can't do break; (codacy gets mad), and i can't do if(true){break}; (codacy gets mad)
// so i will do this
switch (newBlacklist.size()) {
default:
break outer;
}
}
logDebug("Blacklisting unreachable locations " + newBlacklist);
blacklist.addAll(newBlacklist);
}
// safer than direct double comparison from distanceSq
private boolean areAdjacent(BlockPos posA, BlockPos posB) {
int diffX = Math.abs(posA.getX() - posB.getX());
int diffY = Math.abs(posA.getY() - posB.getY());
int diffZ = Math.abs(posA.getZ() - posB.getZ());
return (diffX + diffY + diffZ) == 1;
}
@Override @Override
public void onLostControl() { public synchronized void onLostControl() {
gettingTo = null; gettingTo = null;
knownLocations = null; knownLocations = null;
start = null; start = null;
blacklist = null;
baritone.getInputOverrideHandler().clearAllKeys(); baritone.getInputOverrideHandler().clearAllKeys();
} }
@@ -122,12 +164,20 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
return "Get To Block " + gettingTo; return "Get To Block " + gettingTo;
} }
private void rescan(List<BlockPos> known, CalculationContext context) { private synchronized void rescan(List<BlockPos> known, CalculationContext context) {
knownLocations = MineProcess.searchWorld(context, Collections.singletonList(gettingTo), 64, known); List<BlockPos> positions = MineProcess.searchWorld(context, Collections.singletonList(gettingTo), 64, known);
positions.removeIf(blacklist::contains);
knownLocations = positions;
} }
private Goal createGoal(BlockPos pos) { private Goal createGoal(BlockPos pos) {
return walkIntoInsteadOfAdjacent(gettingTo) ? new GoalTwoBlocks(pos) : new GoalGetToBlock(pos); if (walkIntoInsteadOfAdjacent(gettingTo)) {
return new GoalTwoBlocks(pos);
}
if (blockOnTopMustBeRemoved(gettingTo) && baritone.bsi.get0(pos.up()).isBlockNormalCube()) {
return new GoalBlock(pos.up());
}
return new GoalGetToBlock(pos);
} }
private boolean rightClick() { private boolean rightClick() {
@@ -162,4 +212,12 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
} }
return block == Blocks.CRAFTING_TABLE || block == Blocks.FURNACE || block == Blocks.ENDER_CHEST || block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST; return block == Blocks.CRAFTING_TABLE || block == Blocks.FURNACE || block == Blocks.ENDER_CHEST || block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST;
} }
private boolean blockOnTopMustBeRemoved(Block block) {
if (!rightClickOnArrival(block)) { // only if we plan to actually open it on arrival
return false;
}
// only these chests; you can open a crafting table or furnace even with a block on top
return block == Blocks.ENDER_CHEST || block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST;
}
} }
@@ -228,7 +228,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
return prune(ctx, locs, mining, max); return prune(ctx, locs, mining, max);
} }
public void addNearby() { private void addNearby() {
knownOreLocations.addAll(droppedItemsScan(mining, ctx.world())); knownOreLocations.addAll(droppedItemsScan(mining, ctx.world()));
BlockPos playerFeet = ctx.playerFeet(); BlockPos playerFeet = ctx.playerFeet();
BlockStateInterface bsi = new BlockStateInterface(ctx); BlockStateInterface bsi = new BlockStateInterface(ctx);
@@ -239,8 +239,11 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) { for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) {
// crucial to only add blocks we can see because otherwise this // crucial to only add blocks we can see because otherwise this
// is an x-ray and it'll get caught // is an x-ray and it'll get caught
if (mining.contains(bsi.get0(x, y, z).getBlock()) && RotationUtils.reachable(ctx.player(), new BlockPos(x, y, z), fakedBlockReachDistance).isPresent()) { if (mining.contains(bsi.get0(x, y, z).getBlock())) {
knownOreLocations.add(new BlockPos(x, y, z)); BlockPos pos = new BlockPos(x, y, z);
if ((Baritone.settings().legitMineIncludeDiagonals.get() && knownOreLocations.stream().anyMatch(ore -> ore.distanceSq(pos) <= 2 /* sq means this is pytha dist <= sqrt(2) */)) || RotationUtils.reachable(ctx.player(), pos, fakedBlockReachDistance).isPresent()) {
knownOreLocations.add(pos);
}
} }
} }
} }
@@ -250,12 +253,19 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
public static List<BlockPos> prune(CalculationContext ctx, List<BlockPos> locs2, List<Block> mining, int max) { public static List<BlockPos> prune(CalculationContext ctx, List<BlockPos> locs2, List<Block> mining, int max) {
List<BlockPos> dropped = droppedItemsScan(mining, ctx.world); List<BlockPos> dropped = droppedItemsScan(mining, ctx.world);
dropped.removeIf(drop -> {
for (BlockPos pos : locs2) {
if (pos.distanceSq(drop) <= 9 && mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) && MineProcess.plausibleToBreak(ctx.bsi, pos)) { // TODO maybe drop also has to be supported? no lava below?
return true;
}
}
return false;
});
List<BlockPos> locs = locs2 List<BlockPos> locs = locs2
.stream() .stream()
.distinct() .distinct()
// remove any that are within loaded chunks that aren't actually what we want // remove any that are within loaded chunks that aren't actually what we want
.filter(pos -> !ctx.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ()) || mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) || dropped.contains(pos)) .filter(pos -> !ctx.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ()) || mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) || dropped.contains(pos))
// remove any that are implausible to mine (encased in bedrock, or touching lava) // remove any that are implausible to mine (encased in bedrock, or touching lava)
@@ -77,7 +77,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
"sethome - Sets \"home\"\n" + "sethome - Sets \"home\"\n" +
"home - Paths towards \"home\" \n" + "home - Paths towards \"home\" \n" +
"costs - (debug) all movement costs from current location\n" + "costs - (debug) all movement costs from current location\n" +
"damn - Daniel "; "damn - Daniel\n" +
"Go to https://github.com/cabaletta/baritone/blob/master/USAGE.md for more information";
private static final String COMMAND_PREFIX = "#"; private static final String COMMAND_PREFIX = "#";
@@ -116,12 +117,33 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true; return true;
} }
} }
if (msg.equals("baritone") || msg.equals("settings")) { if (msg.equals("baritone") || msg.equals("modifiedsettings") || msg.startsWith("settings m") || msg.equals("modified")) {
for (Settings.Setting<?> setting : Baritone.settings().allSettings) { logDirect("All settings that have been modified from their default values:");
for (Settings.Setting<?> setting : SettingsUtil.modifiedSettings(Baritone.settings())) {
logDirect(setting.toString()); logDirect(setting.toString());
} }
return true; return true;
} }
if (msg.startsWith("settings")) {
String rest = msg.substring("settings".length());
try {
int page = Integer.parseInt(rest.trim());
int min = page * 10;
int max = Math.min(Baritone.settings().allSettings.size(), (page + 1) * 10);
logDirect("Settings " + min + " to " + (max - 1) + ":");
for (int i = min; i < max; i++) {
logDirect(Baritone.settings().allSettings.get(i).toString());
}
} catch (Exception ex) { // NumberFormatException | ArrayIndexOutOfBoundsException and probably some others I'm forgetting lol
ex.printStackTrace();
logDirect("All settings:");
for (Settings.Setting<?> setting : Baritone.settings().allSettings) {
logDirect(setting.toString());
}
logDirect("To get one page of ten settings at a time, do settings <num>");
}
return true;
}
if (msg.equals("") || msg.equals("help") || msg.equals("?")) { if (msg.equals("") || msg.equals("help") || msg.equals("?")) {
for (String line : HELP_MSG.split("\n")) { for (String line : HELP_MSG.split("\n")) {
logDirect(line); logDirect(line);
@@ -129,31 +151,24 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true; return true;
} }
if (msg.contains(" ")) { if (msg.contains(" ")) {
String[] data = msg.split(" "); String settingName = msg.substring(0, msg.indexOf(' '));
if (data.length == 2) { String settingValue = msg.substring(msg.indexOf(' ') + 1);
Settings.Setting setting = Baritone.settings().byLowerName.get(data[0]); Settings.Setting setting = Baritone.settings().byLowerName.get(settingName);
if (setting != null) { if (setting != null) {
if (settingValue.equals("reset")) {
logDirect("Resetting setting " + settingName + " to default value.");
setting.reset();
} else {
try { try {
if (setting.value.getClass() == Long.class) { SettingsUtil.parseAndApply(Baritone.settings(), settingName, settingValue);
setting.value = Long.parseLong(data[1]); } catch (Exception ex) {
} logDirect("Unable to parse setting");
if (setting.value.getClass() == Integer.class) {
setting.value = Integer.parseInt(data[1]);
}
if (setting.value.getClass() == Double.class) {
setting.value = Double.parseDouble(data[1]);
}
if (setting.value.getClass() == Float.class) {
setting.value = Float.parseFloat(data[1]);
}
} catch (NumberFormatException e) {
logDirect("Unable to parse " + data[1]);
return true; return true;
} }
SettingsUtil.save(Baritone.settings());
logDirect(setting.toString());
return true;
} }
SettingsUtil.save(Baritone.settings());
logDirect(setting.toString());
return true;
} }
} }
if (Baritone.settings().byLowerName.containsKey(msg)) { if (Baritone.settings().byLowerName.containsKey(msg)) {
@@ -163,36 +178,19 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
} }
if (msg.startsWith("goal")) { if (msg.startsWith("goal")) {
String[] params = msg.substring(4).trim().split(" "); String rest = msg.substring(4).trim();
if (params[0].equals("")) {
params = new String[]{};
}
Goal goal; Goal goal;
try { if (rest.equals("clear") || rest.equals("none")) {
switch (params.length) { goal = null;
case 0: } else {
goal = new GoalBlock(ctx.playerFeet()); String[] params = rest.split(" ");
break; if (params[0].equals("")) {
case 1: params = new String[]{};
if (params[0].equals("clear") || params[0].equals("none")) { }
goal = null; goal = parseGoal(params);
} else { if (goal == null) {
goal = new GoalYLevel(Integer.parseInt(params[0])); return true;
}
break;
case 2:
goal = new GoalXZ(Integer.parseInt(params[0]), Integer.parseInt(params[1]));
break;
case 3:
goal = new GoalBlock(new BlockPos(Integer.parseInt(params[0]), Integer.parseInt(params[1]), Integer.parseInt(params[2])));
break;
default:
logDirect("unable to understand lol");
return true;
} }
} catch (NumberFormatException ex) {
logDirect("unable to parse integer " + ex);
return true;
} }
customGoalProcess.setGoal(goal); customGoalProcess.setGoal(goal);
logDirect("Goal: " + goal); logDirect("Goal: " + goal);
@@ -253,7 +251,12 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
logDirect("Queued " + count + " chunks for repacking"); logDirect("Queued " + count + " chunks for repacking");
return true; return true;
} }
if (msg.equals("axis")) { if (msg.equals("come")) {
customGoalProcess.setGoalAndPath(new GoalBlock(new BlockPos(mc.getRenderViewEntity())));
logDirect("Coming");
return true;
}
if (msg.equals("axis") || msg.equals("highway")) {
customGoalProcess.setGoalAndPath(new GoalAxis()); customGoalProcess.setGoalAndPath(new GoalAxis());
return true; return true;
} }
@@ -294,7 +297,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true; return true;
} }
if (msg.equals("reset")) { if (msg.equals("reset")) {
Baritone.settings().reset(); for (Settings.Setting setting : Baritone.settings().allSettings) {
setting.reset();
}
SettingsUtil.save(Baritone.settings());
logDirect("Baritone settings reset"); logDirect("Baritone settings reset");
return true; return true;
} }
@@ -401,7 +407,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
logDirect("Started mining blocks of type " + Arrays.toString(blockTypes)); logDirect("Started mining blocks of type " + Arrays.toString(blockTypes));
return true; return true;
} }
if (msg.startsWith("thisway")) { if (msg.startsWith("thisway") || msg.startsWith("forward")) {
try { try {
Goal goal = GoalXZ.fromDirection(ctx.playerFeetAsVec(), ctx.player().rotationYaw, Double.parseDouble(msg.substring(7).trim())); Goal goal = GoalXZ.fromDirection(ctx.playerFeetAsVec(), ctx.player().rotationYaw, Double.parseDouble(msg.substring(7).trim()));
customGoalProcess.setGoal(goal); customGoalProcess.setGoal(goal);
@@ -469,7 +475,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
if (block == null) { if (block == null) {
waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getName().equalsIgnoreCase(mining)).max(Comparator.comparingLong(IWaypoint::getCreationTimestamp)).orElse(null); waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getName().equalsIgnoreCase(mining)).max(Comparator.comparingLong(IWaypoint::getCreationTimestamp)).orElse(null);
if (waypoint == null) { if (waypoint == null) {
logDirect("No locations for " + mining + " known, cancelling"); Goal goal = parseGoal(waypointType.split(" "));
if (goal != null) {
logDirect("Going to " + goal);
customGoalProcess.setGoalAndPath(goal);
}
return true; return true;
} }
} else { } else {
@@ -548,4 +558,31 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
} }
} }
} }
private Goal parseGoal(String[] params) {
Goal goal;
try {
switch (params.length) {
case 0:
goal = new GoalBlock(ctx.playerFeet());
break;
case 1:
goal = new GoalYLevel(Integer.parseInt(params[0]));
break;
case 2:
goal = new GoalXZ(Integer.parseInt(params[0]), Integer.parseInt(params[1]));
break;
case 3:
goal = new GoalBlock(new BlockPos(Integer.parseInt(params[0]), Integer.parseInt(params[1]), Integer.parseInt(params[2])));
break;
default:
logDirect("unable to understand lol");
return null;
}
} catch (NumberFormatException ex) {
logDirect("unable to parse integer " + ex);
return null;
}
return goal;
}
} }
+72 -72
View File
@@ -1,72 +1,72 @@
/* /*
* This file is part of Baritone. * This file is part of Baritone.
* *
* Baritone is free software: you can redistribute it and/or modify * 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 * 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 * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Baritone is distributed in the hope that it will be useful, * Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details. * GNU Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public License * You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>. * along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/ */
package baritone.utils; package baritone.utils;
import baritone.Baritone; import baritone.Baritone;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
/** /**
* @author Brady * @author Brady
* @since 8/1/2018 * @since 8/1/2018
*/ */
public interface Helper { public interface Helper {
/** /**
* Instance of {@link Helper}. Used for static-context reference. * Instance of {@link Helper}. Used for static-context reference.
*/ */
Helper HELPER = new Helper() {}; Helper HELPER = new Helper() {};
ITextComponent MESSAGE_PREFIX = new TextComponentString(String.format( ITextComponent MESSAGE_PREFIX = new TextComponentString(String.format(
"%s[%sBaritone%s]%s", "%s[%sBaritone%s]%s",
TextFormatting.DARK_PURPLE, TextFormatting.DARK_PURPLE,
TextFormatting.LIGHT_PURPLE, TextFormatting.LIGHT_PURPLE,
TextFormatting.DARK_PURPLE, TextFormatting.DARK_PURPLE,
TextFormatting.GRAY TextFormatting.GRAY
)); ));
Minecraft mc = Minecraft.getMinecraft(); Minecraft mc = Minecraft.getMinecraft();
/** /**
* Send a message to chat only if chatDebug is on * Send a message to chat only if chatDebug is on
* *
* @param message The message to display in chat * @param message The message to display in chat
*/ */
default void logDebug(String message) { default void logDebug(String message) {
if (!Baritone.settings().chatDebug.get()) { if (!Baritone.settings().chatDebug.get()) {
//System.out.println("Suppressed debug message:"); //System.out.println("Suppressed debug message:");
//System.out.println(message); //System.out.println(message);
return; return;
} }
logDirect(message); logDirect(message);
} }
/** /**
* Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a direct response to a chat command) * Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a direct response to a chat command)
* *
* @param message The message to display in chat * @param message The message to display in chat
*/ */
default void logDirect(String message) { default void logDirect(String message) {
ITextComponent component = MESSAGE_PREFIX.createCopy(); ITextComponent component = MESSAGE_PREFIX.createCopy();
component.getStyle().setColor(TextFormatting.GRAY); component.getStyle().setColor(TextFormatting.GRAY);
component.appendSibling(new TextComponentString(" " + message)); component.appendSibling(new TextComponentString(" " + message));
Minecraft.getMinecraft().addScheduledTask(() -> Baritone.settings().logger.get().accept(component)); Minecraft.getMinecraft().addScheduledTask(() -> Baritone.settings().logger.get().accept(component));
} }
} }
@@ -1,131 +1,140 @@
/* /*
* This file is part of Baritone. * This file is part of Baritone.
* *
* Baritone is free software: you can redistribute it and/or modify * 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 * 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 * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Baritone is distributed in the hope that it will be useful, * Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details. * GNU Lesser General Public License for more details.
* *
* You should have received a copy of the GNU Lesser General Public License * You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>. * along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/ */
package baritone.utils; package baritone.utils;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.event.events.TickEvent; import baritone.api.event.events.TickEvent;
import baritone.api.utils.IInputOverrideHandler; import baritone.api.utils.IInputOverrideHandler;
import baritone.api.utils.input.Input; import baritone.api.utils.input.Input;
import baritone.behavior.Behavior; import baritone.behavior.Behavior;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding; import net.minecraft.client.settings.KeyBinding;
import net.minecraft.util.MovementInput; import net.minecraft.util.MovementInputFromOptions;
import net.minecraft.util.MovementInputFromOptions;
import java.util.HashMap;
import java.util.HashMap; import java.util.Map;
import java.util.Map;
/**
/** * An interface with the game's control system allowing the ability to
* An interface with the game's control system allowing the ability to * force down certain controls, having the same effect as if we were actually
* force down certain controls, having the same effect as if we were actually * physically forcing down the assigned key.
* physically forcing down the assigned key. *
* * @author Brady
* @author Brady * @since 7/31/2018
* @since 7/31/2018 */
*/ public final class InputOverrideHandler extends Behavior implements IInputOverrideHandler {
public final class InputOverrideHandler extends Behavior implements IInputOverrideHandler {
/**
/** * Maps inputs to whether or not we are forcing their state down.
* Maps inputs to whether or not we are forcing their state down. */
*/ private final Map<Input, Boolean> inputForceStateMap = new HashMap<>();
private final Map<Input, Boolean> inputForceStateMap = new HashMap<>();
private final BlockBreakHelper blockBreakHelper;
private final BlockBreakHelper blockBreakHelper;
public InputOverrideHandler(Baritone baritone) {
public InputOverrideHandler(Baritone baritone) { super(baritone);
super(baritone); this.blockBreakHelper = new BlockBreakHelper(baritone.getPlayerContext());
this.blockBreakHelper = new BlockBreakHelper(baritone.getPlayerContext()); }
}
/**
/** * Returns whether or not we are forcing down the specified {@link KeyBinding}.
* Returns whether or not we are forcing down the specified {@link KeyBinding}. *
* * @param key The KeyBinding object
* @param key The KeyBinding object * @return Whether or not it is being forced down
* @return Whether or not it is being forced down */
*/ @Override
@Override public final Boolean isInputForcedDown(KeyBinding key) {
public final Boolean isInputForcedDown(KeyBinding key) { Input input = Input.getInputForBind(key);
Input input = Input.getInputForBind(key); if (input == null) {
if (input == null || !inControl()) { return null;
return null; }
} if (input == Input.CLICK_LEFT && inControl()) {
if (input == Input.CLICK_LEFT) { // only override left click off when pathing
return false; return false;
} }
if (input == Input.CLICK_RIGHT) { if (input == Input.CLICK_RIGHT) {
return isInputForcedDown(Input.CLICK_RIGHT); if (isInputForcedDown(Input.CLICK_RIGHT)) {
} // gettoblock and builder can right click even when not pathing; allow them to do so
return null; return true;
} } else if (inControl()) {
// but when we are pathing for real, force right click off
/** return false;
* Returns whether or not we are forcing down the specified {@link Input}. }
* }
* @param input The input return null; // dont force any inputs other than left and right click
* @return Whether or not it is being forced down }
*/
@Override /**
public final boolean isInputForcedDown(Input input) { * Returns whether or not we are forcing down the specified {@link Input}.
return input == null ? false : this.inputForceStateMap.getOrDefault(input, false); *
} * @param input The input
* @return Whether or not it is being forced down
/** */
* Sets whether or not the specified {@link Input} is being forced down. @Override
* public final boolean isInputForcedDown(Input input) {
* @param input The {@link Input} return input == null ? false : this.inputForceStateMap.getOrDefault(input, false);
* @param forced Whether or not the state is being forced }
*/
@Override /**
public final void setInputForceState(Input input, boolean forced) { * Sets whether or not the specified {@link Input} is being forced down.
this.inputForceStateMap.put(input, forced); *
} * @param input The {@link Input}
* @param forced Whether or not the state is being forced
/** */
* Clears the override state for all keys @Override
*/ public final void setInputForceState(Input input, boolean forced) {
@Override this.inputForceStateMap.put(input, forced);
public final void clearAllKeys() { }
this.inputForceStateMap.clear();
} /**
* Clears the override state for all keys
@Override */
public final void onTick(TickEvent event) { @Override
if (event.getType() == TickEvent.Type.OUT) { public final void clearAllKeys() {
return; this.inputForceStateMap.clear();
} }
blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT));
@Override
MovementInput desired = inControl() public final void onTick(TickEvent event) {
? new PlayerMovementInput(this) if (event.getType() == TickEvent.Type.OUT) {
: new MovementInputFromOptions(Minecraft.getMinecraft().gameSettings); return;
}
if (ctx.player().movementInput.getClass() != desired.getClass()) { blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT));
ctx.player().movementInput = desired; // only set it if it was previously incorrect
// gotta do it this way, or else it constantly thinks you're beginning a double tap W sprint lol if (inControl()) {
} if (ctx.player().movementInput.getClass() != PlayerMovementInput.class) {
} ctx.player().movementInput = new PlayerMovementInput(this);
}
private boolean inControl() { } else {
return baritone.getPathingBehavior().isPathing() || baritone != BaritoneAPI.getProvider().getPrimaryBaritone(); if (ctx.player().movementInput.getClass() == PlayerMovementInput.class) { // allow other movement inputs that aren't this one, e.g. for a freecam
} ctx.player().movementInput = new MovementInputFromOptions(Minecraft.getMinecraft().gameSettings);
}
public BlockBreakHelper getBlockBreakHelper() { }
return blockBreakHelper; // only set it if it was previously incorrect
} // gotta do it this way, or else it constantly thinks you're beginning a double tap W sprint lol
} }
private boolean inControl() {
return baritone.getPathingBehavior().isPathing() || baritone != BaritoneAPI.getProvider().getPrimaryBaritone();
}
public BlockBreakHelper getBlockBreakHelper() {
return blockBreakHelper;
}
}
@@ -57,8 +57,6 @@ public final class PathRenderer implements Helper {
private PathRenderer() {} private PathRenderer() {}
public static void render(RenderEvent event, PathingBehavior behavior) { public static void render(RenderEvent event, PathingBehavior behavior) {
// System.out.println("Render passing");
// System.out.println(event.getPartialTicks());
float partialTicks = event.getPartialTicks(); float partialTicks = event.getPartialTicks();
Goal goal = behavior.getGoal(); Goal goal = behavior.getGoal();
@@ -80,7 +78,7 @@ public final class PathRenderer implements Helper {
} }
if (goal != null && Baritone.settings().renderGoal.value) { if (goal != null && Baritone.settings().renderGoal.value) {
drawLitDankGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.get()); drawDankLitGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.get());
} }
if (!Baritone.settings().renderPath.get()) { if (!Baritone.settings().renderPath.get()) {
return; return;
@@ -261,7 +259,7 @@ public final class PathRenderer implements Helper {
GlStateManager.disableBlend(); GlStateManager.disableBlend();
} }
public static void drawLitDankGoalBox(Entity player, Goal goal, float partialTicks, Color color) { public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTicks, Color color) {
double renderPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks; double renderPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks;
double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks;
double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks;
@@ -297,6 +295,8 @@ public final class PathRenderer implements Helper {
GoalXZ goalPos = (GoalXZ) goal; GoalXZ goalPos = (GoalXZ) goal;
if (Baritone.settings().renderGoalXZBeacon.get()) { if (Baritone.settings().renderGoalXZBeacon.get()) {
glPushAttrib(GL_LIGHTING_BIT);
mc.getTextureManager().bindTexture(TileEntityBeaconRenderer.TEXTURE_BEACON_BEAM); mc.getTextureManager().bindTexture(TileEntityBeaconRenderer.TEXTURE_BEACON_BEAM);
if (Baritone.settings().renderGoalIgnoreDepth.get()) { if (Baritone.settings().renderGoalIgnoreDepth.get()) {
@@ -318,6 +318,8 @@ public final class PathRenderer implements Helper {
if (Baritone.settings().renderGoalIgnoreDepth.get()) { if (Baritone.settings().renderGoalIgnoreDepth.get()) {
GlStateManager.enableDepth(); GlStateManager.enableDepth();
} }
glPopAttrib();
return; return;
} }
@@ -332,7 +334,7 @@ public final class PathRenderer implements Helper {
maxY = 256 - renderPosY; maxY = 256 - renderPosY;
} else if (goal instanceof GoalComposite) { } else if (goal instanceof GoalComposite) {
for (Goal g : ((GoalComposite) goal).goals()) { for (Goal g : ((GoalComposite) goal).goals()) {
drawLitDankGoalBox(player, g, partialTicks, color); drawDankLitGoalBox(player, g, partialTicks, color);
} }
return; return;
} else { } else {
@@ -82,6 +82,7 @@ public class PathingControlManager implements IPathingControlManager {
public void preTick() { public void preTick() {
inControlLastTick = inControlThisTick; inControlLastTick = inControlThisTick;
inControlThisTick = null;
PathingBehavior p = baritone.getPathingBehavior(); PathingBehavior p = baritone.getPathingBehavior();
command = executeProcesses(); command = executeProcesses();
if (command == null) { if (command == null) {
@@ -31,7 +31,7 @@ public class PlayerMovementInput extends MovementInput {
this.moveStrafe = 0.0F; this.moveStrafe = 0.0F;
this.moveForward = 0.0F; this.moveForward = 0.0F;
jump = handler.isInputForcedDown(Input.JUMP); // oppa jump = handler.isInputForcedDown(Input.JUMP); // oppa gangnam
if (this.forwardKeyDown = handler.isInputForcedDown(Input.MOVE_FORWARD)) { if (this.forwardKeyDown = handler.isInputForcedDown(Input.MOVE_FORWARD)) {
this.moveForward++; this.moveForward++;