Merge branch 'master' into 1.13.2

This commit is contained in:
Leijurv 2021-01-29 19:30:56 -08:00
commit eb8a673165
No known key found for this signature in database
GPG Key ID: 44A3EA646EADAC6A
36 changed files with 825 additions and 104 deletions

31
.gitmessage Normal file
View File

@ -0,0 +1,31 @@
<emoji> <title> (<ticket>)
# 📝 Update README.md (WD-1234)
# ✅ Add unit test for inputs (WD-1234)
# <emoji> can be:
# 🎨 :art: when improving structure of the code
# ⚡️ :zap: when improving performance
# 🔥 :fire: when removing code or files
# ✨ :sparkles: when introducing new features
# 🚧 :construction: when work in progress
# 🔨 :hammer: when refactoring code
# 📝 :memo: when writing docs
# 💄 :lipstick: when updating the UI and style files
# 📈 :chart_with_upwards_trend: when adding analytics or tracking code
# 🌐 :globe_with_meridians: when adding internationalization and localization
# ✏️ :pencil2: when fixing typos
# 🚚 :truck: when moving or renaming files
# ✅ :white_check_mark: when adding tests
# 👌 :ok_hand: when updating code due to code review changes
# 🐛 :bug: when fixing a bug
# 🚑 :ambulance: when doing a critical hotfix
# 🚨 :rotating_light: when removing linter warnings
# 🔀 :twisted_rightwards_arrows: when merging branches
# ⬆️ :arrow_up: when upgrading dependencies
# ⬇️ :arrow_down: when downgrading dependencies
# 🔧 :wrench: when changing configuration files
# 🔖 :bookmark: when releasing / version tagging
# 💚 :green_heart: when fixing the CI build

View File

@ -10,6 +10,7 @@
[![Minecraft](https://img.shields.io/badge/MC-1.13.2-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.13.2/)
[![Minecraft](https://img.shields.io/badge/MC-1.14.4-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.14.4/)
[![Minecraft](https://img.shields.io/badge/MC-1.15.2-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.15.2/)
[![Minecraft](https://img.shields.io/badge/MC-1.16.4-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.16.4/)
[![Code of Conduct](https://img.shields.io/badge/%E2%9D%A4-code%20of%20conduct-blue.svg?style=flat)](https://github.com/cabaletta/baritone/blob/master/CODE_OF_CONDUCT.md)
[![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle)
[![Contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues/)
@ -21,27 +22,30 @@
![Lines of Code](https://tokei.rs/b1/github/cabaletta/baritone?category=code)
[![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/)
[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.10%20/%20v1.3.5%20/%20v1.4.3-brightgreen.svg)](https://impactclient.net/)
[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.14%20/%20v1.3.8%20/%20v1.4.6%20/%20v1.5.3-brightgreen.svg)](https://impactclient.net/)
[![KAMI Blue integration](https://img.shields.io/badge/KAMI%20Blue%20integration-v1.2.14--master-green)](https://github.com/kami-blue/client)
[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/)
[![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%20integration-v1.3.4%20/%20v1.4.1-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api)
[![rootNET integration](https://img.shields.io/badge/rootNET%20integration-v1.2.11-green.svg)](https://rootnet.dev/)
[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/)
[![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/)
[![rootNET integration](https://img.shields.io/badge/rootNET%20integration-v1.2.14-green.svg)](https://rootnet.dev/)
[![Future integration](https://img.shields.io/badge/Future%20integration-v1.2.12%20%2F%20v1.3.6%20%2F%20v1.4.4-red)](https://futureclient.net/)
[![RusherHack integration](https://img.shields.io/badge/RusherHack%20integration-v1.2.14-green)](https://rusherhack.org/)
[![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com/)
[![forthebadge](https://forthebadge.com/images/badges/mom-made-pizza-rolls.svg)](http://forthebadge.com/)
A Minecraft pathfinder bot.
Baritone is the pathfinding system used in [Impact](https://impactclient.net/) since 4.4. There's a [showcase video](https://youtu.be/CZkLXWo4Fg4) made by @Adovin#0730 on Baritone which I recommend. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a (very old!) video I made showing off what it can do.
Baritone is the pathfinding system used in [Impact](https://impactclient.net/) since 4.4. There's a [showcase video](https://youtu.be/CZkLXWo4Fg4) made by @Adovin#0730 on Baritone which I recommend. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a (very old!) video I made showing off what it can do. [Tutorial playlist](https://www.youtube.com/playlist?list=PLnwnJ1qsS7CoQl9Si-RTluuzCo_4Oulpa)
The easiest way to install Baritone is to install [Impact](https://impactclient.net/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the v1.2.* forge api jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it.
The easiest way to install Baritone is to install [Impact](https://impactclient.net/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the v1.2.* `api-forge` jar from [releases](https://github.com/cabaletta/baritone/releases). **For 1.12.2 Forge, just click [here](https://github.com/cabaletta/baritone/releases/download/v1.2.14/baritone-api-forge-1.2.14.jar)**. Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it.
For 1.15.2, [click here](https://www.youtube.com/watch?v=j1qKtCZFURM) and see description.
For 1.15.2, [click here](https://www.youtube.com/watch?v=j1qKtCZFURM) and see description. If you need Forge 1.15.2, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.5.3), follow the instructions, and get the `api-forge` jar.
For 1.16.4, [click here](https://www.youtube.com/watch?v=_4eVJ9Qz2J8) and see description. If you need Forge 1.16.4, look [here](https://github.com/cabaletta/baritone/releases/tag/v1.6.2) and get the `api-forge` jar.
This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/),
the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2 through 1.15.2. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths).
the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2 through 1.16.4. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths).
Have committed at least once a day from Aug 1 2018 to Aug 1 2019.
Have committed at least once a day from Aug 1, 2018, to Aug 1, 2019.
1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2
@ -69,7 +73,7 @@ The API is heavily documented, you can find the Javadocs for the latest release
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.
Below is an example of basic usage for changing some settings, and then pathing to an X/Z goal.
```
BaritoneAPI.getSettings().allowSprint.value = true;
@ -82,12 +86,22 @@ BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAnd
## Can I use Baritone as a library in my custom utility client?
That's what it's for, sure! (As long as usage is in compliance with the LGPL 3.0 License)
That's what it's for, sure! (As long as usage complies with the LGPL 3.0 License)
## How is it so fast?
Magic. (Hours of [leijurv](https://github.com/leijurv/) enduring excruciating pain)
### Additional Special Thanks To:
![YourKit-Logo](https://www.yourkit.com/images/yklogo.png)
YourKit supports open source projects with innovative and intelligent tools for monitoring and profiling Java and .NET applications.
YourKit is the creator of the [YourKit Java Profiler](https://www.yourkit.com/java/profiler/), [YourKit .NET Profiler](https://www.yourkit.com/.net/profiler/), and [YourKit YouMonitor](https://www.yourkit.com/youmonitor/).
We thank them for granting Baritone an OSS license so that we can make our software the best it can be.
## Why is it called Baritone?
It's named for FitMC's deep sultry voice.
It's named for FitMC's deep sultry voice.

View File

@ -49,6 +49,27 @@ On Mac OSX and Linux, use `./gradlew` instead of `gradlew`.
If you have errors with a package missing please make sure you have setup your environment, and are using Oracle JDK 8.
To check which java you are using do
`java -version` in a command prompt or terminal.
If you are using anything above OpenJDK 8, it might not work because the Java distributions above JDK 8 using may not have the needed javax classes.
Open JDK 8 download: https://openjdk.java.net/install/
#### macOS guide
In order to get JDK 8, Try running the following command:
`% /usr/libexec/java_home -V`
If it doesn't work try this guide: https://stackoverflow.com/questions/46513639/how-to-downgrade-java-from-9-to-8-on-a-macos-eclipse-is-not-running-with-java-9
If you see something like
`% 1.8.0_VERSION, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_VERSION.jdk/Contents/Home`
in the list then you've got JDK 8 installed.
In order to get JDK 8 running in the **current terminal window** you will have to run this command:
`% export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)`
To add OpenJDK 8 to your PATH add the export line to the end of your `.zshrc / .bashrc` if you want it to apply to each new terminal. If you're using bash change the .bachrc and if you're using zsh change the .zshrc
Setting up the Environment:
```

View File

@ -24,6 +24,8 @@ Watch this [showcase video](https://youtu.be/CZkLXWo4Fg4)!
# Commands
[Tutorial playlist](https://www.youtube.com/playlist?list=PLnwnJ1qsS7CoQl9Si-RTluuzCo_4Oulpa)
**All** of these commands may need a prefix before them, as above ^.
`help`
@ -39,7 +41,7 @@ Some common examples:
- `cancel` or `stop` to stop everything
- `goto portal` or `goto ender_chest` or `goto block_type` to go to a block. (in Impact, `.goto` is an alias for `.b goto` for the most part)
- `mine diamond_ore iron_ore` to mine diamond ore or iron ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.) An amount of blocks can also be specified, for example, `mine diamond_ore 64`.
- `click` to click your destination on the screen. Right click path to on top of the block, left click to path into it (either at foot level or eye level), and left click and drag to clear all blocks from an area.
- `click` to click your destination on the screen. Right click path to on top of the block, left click to path into it (either at foot level or eye level), and left click and drag to select an area (`#help sel` to see what you can do with that selection).
- `follow player playerName` to follow a player. `follow players` to follow any players in range (combine with Kill Aura for a fun time). `follow entities` to follow any entities. `follow entity pig` to follow entities of a specific type.
- `wp` for waypoints. A "tag" is like "home" (created automatically on right clicking a bed) or "death" (created automatically on death) or "user" (has to be created manually). So you might want `#wp save user coolbiome`, then to set the goal `#wp goal coolbiome` then `#path` to path to it. For death, `#wp goal death` will list waypoints under the "death" tag (remember stuff is clickable!)
- `build` to build a schematic. `build blah.schematic` will load `schematics/blah.schematic` and build it with the origin being your player feet. `build blah.schematic x y z` to set the origin. Any of those can be relative to your player (`~ 69 ~-420` would build at x=player x, y=69, z=player z-420).
@ -52,7 +54,7 @@ Some common examples:
- `version` to get the version of Baritone you're running
- `damn` daniel
For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/utils/ExampleBaritoneControl.java).
For the rest of the commands, you can take a look at the code [here](https://baritone.leijurv.com/baritone/api/Settings.html).
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>.

View File

@ -172,6 +172,12 @@ javadoc {
jar {
from sourceSets.launch.output, sourceSets.api.output
if (!getProject().hasProperty("baritone.forge_build")) {
exclude "**/BaritoneForgeModXD.class"
exclude "**/mods.toml"
}
preserveFileTimestamps = false
reproducibleFileOrder = true

View File

@ -22,6 +22,21 @@ import org.apache.commons.io.IOUtils;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.JavaVersion;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.internal.file.IdentityFileResolver;
import org.gradle.api.internal.plugins.DefaultConvention;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.TaskCollection;
import org.gradle.api.tasks.compile.ForkOptions;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.internal.Pair;
import org.gradle.internal.jvm.Jvm;
import org.gradle.internal.jvm.inspection.DefaultJvmVersionDetector;
import org.gradle.process.internal.DefaultExecActionFactory;
import java.io.*;
import java.net.URL;
@ -86,6 +101,101 @@ public class ProguardTask extends BaritoneGradleTask {
}
}
private String getJavaBinPathForProguard() throws Exception {
String path;
try {
path = findJavaPathByGradleConfig();
if (path != null) return path;
}
catch (Exception ex) {
System.err.println("Unable to find java by javaCompile options");
ex.printStackTrace();
}
try {
path = findJavaByJavaHome();
if (path != null) return path;
}
catch(Exception ex) {
System.err.println("Unable to find java by JAVA_HOME");
ex.printStackTrace();
}
path = findJavaByGradleCurrentRuntime();
if (path != null) return path;
throw new Exception("Unable to find java to determine ProGuard libraryjars. Please specify forkOptions.executable in javaCompile," +
" JAVA_HOME environment variable, or make sure to run Gradle with the correct JDK (a v1.8 only)");
}
private String findJavaByGradleCurrentRuntime() {
String path = Jvm.current().getJavaExecutable().getAbsolutePath();
if (this.validateJavaVersion(path)) {
System.out.println("Using Gradle's runtime Java for ProGuard");
return path;
}
return null;
}
private String findJavaByJavaHome() {
final String javaHomeEnv = System.getenv("JAVA_HOME");
if (javaHomeEnv != null) {
String path = Jvm.forHome(new File(javaHomeEnv)).getJavaExecutable().getAbsolutePath();
if (this.validateJavaVersion(path)) {
System.out.println("Detected Java path by JAVA_HOME");
return path;
}
}
return null;
}
private String findJavaPathByGradleConfig() {
final TaskCollection<JavaCompile> javaCompiles = super.getProject().getTasks().withType(JavaCompile.class);
final JavaCompile compileTask = javaCompiles.iterator().next();
final ForkOptions forkOptions = compileTask.getOptions().getForkOptions();
if (forkOptions != null) {
String javacPath = forkOptions.getExecutable();
if (javacPath != null) {
File javacFile = new File(javacPath);
if (javacFile.exists()) {
File[] maybeJava = javacFile.getParentFile().listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals("java");
}
});
if (maybeJava != null && maybeJava.length > 0) {
String path = maybeJava[0].getAbsolutePath();
if (this.validateJavaVersion(path)) {
System.out.println("Detected Java path by forkOptions");
return path;
}
}
}
}
}
return null;
}
private boolean validateJavaVersion(String java) {
final JavaVersion javaVersion = new DefaultJvmVersionDetector(new DefaultExecActionFactory(new IdentityFileResolver())).getJavaVersion(java);
if (!javaVersion.getMajorVersion().equals("8")) {
System.out.println("Failed to validate Java version " + javaVersion.toString() + " [" + java + "] for ProGuard libraryjars");
// throw new RuntimeException("Java version incorrect: " + javaVersion.getMajorVersion() + " for " + java);
return false;
}
System.out.println("Validated Java version " + javaVersion.toString() + " [" + java + "] for ProGuard libraryjars");
return true;
}
private void generateConfigs() throws Exception {
Files.copy(getRelativeFile(PROGUARD_CONFIG_TEMPLATE), getTemporaryFile(PROGUARD_CONFIG_DEST), REPLACE_EXISTING);
@ -95,7 +205,7 @@ public class ProguardTask extends BaritoneGradleTask {
template.add(1, "-outjars " + this.getTemporaryFile(PROGUARD_EXPORT_PATH));
// Acquire the RT jar using "java -verbose". This doesn't work on Java 9+
Process p = new ProcessBuilder("java", "-verbose").start();
Process p = new ProcessBuilder(this.getJavaBinPathForProguard(), "-verbose").start();
String out = IOUtils.toString(p.getInputStream(), "UTF-8").split("\n")[0].split("Opened ")[1].replace("]", "");
template.add(2, "-libraryjars '" + out + "'");

View File

@ -25,6 +25,13 @@
-keep class baritone.api.utils.MyChunkPos { *; } # even in standalone we need to keep this for gson reflect
# Keep any class or member annotated with @KeepName so we dont have to put everything in the script
-keep,allowobfuscation @interface baritone.KeepName
-keep @baritone.KeepName class *
-keepclassmembers class * {
@baritone.KeepName *;
}
# setting names are reflected from field names, so keep field names
-keepclassmembers class baritone.api.Settings {
public <fields>;

View File

@ -30,8 +30,8 @@ import java.awt.*;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.List;
import java.util.*;
import java.util.function.Consumer;
/**
@ -61,6 +61,19 @@ public final class Settings {
*/
public final Setting<Boolean> allowInventory = new Setting<>(false);
/**
* Disable baritone's auto-tool at runtime, but still assume that another mod will provide auto tool functionality
* <p>
* Specifically, path calculation will still assume that an auto tool will run at execution time, even though
* Baritone itself will not do that.
*/
public final Setting<Boolean> assumeExternalAutoTool = new Setting<>(false);
/**
* If this setting is on, no auto tool will occur at all, not at calculation time nor execution time
*/
public final Setting<Boolean> disableAutoTool = new Setting<>(false);
/**
* It doesn't actually take twenty ticks to place a block, this cost is so high
* because we want to generally conserve blocks which might be limited.
@ -192,6 +205,15 @@ public final class Settings {
)));
/**
* A list of blocks to become air
* <p>
* If a schematic asks for a block on this list, only air will be accepted at that location (and nothing on buildIgnoreBlocks)
*/
public final Setting<List<Block>> okIfAir = new Setting<>(new ArrayList<>(Arrays.asList(
)));
/**
* If this is true, the builder will treat all non-air blocks as correct. It will only place new blocks.
*/
@ -434,6 +456,11 @@ public final class Settings {
*/
public final Setting<Boolean> simplifyUnloadedYCoord = new Setting<>(true);
/**
* Whenever a block changes, repack the whole chunk that it's in
*/
public final Setting<Boolean> repackOnAnyBlockChange = new Setting<>(true);
/**
* If a movement takes this many ticks more than its initial cost estimate, cancel it
*/
@ -506,6 +533,18 @@ public final class Settings {
*/
public final Setting<Boolean> backfill = new Setting<>(false);
/**
* Shows popup message in the upper right corner, similarly to when you make an advancement
*/
public final Setting<Boolean> logAsToast = new Setting<>(false);
/**
* The time of how long the message in the pop-up will display
* <p>
* If below 1000L (1sec), it's better to disable this
*/
public final Setting<Long> toastTimer = new Setting<>(5000L);
/**
* Print all the debug messages to chat
*/
@ -703,6 +742,23 @@ public final class Settings {
*/
public final Setting<Integer> maxCachedWorldScanCount = new Setting<>(10);
/**
* Sets the minimum y level whilst mining - set to 0 to turn off.
*/
public final Setting<Integer> minYLevelWhileMining = new Setting<>(0);
/**
* This will only allow baritone to mine exposed ores, can be used to stop ore obfuscators on servers that use them.
*/
public final Setting<Boolean> allowOnlyExposedOres = new Setting<>(false);
/**
* When allowOnlyExposedOres is enabled this is the distance around to search.
* <p>
* It is recommended to keep this value low, as it dramatically increases calculation times.
*/
public final Setting<Integer> allowOnlyExposedOresDistance = new Setting<>(1);
/**
* When GetToBlock doesn't know any locations for the desired block, explore randomly instead of giving up.
*/
@ -756,6 +812,17 @@ public final class Settings {
*/
public final Setting<Boolean> layerOrder = new Setting<>(false);
/**
* Start building the schematic at a specific layer.
* Can help on larger builds when schematic wants to break things its already built
*/
public final Setting<Integer> startAtLayer = new Setting<>(0);
/**
* If a layer is unable to be constructed, just skip it.
*/
public final Setting<Boolean> skipFailedLayers = new Setting<>(false);
/**
* How far to move before repeating the build. 0 to disable repeating on a certain axis, 0,0,0 to disable entirely
*/
@ -1051,10 +1118,35 @@ public final class Settings {
public final Setting<Boolean> renderSelectionCorners = new Setting<>(true);
/**
* Desktop Notifications
* Desktop notifications
*/
public final Setting<Boolean> desktopNotifications = new Setting<>(false);
/**
* Desktop notification on path complete
*/
public final Setting<Boolean> notificationOnPathComplete = new Setting<>(true);
/**
* Desktop notification on farm fail
*/
public final Setting<Boolean> notificationOnFarmFail = new Setting<>(true);
/**
* Desktop notification on build finished
*/
public final Setting<Boolean> notificationOnBuildFinished = new Setting<>(true);
/**
* Desktop notification on explore finished
*/
public final Setting<Boolean> notificationOnExploreFinished = new Setting<>(true);
/**
* Desktop notification on mine fail
*/
public final Setting<Boolean> notificationOnMineFail = new Setting<>(true);
/**
* A map of lowercase setting field names to their respective setting
*/

View File

@ -75,7 +75,7 @@ public interface IBaritoneProcess {
* to start eating this tick. {@code PauseForAutoEatProcess} should only actually right click once onTick is called with
* {@code isSafeToCancel} true though.
*
* @return Whethor or not if this control is temporary
* @return Whether or not if this control is temporary
*/
boolean isTemporary();

View File

@ -18,6 +18,7 @@
package baritone.api.utils;
import baritone.api.BaritoneAPI;
import baritone.api.utils.gui.BaritoneToast;
import net.minecraft.client.Minecraft;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
@ -63,6 +64,35 @@ public interface Helper {
return prefix;
}
/**
* Send a message to display as a toast popup
*
* @param title The title to display in the popup
* @param message The message to display in the popup
*/
default void logToast(ITextComponent title, ITextComponent message) {
mc.addScheduledTask(() -> BaritoneToast.addOrUpdate(mc.getToastGui(), title, message, BaritoneAPI.getSettings().toastTimer.value));
}
/**
* Send a message to display as a toast popup
*
* @param title The title to display in the popup
* @param message The message to display in the popup
*/
default void logToast(String title, String message) {
logToast(new TextComponentString(title), new TextComponentString(message));
}
/**
* Send a message to display as a toast popup
*
* @param message The message to display in the popup
*/
default void logToast(String message) {
logToast(Helper.getPrefix(), new TextComponentString(message));
}
/**
* Send a message to chat only if chatDebug is on
*
@ -74,7 +104,31 @@ public interface Helper {
//System.out.println(message);
return;
}
logDirect(message);
// We won't log debug chat into toasts
// Because only a madman would want that extreme spam -_-
logDirect(message, false);
}
/**
* Send components to chat with the [Baritone] prefix
*
* @param logAsToast Whether to log as a toast notification
* @param components The components to send
*/
default void logDirect(boolean logAsToast, ITextComponent... components) {
ITextComponent component = new TextComponentString("");
if (!logAsToast) {
// If we are not logging as a Toast
// Append the prefix to the base component line
component.appendSibling(getPrefix());
component.appendSibling(new TextComponentString(" "));
}
Arrays.asList(components).forEach(component::appendSibling);
if (logAsToast) {
logToast(getPrefix(), component);
} else {
mc.addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component));
}
}
/**
@ -83,11 +137,23 @@ public interface Helper {
* @param components The components to send
*/
default void logDirect(ITextComponent... components) {
ITextComponent component = new TextComponentString("");
component.appendSibling(getPrefix());
component.appendSibling(new TextComponentString(" "));
Arrays.asList(components).forEach(component::appendSibling);
mc.addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component));
logDirect(BaritoneAPI.getSettings().logAsToast.value, components);
}
/**
* 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 color The color to print that message in
* @param logAsToast Whether to log as a toast notification
*/
default void logDirect(String message, TextFormatting color, boolean logAsToast) {
Stream.of(message.split("\n")).forEach(line -> {
ITextComponent component = new TextComponentString(line.replace("\t", " "));
component.getStyle().setColor(color);
logDirect(logAsToast, component);
});
}
/**
@ -98,11 +164,18 @@ public interface Helper {
* @param color The color to print that message in
*/
default void logDirect(String message, TextFormatting color) {
Stream.of(message.split("\n")).forEach(line -> {
ITextComponent component = new TextComponentString(line.replace("\t", " "));
component.getStyle().setColor(color);
logDirect(component);
});
logDirect(message, color, BaritoneAPI.getSettings().logAsToast.value);
}
/**
* 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 logAsToast Whether to log as a toast notification
*/
default void logDirect(String message, boolean logAsToast) {
logDirect(message, TextFormatting.GRAY, logAsToast);
}
/**
@ -112,6 +185,6 @@ public interface Helper {
* @param message The message to display in chat
*/
default void logDirect(String message) {
logDirect(message, TextFormatting.GRAY);
logDirect(message, BaritoneAPI.getSettings().logAsToast.value);
}
}

View File

@ -97,17 +97,4 @@ public interface IPlayerContext {
default boolean isLookingAt(BlockPos pos) {
return getSelectedBlock().equals(Optional.of(pos));
}
/**
* Returns the entity that the crosshair is currently placed over. Updated once per tick.
*
* @return The entity
*/
default Optional<Entity> getSelectedEntity() {
RayTraceResult result = objectMouseOver();
if (result != null && result.type == RayTraceResult.Type.ENTITY) {
return Optional.of(result.entity);
}
return Optional.empty();
}
}

View File

@ -0,0 +1,74 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.utils.gui;
import net.minecraft.client.gui.toasts.GuiToast;
import net.minecraft.client.gui.toasts.IToast;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
public class BaritoneToast implements IToast {
private String title;
private String subtitle;
private long firstDrawTime;
private boolean newDisplay;
private long totalShowTime;
public BaritoneToast(ITextComponent titleComponent, ITextComponent subtitleComponent, long totalShowTime) {
this.title = titleComponent.getFormattedText();
this.subtitle = subtitleComponent == null ? null : subtitleComponent.getFormattedText();
this.totalShowTime = totalShowTime;
}
public Visibility draw(GuiToast toastGui, long delta) {
if (this.newDisplay) {
this.firstDrawTime = delta;
this.newDisplay = false;
}
toastGui.getMinecraft().getTextureManager().bindTexture(new ResourceLocation("textures/gui/toasts.png"));
GlStateManager.color4f(1.0F, 1.0F, 1.0F, 255.0f);
toastGui.drawTexturedModalRect(0, 0, 0, 32, 160, 32);
if (this.subtitle == null) {
toastGui.getMinecraft().fontRenderer.drawString(this.title, 18, 12, -11534256);
} else {
toastGui.getMinecraft().fontRenderer.drawString(this.title, 18, 7, -11534256);
toastGui.getMinecraft().fontRenderer.drawString(this.subtitle, 18, 18, -16777216);
}
return delta - this.firstDrawTime < totalShowTime ? Visibility.SHOW : Visibility.HIDE;
}
public void setDisplayedText(ITextComponent titleComponent, ITextComponent subtitleComponent) {
this.title = titleComponent.getFormattedText();
this.subtitle = subtitleComponent == null ? null : subtitleComponent.getFormattedText();
this.newDisplay = true;
}
public static void addOrUpdate(GuiToast toast, ITextComponent title, ITextComponent subtitle, long totalShowTime) {
BaritoneToast baritonetoast = toast.getToast(BaritoneToast.class, new Object());
if (baritonetoast == null) {
toast.add(new BaritoneToast(title, subtitle, totalShowTime));
} else {
baritonetoast.setDisplayedText(title, subtitle);
}
}
}

View File

@ -17,15 +17,16 @@
package baritone.launch.mixins;
import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.ChunkEvent;
import baritone.api.event.events.type.EventState;
import baritone.cache.CachedChunk;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.network.play.server.SPacketChunkData;
import net.minecraft.network.play.server.SPacketCombatEvent;
import net.minecraft.network.play.server.SPacketUnloadChunk;
import net.minecraft.network.play.server.*;
import net.minecraft.util.math.ChunkPos;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
@ -111,6 +112,68 @@ public class MixinNetHandlerPlayClient {
}
}
@Inject(
method = "handleBlockChange",
at = @At("RETURN")
)
private void postHandleBlockChange(SPacketBlockChange packetIn, CallbackInfo ci) {
if (!Baritone.settings().repackOnAnyBlockChange.value) {
return;
}
if (!CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(packetIn.getState().getBlock())) {
return;
}
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
EntityPlayerSP player = ibaritone.getPlayerContext().player();
if (player != null && player.connection == (NetHandlerPlayClient) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.POST,
ChunkEvent.Type.POPULATE_FULL,
packetIn.getPos().getX() >> 4,
packetIn.getPos().getZ() >> 4
)
);
}
}
}
@Inject(
method = "handleMultiBlockChange",
at = @At("RETURN")
)
private void postHandleMultiBlockChange(SPacketMultiBlockChange packetIn, CallbackInfo ci) {
if (!Baritone.settings().repackOnAnyBlockChange.value) {
return;
}
if (packetIn.getChangedBlocks().length == 0) {
return;
}
https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.15
{
for (SPacketMultiBlockChange.BlockUpdateData update : packetIn.getChangedBlocks()) {
if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(update.getBlockState().getBlock())) {
break https;
}
}
return;
}
ChunkPos pos = new ChunkPos(packetIn.getChangedBlocks()[0].getPos());
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
EntityPlayerSP player = ibaritone.getPlayerContext().player();
if (player != null && player.connection == (NetHandlerPlayClient) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.POST,
ChunkEvent.Type.POPULATE_FULL,
pos.x,
pos.z
)
);
}
}
}
@Inject(
method = "handleCombatEvent",
at = @At(

View File

@ -104,14 +104,14 @@ public class Baritone implements IBaritone {
this.pathingControlManager = new PathingControlManager(this);
{
followProcess = new FollowProcess(this);
mineProcess = new MineProcess(this);
customGoalProcess = new CustomGoalProcess(this); // very high iq
getToBlockProcess = new GetToBlockProcess(this);
builderProcess = new BuilderProcess(this);
exploreProcess = new ExploreProcess(this);
backfillProcess = new BackfillProcess(this);
farmProcess = new FarmProcess(this);
this.pathingControlManager.registerProcess(followProcess = new FollowProcess(this));
this.pathingControlManager.registerProcess(mineProcess = new MineProcess(this));
this.pathingControlManager.registerProcess(customGoalProcess = new CustomGoalProcess(this)); // very high iq
this.pathingControlManager.registerProcess(getToBlockProcess = new GetToBlockProcess(this));
this.pathingControlManager.registerProcess(builderProcess = new BuilderProcess(this));
this.pathingControlManager.registerProcess(exploreProcess = new ExploreProcess(this));
this.pathingControlManager.registerProcess(backfillProcess = new BackfillProcess(this));
this.pathingControlManager.registerProcess(farmProcess = new FarmProcess(this));
}
this.worldProvider = new WorldProvider();

View File

@ -22,7 +22,7 @@ import baritone.api.IBaritoneProvider;
import baritone.api.cache.IWorldScanner;
import baritone.api.command.ICommandSystem;
import baritone.api.schematic.ISchematicSystem;
import baritone.command.BaritoneChatControl;
import baritone.command.ExampleBaritoneControl;
import baritone.cache.WorldScanner;
import baritone.command.CommandSystem;
import baritone.utils.schematic.SchematicSystem;
@ -44,7 +44,7 @@ public final class BaritoneProvider implements IBaritoneProvider {
this.all = Collections.singletonList(this.primary);
// Setup chat control, just for the primary instance
new BaritoneChatControl(this.primary);
new ExampleBaritoneControl(this.primary);
}
@Override

View File

@ -0,0 +1,21 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone;
// Annotation for classes and class members that should not be renamed by proguard
public @interface KeepName { }

View File

@ -26,6 +26,7 @@ import baritone.api.utils.Helper;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.chunk.Chunk;
import java.io.IOException;
@ -33,6 +34,8 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
/**
@ -56,7 +59,17 @@ public final class CachedWorld implements ICachedWorld, Helper {
*/
private final String directory;
private final LinkedBlockingQueue<Chunk> toPack = new LinkedBlockingQueue<>();
/**
* Queue of positions to pack. Refers to the toPackMap, in that every element of this queue will be a
* key in that map.
*/
private final LinkedBlockingQueue<ChunkPos> toPackQueue = new LinkedBlockingQueue<>();
/**
* All chunk positions pending packing. This map will be updated in-place if a new update to the chunk occurs
* while waiting in the queue for the packer thread to get to it.
*/
private final Map<ChunkPos, Chunk> toPackMap = new ConcurrentHashMap<>();
private final int dimension;
@ -89,10 +102,8 @@ public final class CachedWorld implements ICachedWorld, Helper {
@Override
public final void queueForPacking(Chunk chunk) {
try {
toPack.put(chunk);
} catch (InterruptedException e) {
e.printStackTrace();
if (toPackMap.put(chunk.getPos(), chunk) == null) {
toPackQueue.add(chunk.getPos());
}
}
@ -293,13 +304,9 @@ public final class CachedWorld implements ICachedWorld, Helper {
public void run() {
while (true) {
// TODO: Add CachedWorld unloading to remove the redundancy of having this
LinkedBlockingQueue<Chunk> queue = toPack;
if (queue == null) {
break;
}
try {
Chunk chunk = queue.take();
ChunkPos pos = toPackQueue.take();
Chunk chunk = toPackMap.remove(pos);
CachedChunk cached = ChunkPacker.pack(chunk);
CachedWorld.this.updateCachedChunk(cached);
//System.out.println("Processed chunk at " + chunk.x + "," + chunk.z);

View File

@ -49,12 +49,12 @@ import java.util.stream.Stream;
import static baritone.api.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX;
public class BaritoneChatControl implements Helper, AbstractGameEventListener {
public class ExampleBaritoneControl implements Helper, AbstractGameEventListener {
private static final Settings settings = BaritoneAPI.getSettings();
private final ICommandManager manager;
public BaritoneChatControl(IBaritone baritone) {
public ExampleBaritoneControl(IBaritone baritone) {
this.manager = baritone.getCommandManager();
baritone.getGameEventHandler().registerEventListener(this);
}

View File

@ -46,7 +46,7 @@ public class BuildCommand extends Command {
public void execute(String label, IArgConsumer args) throws CommandException {
File file = args.getDatatypePost(RelativeFile.INSTANCE, schematicsDir).getAbsoluteFile();
if (FilenameUtils.getExtension(file.getAbsolutePath()).isEmpty()) {
file = new File(file.getAbsolutePath() + "." + Baritone.settings().schematicFallbackExtension);
file = new File(file.getAbsolutePath() + "." + Baritone.settings().schematicFallbackExtension.value);
}
BetterBlockPos origin = ctx.playerFeet();
BetterBlockPos buildOrigin;

View File

@ -60,10 +60,11 @@ public final class DefaultCommands {
new FindCommand(baritone),
new MineCommand(baritone),
new ClickCommand(baritone),
new SurfaceCommand(baritone),
new ThisWayCommand(baritone),
new WaypointsCommand(baritone),
new CommandAlias(baritone, "sethome", "Sets your home waypoint", "waypoints save home"),
new CommandAlias(baritone, "home", "Set goal to your home waypoint", "waypoints goal home"),
new CommandAlias(baritone, "home", "Path to your home waypoint", "waypoints goto home"),
new SelCommand(baritone)
));
ExecutionControlCommands prc = new ExecutionControlCommands(baritone);

View File

@ -79,7 +79,7 @@ public class ExecutionControlCommands {
}
}
);
pauseCommand = new Command(baritone, "pause") {
pauseCommand = new Command(baritone, "pause", "p") {
@Override
public void execute(String label, IArgConsumer args) throws CommandException {
args.requireMax(0);
@ -112,7 +112,7 @@ public class ExecutionControlCommands {
);
}
};
resumeCommand = new Command(baritone, "resume") {
resumeCommand = new Command(baritone, "resume", "r") {
@Override
public void execute(String label, IArgConsumer args) throws CommandException {
args.requireMax(0);
@ -171,7 +171,7 @@ public class ExecutionControlCommands {
);
}
};
cancelCommand = new Command(baritone, "cancel", "stop") {
cancelCommand = new Command(baritone, "cancel", "c", "stop") {
@Override
public void execute(String label, IArgConsumer args) throws CommandException {
args.requireMax(0);

View File

@ -17,6 +17,7 @@
package baritone.command.defaults;
import baritone.KeepName;
import baritone.api.IBaritone;
import baritone.api.command.Command;
import baritone.api.command.datatypes.EntityClassById;
@ -131,6 +132,7 @@ public class FollowCommand extends Command {
);
}
@KeepName
private enum FollowGroup {
ENTITIES(EntityLiving.class::isInstance),
PLAYERS(EntityPlayer.class::isInstance); /* ,
@ -143,6 +145,7 @@ public class FollowCommand extends Command {
}
}
@KeepName
private enum FollowList {
ENTITY(EntityClassById.INSTANCE),
PLAYER(NearbyPlayer.INSTANCE);

View File

@ -72,7 +72,7 @@ public class GotoCommand extends Command {
@Override
public List<String> getLongDesc() {
return Arrays.asList(
"The got command tells Baritone to head towards a given goal or block.",
"The goto command tells Baritone to head towards a given goal or block.",
"",
"Wherever a coordinate is expected, you can use ~ just like in regular Minecraft commands. Or, you can just use regular numbers.",
"",

View File

@ -0,0 +1,89 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.command.defaults;
import baritone.api.IBaritone;
import baritone.api.command.Command;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.utils.BetterBlockPos;
import net.minecraft.block.BlockAir;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class SurfaceCommand extends Command {
protected SurfaceCommand(IBaritone baritone) {
super(baritone, "surface", "top");
}
@Override
public void execute(String label, IArgConsumer args) throws CommandException {
final BetterBlockPos playerPos = baritone.getPlayerContext().playerFeet();
final int surfaceLevel = baritone.getPlayerContext().world().getSeaLevel();
final int worldHeight = baritone.getPlayerContext().world().getActualHeight();
// Ensure this command will not run if you are above the surface level and the block above you is air
// As this would imply that your are already on the open surface
if (playerPos.getY() > surfaceLevel && mc.world.getBlockState(playerPos.up()).getBlock() instanceof BlockAir) {
logDirect("Already at surface");
return;
}
final int startingYPos = Math.max(playerPos.getY(), surfaceLevel);
for (int currentIteratedY = startingYPos; currentIteratedY < worldHeight; currentIteratedY++) {
final BetterBlockPos newPos = new BetterBlockPos(playerPos.getX(), currentIteratedY, playerPos.getZ());
if (!(mc.world.getBlockState(newPos).getBlock() instanceof BlockAir) && newPos.getY() > playerPos.getY()) {
Goal goal = new GoalBlock(newPos.up());
logDirect(String.format("Going to: %s", goal.toString()));
baritone.getCustomGoalProcess().setGoalAndPath(goal);
return;
}
}
logDirect("No higher location found");
}
@Override
public Stream<String> tabComplete(String label, IArgConsumer args) {
return Stream.empty();
}
@Override
public String getShortDesc() {
return "Used to get out of caves, mines, ...";
}
@Override
public List<String> getLongDesc() {
return Arrays.asList(
"The surface/top command tells Baritone to head towards the closest surface-like area.",
"",
"This can be the surface or the highest available air space, depending on circumstances.",
"",
"Usage:",
"> surface - Used to get out of caves, mines, ...",
"> top - Used to get out of caves, mines, ..."
);
}
}

View File

@ -235,6 +235,10 @@ public class WaypointsCommand extends Command {
Goal goal = new GoalBlock(waypoint.getLocation());
baritone.getCustomGoalProcess().setGoal(goal);
logDirect(String.format("Goal: %s", goal));
} else if (action == Action.GOTO) {
Goal goal = new GoalBlock(waypoint.getLocation());
baritone.getCustomGoalProcess().setGoalAndPath(goal);
logDirect(String.format("Going to: %s", goal));
}
}
}
@ -292,7 +296,8 @@ public class WaypointsCommand extends Command {
"> wp <s/save> <tag> <name> <pos> - Save the waypoint with the specified name and position.",
"> wp <i/info/show> <tag> - Show info on a waypoint by tag.",
"> wp <d/delete> <tag> - Delete a waypoint by tag.",
"> wp <g/goal/goto> <tag> - Set a goal to a waypoint by tag."
"> wp <g/goal> <tag> - Set a goal to a waypoint by tag.",
"> wp <goto> <tag> - Set a goal to a waypoint by tag and start pathing."
);
}
@ -302,7 +307,8 @@ public class WaypointsCommand extends Command {
SAVE("save", "s"),
INFO("info", "show", "i"),
DELETE("delete", "d"),
GOAL("goal", "goto", "g");
GOAL("goal", "g"),
GOTO("goto");
private final String[] names;
Action(String... names) {

View File

@ -441,7 +441,9 @@ public interface MovementHelper extends ActionCosts, Helper {
* @param ts previously calculated ToolSet
*/
static void switchToBestToolFor(IPlayerContext ctx, IBlockState b, ToolSet ts, boolean preferSilkTouch) {
ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock(), preferSilkTouch);
if (!Baritone.settings().disableAutoTool.value && !Baritone.settings().assumeExternalAutoTool.value) {
ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock(), preferSilkTouch);
}
}
static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) {
@ -576,4 +578,11 @@ public interface MovementHelper extends ActionCosts, Helper {
enum PlaceResult {
READY_TO_PLACE, ATTEMPTING, NO_OPTION;
}
static boolean isTransparent(Block b) {
return b == Blocks.AIR ||
b == Blocks.LAVA ||
b == Blocks.WATER;
}
}

View File

@ -31,6 +31,7 @@ import baritone.utils.pathing.MutableMoveResult;
import com.google.common.collect.ImmutableSet;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
@ -56,6 +57,35 @@ public class MovementDiagonal extends Movement {
super(baritone, start, end, new BetterBlockPos[]{dir1, dir1.up(), dir2, dir2.up(), end, end.up()});
}
@Override
protected boolean safeToCancel(MovementState state) {
//too simple. backfill does not work after cornering with this
//return MovementHelper.canWalkOn(ctx, ctx.playerFeet().down());
EntityPlayerSP player = ctx.player();
double offset = 0.25;
double x = player.posX;
double y = player.posY - 1;
double z = player.posZ;
//standard
if (ctx.playerFeet().equals(src)){
return true;
}
//both corners are walkable
if (MovementHelper.canWalkOn(ctx, new BlockPos(src.x, src.y - 1, dest.z))
&& MovementHelper.canWalkOn(ctx, new BlockPos(dest.x, src.y - 1, src.z))){
return true;
}
//we are in a likely unwalkable corner, check for a supporting block
if (ctx.playerFeet().equals(new BetterBlockPos(src.x, src.y, dest.z))
|| ctx.playerFeet().equals(new BetterBlockPos(dest.x, src.y, src.z))){
return (MovementHelper.canWalkOn(ctx, new BetterBlockPos(x + offset, y, z + offset))
|| MovementHelper.canWalkOn(ctx, new BetterBlockPos(x + offset, y, z - offset))
|| MovementHelper.canWalkOn(ctx, new BetterBlockPos(x - offset, y, z + offset))
|| MovementHelper.canWalkOn(ctx, new BetterBlockPos(x - offset, y, z - offset)));
}
return true;
}
@Override
public double calculateCost(CalculationContext context) {
MutableMoveResult result = new MutableMoveResult();

View File

@ -39,6 +39,7 @@ import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.BaritoneProcessHelper;
import baritone.utils.BlockStateInterface;
import baritone.utils.NotificationHelper;
import baritone.utils.PathingCommandContext;
import baritone.utils.schematic.MapArtSchematic;
import baritone.utils.schematic.SchematicSystem;
@ -100,7 +101,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
}
this.origin = new Vec3i(x, y, z);
this.paused = false;
this.layer = 0;
this.layer = Baritone.settings().startAtLayer.value;
this.numRepeats = 0;
this.observedCompleted = new LongOpenHashSet();
}
@ -423,6 +424,9 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
numRepeats++;
if (repeat.equals(new Vec3i(0, 0, 0)) || (max != -1 && numRepeats >= max)) {
logDirect("Done building");
if (Baritone.settings().desktopNotifications.value && Baritone.settings().notificationOnBuildFinished.value) {
NotificationHelper.notify("Done building", false);
}
onLostControl();
return null;
}
@ -497,6 +501,11 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (goal == null) {
goal = assemble(bcc, approxPlaceable); // we're far away, so assume that we have our whole inventory to recalculate placeable properly
if (goal == null) {
if (Baritone.settings().skipFailedLayers.value && Baritone.settings().buildInLayers.value && layer < realSchematic.heightY()) {
logDirect("Skipping layer that I cannot construct! Layer #" + layer);
layer++;
return onTick(calcFailed, isSafeToCancel);
}
logDirect("Unable to do it. Pausing. resume to resume, cancel to cancel");
paused = true;
return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE);
@ -760,7 +769,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
name = null;
schematic = null;
realSchematic = null;
layer = 0;
layer = Baritone.settings().startAtLayer.value;
numRepeats = 0;
paused = false;
observedCompleted = null;
@ -796,7 +805,9 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if ((current.getBlock() == Blocks.WATER || current.getBlock() == Blocks.LAVA) && Baritone.settings().okIfWater.value) {
return true;
}
// TODO more complicated comparison logic I guess
if (current.getBlock() instanceof BlockAir && Baritone.settings().okIfAir.value.contains(desired.getBlock())) {
return true;
}
if (desired.getBlock() instanceof BlockAir && Baritone.settings().buildIgnoreBlocks.value.contains(current.getBlock())) {
return true;
}

View File

@ -23,6 +23,7 @@ import baritone.api.process.ICustomGoalProcess;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.utils.BaritoneProcessHelper;
import baritone.utils.NotificationHelper;
/**
* As set by ExampleBaritoneControl or something idk
@ -93,6 +94,9 @@ public final class CustomGoalProcess extends BaritoneProcessHelper implements IC
if (Baritone.settings().disconnectOnArrival.value) {
ctx.world().sendQuittingDisconnectingPacket();
}
if (Baritone.settings().desktopNotifications.value && Baritone.settings().notificationOnPathComplete.value) {
NotificationHelper.notify("Pathing complete", false);
}
return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL);
}
return new PathingCommand(this.goal, PathingCommandType.SET_GOAL_AND_PATH);

View File

@ -29,6 +29,7 @@ import baritone.api.process.PathingCommandType;
import baritone.api.utils.MyChunkPos;
import baritone.cache.CachedWorld;
import baritone.utils.BaritoneProcessHelper;
import baritone.utils.NotificationHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
@ -83,12 +84,18 @@ public final class ExploreProcess extends BaritoneProcessHelper implements IExpl
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
if (calcFailed) {
logDirect("Failed");
if (Baritone.settings().desktopNotifications.value && Baritone.settings().notificationOnExploreFinished.value) {
NotificationHelper.notify("Exploration failed", true);
}
onLostControl();
return null;
}
IChunkFilter filter = calcFilter();
if (!Baritone.settings().disableCompletionCheck.value && filter.countRemain() == 0) {
logDirect("Explored all chunks");
if (Baritone.settings().desktopNotifications.value && Baritone.settings().notificationOnExploreFinished.value) {
NotificationHelper.notify("Explored all chunks", false);
}
onLostControl();
return null;
}

View File

@ -31,6 +31,7 @@ import baritone.api.utils.input.Input;
import baritone.cache.WorldScanner;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.BaritoneProcessHelper;
import baritone.utils.NotificationHelper;
import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
@ -255,6 +256,9 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
if (calcFailed) {
logDirect("Farm failed");
if (Baritone.settings().desktopNotifications.value && Baritone.settings().notificationOnFarmFail.value) {
NotificationHelper.notify("Farm failed", true);
}
onLostControl();
return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE);
}

View File

@ -30,6 +30,7 @@ import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.BaritoneProcessHelper;
import baritone.utils.BlockStateInterface;
import baritone.utils.NotificationHelper;
import net.minecraft.block.Block;
import net.minecraft.block.BlockAir;
import net.minecraft.block.BlockFalling;
@ -88,10 +89,16 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
if (calcFailed) {
if (!knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) {
logDirect("Unable to find any path to " + filter + ", blacklisting presumably unreachable closest instance...");
if (Baritone.settings().desktopNotifications.value && Baritone.settings().notificationOnMineFail.value) {
NotificationHelper.notify("Unable to find any path to " + filter + ", blacklisting presumably unreachable closest instance...", true);
}
knownOreLocations.stream().min(Comparator.comparingDouble(ctx.player()::getDistanceSq)).ifPresent(blacklist::add);
knownOreLocations.removeIf(blacklist::contains);
} else {
logDirect("Unable to find any path to " + filter + ", canceling mine");
if (Baritone.settings().desktopNotifications.value && Baritone.settings().notificationOnMineFail.value) {
NotificationHelper.notify("Unable to find any path to " + filter + ", canceling mine", true);
}
cancel();
return null;
}
@ -221,6 +228,9 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
locs.addAll(dropped);
if (locs.isEmpty()) {
logDirect("No locations for " + filter + " known, cancelling");
if (Baritone.settings().desktopNotifications.value && Baritone.settings().notificationOnMineFail.value) {
NotificationHelper.notify("No locations for " + filter + " known, cancelling", true);
}
cancel();
return;
}
@ -399,6 +409,16 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
// remove any that are implausible to mine (encased in bedrock, or touching lava)
.filter(pos -> MineProcess.plausibleToBreak(ctx, pos))
.filter(pos -> {
if (Baritone.settings().allowOnlyExposedOres.value) {
return isNextToAir(ctx, pos);
} else {
return true;
}
})
.filter(pos -> pos.getY() >= Baritone.settings().minYLevelWhileMining.value)
.filter(pos -> !blacklist.contains(pos))
.sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().player()::getDistanceSq))
@ -410,6 +430,22 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
return locs;
}
public static boolean isNextToAir(CalculationContext ctx, BlockPos pos) {
int radius = Baritone.settings().allowOnlyExposedOresDistance.value;
for (int dx = -radius; dx <= radius; dx++) {
for (int dy = -radius; dy <= radius; dy++) {
for (int dz = -radius; dz <= radius; dz++) {
if (Math.abs(dx) + Math.abs(dy) + Math.abs(dz) <= radius
&& MovementHelper.isTransparent(ctx.getBlock(pos.getX() + dx, pos.getY() + dy, pos.getZ() + dz))) {
return true;
}
}
}
}
return false;
}
public static boolean plausibleToBreak(CalculationContext ctx, BlockPos pos) {
if (MovementHelper.getMiningDurationTicks(ctx, pos.getX(), pos.getY(), pos.getZ(), ctx.bsi.get0(pos), true) >= COST_INF) {
return false;

View File

@ -30,7 +30,6 @@ public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper
public BaritoneProcessHelper(Baritone baritone) {
this.baritone = baritone;
this.ctx = baritone.getPlayerContext();
baritone.getPathingControlManager().registerProcess(this);
}
@Override

View File

@ -20,7 +20,6 @@ package baritone.utils;
import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.pathing.goals.GoalTwoBlocks;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.Helper;
import net.minecraft.client.gui.GuiScreen;
@ -78,24 +77,26 @@ public class GuiClick extends GuiScreen {
@Override
public boolean mouseReleased(double mouseX, double mouseY, int mouseButton) {
if (mouseButton == 0) {
if (clickStart != null && !clickStart.equals(currentMouseOver)) {
BaritoneAPI.getProvider().getPrimaryBaritone().getSelectionManager().removeAllSelections();
BaritoneAPI.getProvider().getPrimaryBaritone().getSelectionManager().addSelection(BetterBlockPos.from(clickStart), BetterBlockPos.from(currentMouseOver));
ITextComponent component = new TextComponentString("Selection made! For usage: " + Baritone.settings().prefix.value + "help sel");
component.getStyle()
.setColor(TextFormatting.WHITE)
.setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
FORCE_COMMAND_PREFIX + "help sel"
));
Helper.HELPER.logDirect(component);
clickStart = null;
} else {
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalTwoBlocks(currentMouseOver));
if (currentMouseOver != null) { //Catch this, or else a click into void will result in a crash
if (mouseButton == 0) {
if (clickStart != null && !clickStart.equals(currentMouseOver)) {
BaritoneAPI.getProvider().getPrimaryBaritone().getSelectionManager().removeAllSelections();
BaritoneAPI.getProvider().getPrimaryBaritone().getSelectionManager().addSelection(BetterBlockPos.from(clickStart), BetterBlockPos.from(currentMouseOver));
ITextComponent component = new TextComponentString("Selection made! For usage: " + Baritone.settings().prefix.value + "help sel");
component.getStyle()
.setColor(TextFormatting.WHITE)
.setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
FORCE_COMMAND_PREFIX + "help sel"
));
Helper.HELPER.logDirect(component);
clickStart = null;
} else {
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(currentMouseOver));
}
} else if (mouseButton == 1) {
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(currentMouseOver.up()));
}
} else if (mouseButton == 1) {
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(currentMouseOver.up()));
}
clickStart = null;
return super.mouseReleased(mouseX, mouseY, mouseButton);

View File

@ -45,7 +45,6 @@ public interface IRenderer {
static void startLines(Color color, float alpha, float lineWidth, boolean ignoreDepth) {
GlStateManager.enableBlend();
GlStateManager.disableLighting();
GlStateManager.blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
glColor(color, alpha);
GlStateManager.lineWidth(lineWidth);
@ -68,7 +67,6 @@ public interface IRenderer {
GlStateManager.depthMask(true);
GlStateManager.enableTexture2D();
GlStateManager.enableLighting();
GlStateManager.disableBlend();
}

View File

@ -89,12 +89,27 @@ public class ToolSet {
}
/**
* Calculate which tool on the hotbar is best for mining
* Calculate which tool on the hotbar is best for mining, depending on an override setting,
* related to auto tool movement cost, it will either return current selected slot, or the best slot.
*
* @param b the blockstate to be mined
* @return An int containing the index in the tools array that worked best
*/
public int getBestSlot(Block b, boolean preferSilkTouch) {
return getBestSlot(b, preferSilkTouch, false);
}
public int getBestSlot(Block b, boolean preferSilkTouch, boolean pathingCalculation) {
/*
If we actually want know what efficiency our held item has instead of the best one
possible, this lets us make pathing depend on the actual tool to be used (if auto tool is disabled)
*/
if (Baritone.settings().disableAutoTool.value && pathingCalculation) {
return player.inventory.currentItem;
}
int best = 0;
double highestSpeed = Double.NEGATIVE_INFINITY;
int lowestCost = Integer.MIN_VALUE;
@ -130,7 +145,7 @@ public class ToolSet {
* @return A double containing the destruction ticks with the best tool
*/
private double getBestDestructionTime(Block b) {
ItemStack stack = player.inventory.getStackInSlot(getBestSlot(b, false));
ItemStack stack = player.inventory.getStackInSlot(getBestSlot(b, false, true));
return calculateSpeedVsBlock(stack, b.getDefaultState()) * avoidanceMultiplier(b);
}