Compare commits

..

18 Commits

Author SHA1 Message Date
Leijurv e661330fb6 v1.0.0-hotfix-4 2018-12-04 14:19:20 -08:00
Leijurv 9b13380b29 fixed switched block states in traverse 2018-12-04 14:18:32 -08:00
Leijurv b48444da8c don't splice if not on ground 2018-12-01 10:48:43 -08:00
Leijurv 11a4225eaf fix inability to break fire 2018-11-29 20:10:04 -08:00
Leijurv 0611e3088e cherry pick flowing cache fix 2018-11-28 16:04:13 -08:00
Leijurv 73628f09c1 don't crash when Auto mine does weird things 2018-11-27 10:23:26 -08:00
Leijurv a907746f53 only walk through supported snow, fixes #276 2018-11-26 15:33:33 -08:00
Leijurv 8189e90569 unable to start a parkour jump from stairs 2018-11-26 15:19:03 -08:00
Leijurv 9f83677df9 favored lookup performance 2018-11-26 15:11:36 -08:00
Leijurv 5265c46f60 over 10k less objects per second 2018-11-26 15:08:37 -08:00
Leijurv 6d37e14b0e thousands here too, on long paths 2018-11-26 15:07:38 -08:00
Leijurv fbecff52af believe it or not, this saves thousands of object allocations per second 2018-11-26 15:07:29 -08:00
Leijurv 4af14cf0a6 unneeded, and was allocating thousands of sets a second 2018-11-26 15:07:12 -08:00
Leijurv 16a201255e fix behavior around cocoa pods and vines, fixes #277 2018-11-26 15:03:59 -08:00
Leijurv 22bb9f0ec8 v1.0.0-hotfix-3 2018-11-12 09:07:48 -08:00
Leijurv 654ac1075a wait a tick until objectMouseOver matches, fixes #254 2018-11-10 09:26:32 -08:00
Leijurv ffc050668b fix cherry pick merge errors 2018-11-07 10:01:58 -08:00
Leijurv 80f65452e1 make sure to pick up dropped items while mining, fixes #170 2018-11-07 09:56:47 -08:00
147 changed files with 2700 additions and 5604 deletions
+11 -14
View File
@@ -1,30 +1,25 @@
# Baritone
[![Build Status](https://travis-ci.com/cabaletta/baritone.svg?branch=master)](https://travis-ci.com/cabaletta/baritone)
[![Release](https://img.shields.io/github/release/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/releases)
[![License](https://img.shields.io/badge/license-LGPL--3.0-green.svg)](LICENSE)
[![License](https://img.shields.io/github/license/cabaletta/baritone.svg)](LICENSE)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&utm_medium=referral&utm_content=cabaletta/baritone&utm_campaign=Badge_Grade)
[![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone)
[![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)
[![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2)
[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.0.0--hotfix--4-brightgreen.svg)](https://impactdevelopment.github.io/)
[![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-orange.svg)](https://github.com/zeroeightysix/KAMI/)
[![Asuna integration](https://img.shields.io/badge/Asuna%20integration-v1.0.0-orange.svg)](https://github.com/EmotionalLove/Asuna/)
[![Future integration](https://img.shields.io/badge/Future%20integration-%3F%3F%3F-red.svg)](https://futureclient.net/)
A Minecraft pathfinder bot.
A Minecraft pathfinder bot. This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/),
the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths).
Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do.
This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/),
the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [29x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths).
Here are some links to help to get started:
- [Features](FEATURES.md)
- [Installation](INSTALL.md)
There's also some useful information down below
# Setup
## Command Line
@@ -41,11 +36,12 @@ Building Baritone:
$ gradlew build
```
To replace out Impact 4.4's Baritone build with a customized one, switch to the `impact4.4-compat` branch, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`).
For example, to replace out Impact 4.4's Baritone build with a customized one, build Baritone as above then copy `dist/baritone-api-$VERSION.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`).
## IntelliJ's Gradle UI
- Open the project in IntelliJ as a Gradle project
- Run the Gradle tasks `setupDecompWorkspace` then `genIntellijRuns`
- Run the Gradle task `setupDecompWorkspace`
- Run the Gradle task `genIntellijRuns`
- Refresh the Gradle project (or, to be safe, just restart IntelliJ)
- Select the "Minecraft Client" launch config
- In `Edit Configurations...` you may need to select `baritone_launch` for `Use classpath of module:`.
@@ -61,12 +57,13 @@ Quick start example: `thisway 1000` or `goal 70` to set the goal, `path` to actu
BaritoneAPI.getSettings().allowSprint.value = true;
BaritoneAPI.getSettings().pathTimeoutMS.value = 2000L;
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalXZ(10000, 20000));
BaritoneAPI.getPathingBehavior().setGoal(new GoalXZ(10000, 20000));
BaritoneAPI.getPathingBehavior().path();
```
# FAQ
## Can I use Baritone as a library in my custom utility client?
## Can I use Baritone as a library in my hacked client?
Sure! (As long as usage is in compliance with the LGPL 3 License)
+3 -7
View File
@@ -16,7 +16,7 @@
*/
group 'baritone'
version '1.0.0-hotfix-2'
version '1.0.0-hotfix-4'
buildscript {
repositories {
@@ -58,7 +58,7 @@ sourceSets {
minecraft {
version = '1.12.2'
mappings = 'stable_39'
mappings = 'snapshot_20180731'
tweakClass = 'baritone.launch.BaritoneTweaker'
runDir = 'run'
@@ -98,11 +98,6 @@ mixin {
add sourceSets.launch, 'mixins.baritone.refmap.json'
}
javadoc {
source = sourceSets.api.allJava
classpath = sourceSets.api.compileClasspath
}
jar {
from sourceSets.launch.output, sourceSets.api.output
preserveFileTimestamps = false
@@ -112,6 +107,7 @@ jar {
task proguard(type: ProguardTask) {
url 'https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip'
extract 'proguard6.0.3/lib/proguard.jar'
versionManifest 'https://launchermeta.mojang.com/mc/game/version_manifest.json'
}
task createDist(type: CreateDistTask, dependsOn: proguard)
@@ -18,26 +18,21 @@
package baritone.gradle.task;
import baritone.gradle.util.Determinizer;
import baritone.gradle.util.MappingType;
import baritone.gradle.util.ReobfWrapper;
import com.google.gson.*;
import org.apache.commons.io.IOUtils;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.internal.plugins.DefaultConvention;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.TaskAction;
import org.gradle.internal.Pair;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@@ -57,6 +52,10 @@ public class ProguardTask extends BaritoneGradleTask {
@Input
private String extract;
@Input
private String versionManifest;
private Map<String, String> versionDownloadMap;
private List<String> requiredLibraries;
@TaskAction
@@ -68,6 +67,7 @@ public class ProguardTask extends BaritoneGradleTask {
downloadProguard();
extractProguard();
generateConfigs();
downloadVersionManifest();
acquireDependencies();
proguardApi();
proguardStandalone();
@@ -132,6 +132,20 @@ public class ProguardTask extends BaritoneGradleTask {
});
}
private void downloadVersionManifest() throws Exception {
Path manifestJson = getTemporaryFile(VERSION_MANIFEST);
write(new URL(this.versionManifest).openStream(), manifestJson);
// Place all the versions in the map with their download URL
this.versionDownloadMap = new HashMap<>();
JsonObject json = readJson(Files.readAllLines(manifestJson)).getAsJsonObject();
JsonArray versions = json.getAsJsonArray("versions");
versions.forEach(element -> {
JsonObject object = element.getAsJsonObject();
this.versionDownloadMap.put(object.get("id").getAsString(), object.get("url").getAsString());
});
}
private void acquireDependencies() throws Exception {
// Create a map of all of the dependencies that we are able to access in this project
@@ -149,13 +163,15 @@ public class ProguardTask extends BaritoneGradleTask {
// Iterate the required libraries to copy them to tempLibraries
for (String lib : this.requiredLibraries) {
// copy from the forgegradle cache
if (lib.equals("minecraft")) {
Path cachedJar = getMinecraftJar();
Path inTempDir = getTemporaryFile("tempLibraries/minecraft.jar");
// TODO: maybe try not to copy every time
Files.copy(cachedJar, inTempDir, REPLACE_EXISTING);
// Download the version jar from the URL acquired from the version manifest
if (lib.startsWith("minecraft")) {
String version = lib.split("-")[1];
Path versionJar = getTemporaryFile("tempLibraries/" + lib + ".jar");
if (!Files.exists(versionJar)) {
JsonObject versionJson = PARSER.parse(new InputStreamReader(new URL(this.versionDownloadMap.get(version)).openStream())).getAsJsonObject();
String url = versionJson.getAsJsonObject("downloads").getAsJsonObject("client").getAsJsonPrimitive("url").getAsString();
write(new URL(url).openStream(), versionJar);
}
continue;
}
@@ -179,89 +195,6 @@ public class ProguardTask extends BaritoneGradleTask {
}
}
// a bunch of epic stuff to get the path to the cached jar
private Path getMinecraftJar() throws Exception {
MappingType mappingType;
try {
mappingType = getMappingType();
} catch (Exception e) {
System.err.println("Failed to get mapping type, assuming NOTCH.");
mappingType = MappingType.NOTCH;
}
String suffix;
switch (mappingType) {
case NOTCH:
suffix = "";
break;
case SEARGE:
suffix = "-srgBin";
break;
case CUSTOM:
throw new IllegalStateException("Custom mappings not supported!");
default:
throw new IllegalStateException("Unknown mapping type: " + mappingType);
}
DefaultConvention convention = (DefaultConvention) this.getProject().getConvention();
Object extension = convention.getAsMap().get("minecraft");
Objects.requireNonNull(extension);
// for some reason cant use Class.forName
Class<?> class_baseExtension = extension.getClass().getSuperclass().getSuperclass().getSuperclass(); // <-- cursed
Field f_replacer = class_baseExtension.getDeclaredField("replacer");
f_replacer.setAccessible(true);
Object replacer = f_replacer.get(extension);
Class<?> class_replacementProvider = replacer.getClass();
Field replacement_replaceMap = class_replacementProvider.getDeclaredField("replaceMap");
replacement_replaceMap.setAccessible(true);
Map<String, Object> replacements = (Map) replacement_replaceMap.get(replacer);
String cacheDir = replacements.get("CACHE_DIR").toString() + "/net/minecraft";
String mcVersion = replacements.get("MC_VERSION").toString();
String mcpInsert = replacements.get("MAPPING_CHANNEL").toString() + "/" + replacements.get("MAPPING_VERSION").toString();
String fullJarName = "minecraft-" + mcVersion + suffix + ".jar";
String baseDir = String.format("%s/minecraft/%s/", cacheDir, mcVersion);
String jarPath;
if (mappingType == MappingType.SEARGE) {
jarPath = String.format("%s/%s/%s", baseDir, mcpInsert, fullJarName);
} else {
jarPath = baseDir + fullJarName;
}
jarPath = jarPath
.replace("/", File.separator)
.replace("\\", File.separator); // hecking regex
return new File(jarPath).toPath();
}
// throws IllegalStateException if mapping type is ambiguous or it fails to find it
private MappingType getMappingType() {
// if it fails to find this then its probably a forgegradle version problem
Set<Object> reobf = (NamedDomainObjectContainer<Object>) this.getProject().getExtensions().getByName("reobf");
List<MappingType> mappingTypes = getUsedMappingTypes(reobf);
long mappingTypesUsed = mappingTypes.size();
if (mappingTypesUsed == 0) {
throw new IllegalStateException("Failed to find mapping type (no jar task?)");
}
if (mappingTypesUsed > 1) {
throw new IllegalStateException("Ambiguous mapping type (multiple jars with different mapping types?)");
}
return mappingTypes.get(0);
}
private List<MappingType> getUsedMappingTypes(Set<Object> reobf) {
return reobf.stream()
.map(ReobfWrapper::new)
.map(ReobfWrapper::getMappingType)
.distinct()
.collect(Collectors.toList());
}
private void proguardApi() throws Exception {
runProguard(getTemporaryFile(PROGUARD_API_CONFIG));
Determinizer.determinize(this.proguardOut.toString(), this.artifactApiPath.toString());
@@ -286,6 +219,10 @@ public class ProguardTask extends BaritoneGradleTask {
this.extract = extract;
}
public void setVersionManifest(String versionManifest) {
this.versionManifest = versionManifest;
}
private void runProguard(Path config) throws Exception {
// Delete the existing proguard output file. Proguard probably handles this already, but why not do it ourselves
if (Files.exists(this.proguardOut)) {
@@ -315,7 +252,7 @@ public class ProguardTask extends BaritoneGradleTask {
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
} catch (final Exception e) {
e.printStackTrace();
}
}).start();
@@ -1,29 +0,0 @@
/*
* 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.gradle.util;
/**
* All credits go to AsmLibGradle and its contributors.
*
* @see <a href="https://github.com/pozzed/AsmLibGradle/blob/8f917dbc3939eab7a3d9daf54d9d285fdf34f4b2/src/main/java/net/futureclient/asmlib/forgegradle/MappingType.java">Original Source</a>
*/
public enum MappingType {
SEARGE,
NOTCH,
CUSTOM // forgegradle
}
@@ -1,63 +0,0 @@
/*
* 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.gradle.util;
import java.lang.reflect.Field;
import java.util.Objects;
/**
* All credits go to AsmLibGradle and its contributors.
*
* @see <a href="https://github.com/pozzed/AsmLibGradle/blob/8f917dbc3939eab7a3d9daf54d9d285fdf34f4b2/src/main/java/net/futureclient/asmlib/forgegradle/ReobfWrapper.java">Original Source</a>
*/
public class ReobfWrapper {
private final Object instance;
private final Class<?> type;
public ReobfWrapper(Object instance) {
this.instance = instance;
Objects.requireNonNull(instance);
this.type = instance.getClass();
}
public String getName() {
try {
Field nameField = type.getDeclaredField("name");
nameField.setAccessible(true);
return (String) nameField.get(this.instance);
} catch (ReflectiveOperationException ex) {
throw new IllegalStateException(ex);
}
}
public MappingType getMappingType() {
try {
Field enumField = type.getDeclaredField("mappingType");
enumField.setAccessible(true);
Enum<?> aEnum = (Enum<?>) enumField.get(this.instance);
MappingType mappingType = MappingType.values()[aEnum.ordinal()];
if (!aEnum.name().equals(mappingType.name())) {
throw new IllegalStateException("ForgeGradle ReobfMappingType is not equivalent to MappingType (version error?)");
}
return mappingType;
} catch (ReflectiveOperationException ex) {
throw new IllegalStateException(ex);
}
}
}
+2 -3
View File
@@ -19,7 +19,7 @@
-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
-keep class baritone.utils.ExampleBaritoneControl { *; }
# setting names are reflected from field names, so keep field names
-keepclassmembers class baritone.api.Settings {
@@ -31,8 +31,7 @@
# copy all necessary libraries into tempLibraries to build
# The correct jar will be copied from the forgegradle cache based on the mapping type being compiled with
-libraryjars 'tempLibraries/minecraft.jar'
-libraryjars 'tempLibraries/minecraft-1.12.2.jar'
-libraryjars 'tempLibraries/SimpleTweaker-1.2.jar'
+37 -5
View File
@@ -17,6 +17,10 @@
package baritone.api;
import baritone.api.behavior.*;
import baritone.api.cache.IWorldProvider;
import baritone.api.cache.IWorldScanner;
import baritone.api.event.listener.IGameEventListener;
import baritone.api.utils.SettingsUtil;
import java.util.Iterator;
@@ -32,23 +36,51 @@ import java.util.ServiceLoader;
*/
public final class BaritoneAPI {
private static final IBaritoneProvider provider;
private static final IBaritoneProvider baritone;
private static final Settings settings;
static {
ServiceLoader<IBaritoneProvider> baritoneLoader = ServiceLoader.load(IBaritoneProvider.class);
Iterator<IBaritoneProvider> instances = baritoneLoader.iterator();
provider = instances.next();
baritone = instances.next();
settings = new Settings();
SettingsUtil.readAndApply(settings);
}
public static IBaritoneProvider getProvider() {
return BaritoneAPI.provider;
public static IFollowBehavior getFollowBehavior() {
return baritone.getFollowBehavior();
}
public static ILookBehavior getLookBehavior() {
return baritone.getLookBehavior();
}
public static IMemoryBehavior getMemoryBehavior() {
return baritone.getMemoryBehavior();
}
public static IMineBehavior getMineBehavior() {
return baritone.getMineBehavior();
}
public static IPathingBehavior getPathingBehavior() {
return baritone.getPathingBehavior();
}
public static Settings getSettings() {
return BaritoneAPI.settings;
return settings;
}
public static IWorldProvider getWorldProvider() {
return baritone.getWorldProvider();
}
public static IWorldScanner getWorldScanner() {
return baritone.getWorldScanner();
}
public static void registerEventListener(IGameEventListener listener) {
baritone.registerEventListener(listener);
}
}
-79
View File
@@ -1,79 +0,0 @@
/*
* 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;
import baritone.api.behavior.ILookBehavior;
import baritone.api.behavior.IPathingBehavior;
import baritone.api.cache.IWorldProvider;
import baritone.api.event.listener.IEventBus;
import baritone.api.pathing.calc.IPathingControlManager;
import baritone.api.process.ICustomGoalProcess;
import baritone.api.process.IFollowProcess;
import baritone.api.process.IGetToBlockProcess;
import baritone.api.process.IMineProcess;
import baritone.api.utils.IInputOverrideHandler;
import baritone.api.utils.IPlayerContext;
/**
* @author Brady
* @since 9/29/2018
*/
public interface IBaritone {
/**
* @return The {@link IFollowProcess} instance
* @see IFollowProcess
*/
IFollowProcess getFollowProcess();
/**
* @return The {@link ILookBehavior} instance
* @see ILookBehavior
*/
ILookBehavior getLookBehavior();
/**
* @return The {@link IMineProcess} instance
* @see IMineProcess
*/
IMineProcess getMineProcess();
/**
* @return The {@link IPathingBehavior} instance
* @see IPathingBehavior
*/
IPathingBehavior getPathingBehavior();
/**
* @return The {@link IWorldProvider} instance
* @see IWorldProvider
*/
IWorldProvider getWorldProvider();
IPathingControlManager getPathingControlManager();
IInputOverrideHandler getInputOverrideHandler();
ICustomGoalProcess getCustomGoalProcess();
IGetToBlockProcess getGetToBlockProcess();
IPlayerContext getPlayerContext();
IEventBus getGameEventHandler();
}
@@ -17,55 +17,70 @@
package baritone.api;
import baritone.api.behavior.*;
import baritone.api.cache.IWorldProvider;
import baritone.api.cache.IWorldScanner;
import net.minecraft.client.entity.EntityPlayerSP;
import java.util.List;
import baritone.api.event.listener.IGameEventListener;
/**
* @author Leijurv
* @author Brady
* @since 9/29/2018
*/
public interface IBaritoneProvider {
/**
* Returns the primary {@link IBaritone} instance. This instance is persistent, and
* is represented by the local player that is created by the game itself, not a "bot"
* player through Baritone.
* @see IFollowBehavior
*
* @return The primary {@link IBaritone} instance.
* @return The {@link IFollowBehavior} instance
*/
IBaritone getPrimaryBaritone();
IFollowBehavior getFollowBehavior();
/**
* Returns all of the active {@link IBaritone} instances. This includes the local one
* returned by {@link #getPrimaryBaritone()}.
* @see ILookBehavior
*
* @return All active {@link IBaritone} instances.
* @see #getBaritoneForPlayer(EntityPlayerSP)
* @return The {@link ILookBehavior} instance
*/
List<IBaritone> getAllBaritones();
ILookBehavior getLookBehavior();
/**
* 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.
* @see IMemoryBehavior
*
* @param player The player
* @return The {@link IBaritone} instance.
* @return The {@link IMemoryBehavior} instance
*/
default IBaritone getBaritoneForPlayer(EntityPlayerSP player) {
for (IBaritone baritone : getAllBaritones()) {
if (player.equals(baritone.getPlayerContext().player())) {
return baritone;
}
}
throw new IllegalStateException("No baritone for player " + player);
}
IMemoryBehavior getMemoryBehavior();
/**
* Returns the {@link IWorldScanner} instance. This is not a type returned by
* {@link IBaritone} implementation, because it is not linked with {@link IBaritone}.
* @see IMineBehavior
*
* @return The {@link IWorldScanner} instance.
* @return The {@link IMineBehavior} instance
*/
IMineBehavior getMineBehavior();
/**
* @see IPathingBehavior
*
* @return The {@link IPathingBehavior} instance
*/
IPathingBehavior getPathingBehavior();
/**
* @see IWorldProvider
*
* @return The {@link IWorldProvider} instance
*/
IWorldProvider getWorldProvider();
/**
* @see IWorldScanner
*
* @return The {@link IWorldScanner} instance
*/
IWorldScanner getWorldScanner();
/**
* Registers a {@link IGameEventListener} with Baritone's "event bus".
*
* @param listener The listener
*/
void registerEventListener(IGameEventListener listener);
}
+13 -119
View File
@@ -50,11 +50,6 @@ public class Settings {
*/
public Setting<Boolean> allowPlace = new Setting<>(true);
/**
* Allow Baritone to move items in your inventory to your hotbar
*/
public Setting<Boolean> allowInventory = 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
@@ -68,16 +63,6 @@ public class Settings {
*/
public Setting<Double> blockBreakAdditionalPenalty = new Setting<>(2D);
/**
* Additional penalty for hitting the space bar (ascend, pillar, or parkour) beacuse it uses hunger
*/
public Setting<Double> jumpPenalty = new Setting<>(2D);
/**
* Walking on water uses up hunger really quick, so penalize it
*/
public Setting<Double> walkOnWaterOnePenalty = new Setting<>(5D);
/**
* Allow Baritone to fall arbitrary distances and place a water bucket beneath it.
* Reliability: questionable.
@@ -104,22 +89,6 @@ public class Settings {
*/
public Setting<Boolean> assumeSafeWalk = new Setting<>(false);
/**
* If true, parkour is allowed to make jumps when standing on blocks at the maximum height, so player feet is y=256
* <p>
* Defaults to false because this fails on NCP
*/
public Setting<Boolean> allowJumpAt256 = new Setting<>(false);
/**
* Allow descending diagonally
* <p>
* Safer than allowParkour yet still slightly unsafe, can make contact with unchecked adjacent blocks, so it's unsafe in the nether.
* <p>
* For a generic "take some risks" mode I'd turn on this one, parkour, and parkour place.
*/
public Setting<Boolean> allowDiagonalDescend = new Setting<>(false);
/**
* Blocks that Baritone is allowed to place (as throwaway, for sneak bridging, pillaring, etc.)
*/
@@ -173,7 +142,7 @@ public class Settings {
* <p>
* Finding the optimal path is worth it, so it's the default.
*/
public Setting<Double> costHeuristic = new Setting<>(3.563);
public Setting<Double> costHeuristic = new Setting<>(3.5D);
// a bunch of obscure internal A* settings that you probably don't want to change
/**
@@ -189,42 +158,6 @@ public class Settings {
*/
public Setting<Double> backtrackCostFavoringCoefficient = new Setting<>(0.5);
/**
* Toggle the following 4 settings
* <p>
* They have a noticable performance impact, so they default off
*/
public Setting<Boolean> avoidance = new Setting<>(false);
/**
* Set to 1.0 to effectively disable this feature
* <p>
* Set below 1.0 to go out of your way to walk near mob spawners
*/
public Setting<Double> mobSpawnerAvoidanceCoefficient = new Setting<>(2.0);
public Setting<Integer> mobSpawnerAvoidanceRadius = new Setting<>(16);
/**
* Set to 1.0 to effectively disable this feature
* <p>
* Set below 1.0 to go out of your way to walk near mobs
*/
public Setting<Double> mobAvoidanceCoefficient = new Setting<>(1.5);
public Setting<Integer> mobAvoidanceRadius = new Setting<>(8);
/**
* When running a goto towards a container block (chest, ender chest, furnace, etc),
* right click and open it once you arrive.
*/
public Setting<Boolean> rightClickContainerOnArrival = new Setting<>(true);
/**
* When running a goto towards a nether portal block, walk all the way into the portal
* instead of stopping one block before.
*/
public Setting<Boolean> enterPortal = new Setting<>(true);
/**
* Don't repropagate cost improvements below 0.01 ticks. They're all just floating point inaccuracies,
* and there's no point.
@@ -314,28 +247,14 @@ public class Settings {
public Setting<Integer> movementTimeoutTicks = new Setting<>(100);
/**
* Pathing ends after this amount of time, but only if a path has been found
* <p>
* If no valid path (length above the minimum) has been found, pathing continues up until the failure timeout
* Pathing can never take longer than this
*/
public Setting<Long> primaryTimeoutMS = new Setting<>(500L);
public Setting<Long> pathTimeoutMS = new Setting<>(2000L);
/**
* Pathing can never take longer than this, even if that means failing to find any path at all
* Planning ahead while executing a segment can never take longer than this
*/
public Setting<Long> failureTimeoutMS = new Setting<>(2000L);
/**
* Planning ahead while executing a segment ends after this amount of time, but only if a path has been found
* <p>
* If no valid path (length above the minimum) has been found, pathing continues up until the failure timeout
*/
public Setting<Long> planAheadPrimaryTimeoutMS = new Setting<>(4000L);
/**
* Planning ahead while executing a segment can never take longer than this, even if that means failing to find any path at all
*/
public Setting<Long> planAheadFailureTimeoutMS = new Setting<>(5000L);
public Setting<Long> planAheadTimeoutMS = new Setting<>(4000L);
/**
* For debugging, consider nodes much much slower
@@ -357,13 +276,6 @@ public class Settings {
*/
public Setting<Boolean> chunkCaching = new Setting<>(true);
/**
* On save, delete from RAM any cached regions that are more than 1024 blocks away from the player
* <p>
* Temporarily disabled, see issue #248
*/
public Setting<Boolean> pruneRegionsFromRAM = new Setting<>(false);
/**
* Print all the debug messages to chat
*/
@@ -393,23 +305,17 @@ public class Settings {
/**
* Ignore depth when rendering the goal
*/
public Setting<Boolean> renderGoalIgnoreDepth = new Setting<>(true);
/**
* Renders X/Z type Goals with the vanilla beacon beam effect. Combining this with
* {@link #renderGoalIgnoreDepth} will cause strange render clipping.
*/
public Setting<Boolean> renderGoalXZBeacon = new Setting<>(false);
public Setting<Boolean> renderGoalIgnoreDepth = new Setting<>(false);
/**
* Ignore depth when rendering the selection boxes (to break, to place, to walk into)
*/
public Setting<Boolean> renderSelectionBoxesIgnoreDepth = new Setting<>(true);
public Setting<Boolean> renderSelectionBoxesIgnoreDepth = new Setting<>(false);
/**
* Ignore depth when rendering the path
*/
public Setting<Boolean> renderPathIgnoreDepth = new Setting<>(true);
public Setting<Boolean> renderPathIgnoreDepth = new Setting<>(false);
/**
* Line width of the path when rendered, in pixels
@@ -452,6 +358,10 @@ public class Settings {
/**
* {@code true}: can mine blocks when in inventory, chat, or tabbed away in ESC menu
* <p>
* {@code false}: works on cosmic prisons
* <p>
* LOL
*/
public Setting<Boolean> leftClickWorkaround = new Setting<>(true);
@@ -460,16 +370,6 @@ public class Settings {
*/
public Setting<Boolean> walkWhileBreaking = new Setting<>(true);
/**
* If we are more than 500 movements into the current path, discard the oldest segments, as they are no longer useful
*/
public Setting<Integer> maxPathHistoryLength = new Setting<>(300);
/**
* If the current path is too long, cut off this many movements from the beginning.
*/
public Setting<Integer> pathHistoryCutoffAmount = new Setting<>(50);
/**
* Rescan for the goal once every 5 ticks.
* Set to 0 to disable.
@@ -494,7 +394,7 @@ public class Settings {
* <p>
* Also on cosmic prisons this should be set to true since you don't actually mine the ore it just gets replaced with stone.
*/
public Setting<Boolean> cancelOnGoalInvalidation = new Setting<>(true);
public Setting<Boolean> cancelOnGoalInvalidation = new Setting<>(false);
/**
* The "axis" command (aka GoalAxis) will go to a axis, or diagonal axis, at this Y level.
@@ -622,12 +522,6 @@ public class Settings {
*/
public final List<Setting<?>> allSettings;
public void reset() {
for (Setting setting : allSettings) {
setting.value = setting.defaultValue;
}
}
public class Setting<T> {
public T value;
public final T defaultValue;
@@ -18,9 +18,10 @@
package baritone.api.behavior;
import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.utils.interfaces.Toggleable;
/**
* @author Brady
* @since 9/23/2018
*/
public interface IBehavior extends AbstractGameEventListener {}
public interface IBehavior extends AbstractGameEventListener, Toggleable {}
@@ -15,37 +15,30 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.process;
package baritone.api.behavior;
import net.minecraft.entity.Entity;
import java.util.List;
import java.util.function.Predicate;
/**
* @author Brady
* @since 9/23/2018
*/
public interface IFollowProcess extends IBaritoneProcess {
public interface IFollowBehavior extends IBehavior {
/**
* Set the follow target to any entities matching this predicate
* Set the follow target to the specified entity;
*
* @param filter the predicate
* @param entity The entity to follow
*/
void follow(Predicate<Entity> filter);
void follow(Entity entity);
/**
* @return The entities that are currently being followed. null if not currently following, empty if nothing matches the predicate
* @return The entity that is currently being followed
*/
List<Entity> following();
Predicate<Entity> currentFilter();
Entity following();
/**
* Cancels the follow behavior, this will clear the current follow target.
*/
default void cancel() {
onLostControl();
}
void cancel();
}
@@ -33,7 +33,7 @@ public interface ILookBehavior extends IBehavior {
* otherwise, it should be {@code false};
*
* @param rotation The target rotations
* @param force Whether or not to "force" the rotations
* @param force Whether or not to "force" the rotations
*/
void updateTarget(Rotation rotation, boolean force);
}
@@ -15,8 +15,9 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.cache;
package baritone.api.behavior;
import baritone.api.behavior.memory.IRememberedInventory;
import net.minecraft.util.math.BlockPos;
import java.util.Map;
@@ -25,7 +26,7 @@ import java.util.Map;
* @author Brady
* @since 9/23/2018
*/
public interface IContainerMemory {
public interface IMemoryBehavior extends IBehavior {
/**
* Gets a remembered inventory by its block position.
@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.process;
package baritone.api.behavior;
import net.minecraft.block.Block;
@@ -23,7 +23,7 @@ import net.minecraft.block.Block;
* @author Brady
* @since 9/23/2018
*/
public interface IMineProcess extends IBaritoneProcess {
public interface IMineBehavior extends IBehavior {
/**
* Begin to search for and mine the specified blocks until
@@ -31,9 +31,9 @@ public interface IMineProcess extends IBaritoneProcess {
* are mined. This is based on the first target block to mine.
*
* @param quantity The number of items to get from blocks mined
* @param blocks The blocks to mine
* @param blocks The blocks to mine
*/
void mineByName(int quantity, String... blocks);
void mine(int quantity, String... blocks);
/**
* Begin to search for and mine the specified blocks until
@@ -41,7 +41,7 @@ public interface IMineProcess extends IBaritoneProcess {
* are mined. This is based on the first target block to mine.
*
* @param quantity The number of items to get from blocks mined
* @param blocks The blocks to mine
* @param blocks The blocks to mine
*/
void mine(int quantity, Block... blocks);
@@ -50,8 +50,8 @@ public interface IMineProcess extends IBaritoneProcess {
*
* @param blocks The blocks to mine
*/
default void mineByName(String... blocks) {
mineByName(0, blocks);
default void mine(String... blocks) {
this.mine(0, blocks);
}
/**
@@ -60,13 +60,11 @@ public interface IMineProcess extends IBaritoneProcess {
* @param blocks The blocks to mine
*/
default void mine(Block... blocks) {
mine(0, blocks);
this.mine(0, blocks);
}
/**
* Cancels the current mining task
*/
default void cancel() {
onLostControl();
}
void cancel();
}
@@ -39,25 +39,35 @@ public interface IPathingBehavior extends IBehavior {
*/
Optional<Double> ticksRemainingInSegment();
/**
* Sets the pathing goal.
*
* @param goal The pathing goal
*/
void setGoal(Goal goal);
/**
* @return The current pathing goal
*/
Goal getGoal();
/**
* Begins pathing. Calculation will start in a new thread, and once completed,
* movement will commence. Returns whether or not the operation was successful.
*
* @return Whether or not the operation was successful
*/
boolean path();
/**
* @return Whether or not a path is currently being executed.
*/
boolean isPathing();
/**
* Cancels the pathing behavior or the current path calculation, and all processes that could be controlling path.
* <p>
* Basically, "MAKE IT STOP".
*
* @return Whether or not the pathing behavior was canceled. All processes are guaranteed to be canceled, but the
* PathingBehavior might be in the middle of an uncancelable action like a parkour jump
* Cancels the pathing behavior or the current path calculation.
*/
boolean cancelEverything();
void cancel();
/**
* Returns the current path, from the current path executor, if there is one.
@@ -71,7 +81,7 @@ public interface IPathingBehavior extends IBehavior {
/**
* @return The current path finder being executed
*/
Optional<? extends IPathFinder> getInProgress();
Optional<IPathFinder> getPathFinder();
/**
* @return The current path executor
@@ -15,7 +15,7 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.cache;
package baritone.api.behavior.memory;
import net.minecraft.item.ItemStack;
+1 -1
View File
@@ -22,7 +22,7 @@ import net.minecraft.util.math.BlockPos;
/**
* @author Brady
* @since 8/4/2018
* @since 8/4/2018 2:01 AM
*/
public interface IBlockTypeAccess {
+4 -3
View File
@@ -29,20 +29,21 @@ public interface ICachedRegion extends IBlockTypeAccess {
* however, the block coordinates should in on a scale from 0 to 511 (inclusive)
* because region sizes are 512x512 blocks.
*
* @see ICachedWorld#isCached(int, int)
*
* @param blockX The block X coordinate
* @param blockZ The block Z coordinate
* @return Whether or not the specified XZ location is cached
* @see ICachedWorld#isCached(int, int)
*/
boolean isCached(int blockX, int blockZ);
/**
* @return The X coordinate of this region
* The X coordinate of this region
*/
int getX();
/**
* @return The Z coordinate of this region
* The Z coordinate of this region
*/
int getZ();
}
+3 -5
View File
@@ -61,14 +61,12 @@ public interface ICachedWorld {
* information that is returned by this method may not be up to date, because
* older cached chunks can contain data that is much more likely to have changed.
*
* @param block The special block to search for
* @param maximum The maximum number of position results to receive
* @param centerX The x block coordinate center of the search
* @param centerZ The z block coordinate center of the search
* @param block The special block to search for
* @param maximum The maximum number of position results to receive
* @param maxRegionDistanceSq The maximum region distance, squared
* @return The locations found that match the special block
*/
LinkedList<BlockPos> getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq);
LinkedList<BlockPos> getLocationsOf(String block, int maximum, int maxRegionDistanceSq);
/**
* Reloads all of the cached regions in this world from disk. Anything that is not saved
+4 -2
View File
@@ -50,17 +50,19 @@ public interface IWaypointCollection {
/**
* Gets all of the waypoints that have the specified tag
*
* @see IWaypointCollection#getAllWaypoints()
*
* @param tag The tag
* @return All of the waypoints with the specified tag
* @see IWaypointCollection#getAllWaypoints()
*/
Set<IWaypoint> getByTag(IWaypoint.Tag tag);
/**
* Gets all of the waypoints in this collection, regardless of the tag.
*
* @return All of the waypoints in this collection
* @see IWaypointCollection#getByTag(IWaypoint.Tag)
*
* @return All of the waypoints in this collection
*/
Set<IWaypoint> getAllWaypoints();
}
+2 -8
View File
@@ -27,19 +27,13 @@ public interface IWorldData {
* Returns the cached world for this world. A cached world is a simplified format
* of a regular world, intended for use on multiplayer servers where chunks are not
* traditionally stored to disk, allowing for long distance pathing with minimal disk usage.
*
* @return The cached world for this world
*/
ICachedWorld getCachedWorld();
/**
* Returns the waypoint collection for this world.
*
* @return The waypoint collection for this world
*/
IWaypointCollection getWaypoints();
/**
* @return The {@link IContainerMemory} instance
* @see IContainerMemory
*/
IContainerMemory getContainerMemory();
}
+1 -19
View File
@@ -17,10 +17,8 @@
package baritone.api.cache;
import baritone.api.utils.IPlayerContext;
import net.minecraft.block.Block;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import java.util.List;
@@ -33,8 +31,6 @@ public interface IWorldScanner {
/**
* Scans the world, up to the specified max chunk radius, for the specified blocks.
*
* @param ctx The {@link IPlayerContext} containing player and world info that the
* scan is based upon
* @param blocks The blocks to scan for
* @param max The maximum number of blocks to scan before cutoff
* @param yLevelThreshold If a block is found within this Y level, the current result will be
@@ -42,19 +38,5 @@ public interface IWorldScanner {
* @param maxSearchRadius The maximum chunk search radius
* @return The matching block positions
*/
List<BlockPos> scanChunkRadius(IPlayerContext ctx, List<Block> blocks, int max, int yLevelThreshold, int maxSearchRadius);
/**
* Scans a single chunk for the specified blocks.
*
* @param ctx The {@link IPlayerContext} containing player and world info that the
* scan is based upon
* @param blocks The blocks to scan for
* @param pos The position of the target chunk
* @param max The maximum number of blocks to scan before cutoff
* @param yLevelThreshold If a block is found within this Y level, the current result will be
* returned, if the value is negative, then this condition doesn't apply.
* @return The matching block positions
*/
List<BlockPos> scanChunk(IPlayerContext ctx, List<Block> blocks, ChunkPos pos, int max, int yLevelThreshold);
List<BlockPos> scanChunkRadius(List<Block> blocks, int max, int yLevelThreshold, int maxSearchRadius);
}
@@ -20,7 +20,7 @@ package baritone.api.event.events;
import net.minecraft.util.math.BlockPos;
/**
* Called when the local player interacts with a block, can be either {@link Type#START_BREAK} or {@link Type#USE}.
* Called when the local player interacts with a block, can be either {@link Type#BREAK} or {@link Type#USE}.
*
* @author Brady
* @since 8/22/2018
@@ -59,9 +59,9 @@ public final class BlockInteractEvent {
public enum Type {
/**
* We're starting to break the target block.
* We're breaking the target block.
*/
START_BREAK,
BREAK,
/**
* We're right clicking on the target block. Either placing or interacting with.
@@ -22,7 +22,7 @@ import net.minecraft.client.entity.EntityPlayerSP;
/**
* @author Brady
* @since 8/1/2018
* @since 8/1/2018 6:39 PM
*/
public final class ChatEvent extends ManagedPlayerEvent.Cancellable {
@@ -21,7 +21,7 @@ import baritone.api.event.events.type.EventState;
/**
* @author Brady
* @since 8/2/2018
* @since 8/2/2018 12:32 AM
*/
public final class ChunkEvent {
@@ -31,9 +31,7 @@ public final class ChunkEvent {
private final EventState state;
/**
* The type of chunk event that occurred
*
* @see Type
* The type of chunk event that occurred;
*/
private final Type type;
@@ -96,16 +94,7 @@ public final class ChunkEvent {
/**
* When the chunk is being populated with blocks, tile entities, etc.
* <p>
* And it's a full chunk
*/
POPULATE_FULL,
/**
* When the chunk is being populated with blocks, tile entities, etc.
* <p>
* And it's a partial chunk
*/
POPULATE_PARTIAL
POPULATE
}
}
@@ -23,7 +23,7 @@ import net.minecraft.network.Packet;
/**
* @author Brady
* @since 8/6/2018
* @since 8/6/2018 9:31 PM
*/
public final class PacketEvent {
@@ -19,7 +19,7 @@ package baritone.api.event.events;
/**
* @author Brady
* @since 8/5/2018
* @since 8/5/2018 12:28 AM
*/
public final class RenderEvent {
@@ -17,6 +17,7 @@
package baritone.api.event.events;
import baritone.api.event.events.type.EventState;
import baritone.api.event.events.type.ManagedPlayerEvent;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
@@ -34,30 +35,21 @@ public final class RotationMoveEvent extends ManagedPlayerEvent {
private final Type type;
/**
* The yaw rotation
* The state of the event
*/
private float yaw;
private final EventState state;
public RotationMoveEvent(EntityPlayerSP player, Type type, float yaw) {
public RotationMoveEvent(EntityPlayerSP player, EventState state, Type type) {
super(player);
this.state = state;
this.type = type;
this.yaw = yaw;
}
/**
* Set the yaw movement rotation
*
* @param yaw Yaw rotation
* @return The state of the event
*/
public final void setYaw(float yaw) {
this.yaw = yaw;
}
/**
* @return The yaw rotation
*/
public final float getYaw() {
return this.yaw;
public final EventState getState() {
return this.state;
}
/**
@@ -22,7 +22,7 @@ import net.minecraft.client.multiplayer.WorldClient;
/**
* @author Brady
* @since 8/4/2018
* @since 8/4/2018 3:13 AM
*/
public final class WorldEvent {
@@ -19,7 +19,7 @@ package baritone.api.event.events.type;
/**
* @author Brady
* @since 8/1/2018
* @since 8/1/2018 6:41 PM
*/
public class Cancellable implements ICancellable {
@@ -19,17 +19,19 @@ package baritone.api.event.events.type;
/**
* @author Brady
* @since 8/2/2018
* @since 8/2/2018 12:34 AM
*/
public enum EventState {
/**
* Before the dispatching of what the event is targetting
* Indicates that whatever movement the event is being
* dispatched as a result of is about to occur.
*/
PRE,
/**
* After the dispatching of what the event is targetting
* Indicates that whatever movement the event is being
* dispatched as a result of has already occurred.
*/
POST
}
@@ -26,7 +26,7 @@ import baritone.api.event.events.*;
*
* @author Brady
* @see IGameEventListener
* @since 8/1/2018
* @since 8/1/2018 6:29 PM
*/
public interface AbstractGameEventListener extends IGameEventListener {
@@ -36,6 +36,9 @@ public interface AbstractGameEventListener extends IGameEventListener {
@Override
default void onPlayerUpdate(PlayerUpdateEvent event) {}
@Override
default void onProcessKeyBinds() {}
@Override
default void onSendChatMessage(ChatEvent event) {}
@@ -1,36 +0,0 @@
/*
* 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.event.listener;
/**
* A type of {@link IGameEventListener} that can have additional listeners
* registered so that they receive the events that are dispatched to this
* listener.
*
* @author Brady
* @since 11/14/2018
*/
public interface IEventBus extends IGameEventListener {
/**
* Registers the specified {@link IGameEventListener} to this event bus
*
* @param listener The listener
*/
void registerEventListener(IGameEventListener listener);
}
@@ -23,20 +23,23 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.GuiGameOver;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.util.text.ITextComponent;
/**
* @author Brady
* @since 7/31/2018
* @since 7/31/2018 11:05 PM
*/
public interface IGameEventListener {
/**
* Run once per game tick before screen input is handled.
*
* @param event The event
* @see Minecraft#runTick()
*/
void onTick(TickEvent event);
@@ -44,15 +47,20 @@ public interface IGameEventListener {
/**
* Run once per game tick from before and after the player rotation is sent to the server.
*
* @param event The event
* @see EntityPlayerSP#onUpdate()
*/
void onPlayerUpdate(PlayerUpdateEvent event);
/**
* Run once per game tick from before keybinds are processed.
*
* @see Minecraft#processKeyBinds()
*/
void onProcessKeyBinds();
/**
* Runs whenever the client player sends a message to the server.
*
* @param event The event
* @see EntityPlayerSP#sendChatMessage(String)
*/
void onSendChatMessage(ChatEvent event);
@@ -60,7 +68,6 @@ public interface IGameEventListener {
/**
* Runs before and after whenever a chunk is either loaded, unloaded, or populated.
*
* @param event The event
* @see WorldClient#doPreChunk(int, int, boolean)
*/
void onChunkEvent(ChunkEvent event);
@@ -70,14 +77,13 @@ public interface IGameEventListener {
* <p>
* <b>Note:</b> {@link GameSettings#anaglyph} has been removed in Minecraft 1.13
*
* @param event The event
* @see EntityRenderer#renderWorldPass(int, float, long)
*/
void onRenderPass(RenderEvent event);
/**
* Runs before and after whenever a new world is loaded
*
* @param event The event
* @see Minecraft#loadWorld(WorldClient, String)
*/
void onWorldEvent(WorldEvent event);
@@ -85,7 +91,7 @@ public interface IGameEventListener {
/**
* Runs before a outbound packet is sent
*
* @param event The event
* @see NetworkManager#dispatchPacket(Packet, GenericFutureListener[])
* @see Packet
* @see GenericFutureListener
*/
@@ -94,7 +100,7 @@ public interface IGameEventListener {
/**
* Runs before an inbound packet is processed
*
* @param event The event
* @see NetworkManager#dispatchPacket(Packet, GenericFutureListener[])
* @see Packet
* @see GenericFutureListener
*/
@@ -104,29 +110,31 @@ public interface IGameEventListener {
* Run once per game tick from before and after the player's moveRelative method is called
* and before and after the player jumps.
*
* @param event The event
* @see Entity#moveRelative(float, float, float, float)
* @see EntityLivingBase#jump()
*/
void onPlayerRotationMove(RotationMoveEvent event);
/**
* Called when the local player interacts with a block, whether it is breaking or opening/placing.
*
* @param event The event
* @see Minecraft#clickMouse()
* @see Minecraft#rightClickMouse()
*/
void onBlockInteract(BlockInteractEvent event);
/**
* Called when the local player dies, as indicated by the creation of the {@link GuiGameOver} screen.
*
* @see GuiGameOver
* @see GuiGameOver(ITextComponent)
* @see ITextComponent
*/
void onPlayerDeath();
/**
* When the pathfinder's state changes
*
* @param event The event
* @param event
*/
void onPathEvent(PathEvent event);
}
@@ -22,7 +22,6 @@ import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.movement.IMovement;
import baritone.api.utils.BetterBlockPos;
import java.util.HashSet;
import java.util.List;
/**
@@ -51,12 +50,8 @@ public interface IPath {
/**
* This path is actually going to be executed in the world. Do whatever additional processing is required.
* (as opposed to Path objects that are just constructed every frame for rendering)
*
* @return The result of path post processing
*/
default IPath postProcess() {
throw new UnsupportedOperationException();
}
default void postProcess() {}
/**
* Returns the number of positions in this path. Equivalent to {@code positions().size()}.
@@ -120,60 +115,23 @@ public interface IPath {
/**
* Cuts off this path at the loaded chunk border, and returns the resulting path. Default
* implementation just returns this path, without the intended functionality.
* <p>
* The argument is supposed to be a BlockStateInterface LOL LOL LOL LOL LOL
*
* @param bsi The block state lookup, highly cursed
* @return The result of this cut-off operation
*/
default IPath cutoffAtLoadedChunks(Object bsi) {
throw new UnsupportedOperationException();
default IPath cutoffAtLoadedChunks() {
return this;
}
/**
* Cuts off this path using the min length and cutoff factor settings, and returns the resulting path.
* Default implementation just returns this path, without the intended functionality.
*
* @param destination The end goal of this path
* @return The result of this cut-off operation
* @see Settings#pathCutoffMinimumLength
* @see Settings#pathCutoffFactor
*
* @return The result of this cut-off operation
*/
default IPath staticCutoff(Goal destination) {
throw new UnsupportedOperationException();
}
/**
* Performs a series of checks to ensure that the assembly of the path went as expected.
*/
default void sanityCheck() {
List<BetterBlockPos> path = positions();
List<IMovement> movements = movements();
if (!getSrc().equals(path.get(0))) {
throw new IllegalStateException("Start node does not equal first path element");
}
if (!getDest().equals(path.get(path.size() - 1))) {
throw new IllegalStateException("End node does not equal last path element");
}
if (path.size() != movements.size() + 1) {
throw new IllegalStateException("Size of path array is unexpected");
}
HashSet<BetterBlockPos> seenSoFar = new HashSet<>();
for (int i = 0; i < path.size() - 1; i++) {
BetterBlockPos src = path.get(i);
BetterBlockPos dest = path.get(i + 1);
IMovement movement = movements.get(i);
if (!src.equals(movement.getSrc())) {
throw new IllegalStateException("Path source is not equal to the movement source");
}
if (!dest.equals(movement.getDest())) {
throw new IllegalStateException("Path destination is not equal to the movement destination");
}
if (seenSoFar.contains(src)) {
throw new IllegalStateException("Path doubles back on itself, making a loop");
}
seenSoFar.add(src);
}
return this;
}
}
@@ -18,7 +18,6 @@
package baritone.api.pathing.calc;
import baritone.api.pathing.goals.Goal;
import baritone.api.utils.PathCalculationResult;
import java.util.Optional;
@@ -34,11 +33,9 @@ public interface IPathFinder {
/**
* Calculate the path in full. Will take several seconds.
*
* @param primaryTimeout If a path is found, the path finder will stop after this amount of time
* @param failureTimeout If a path isn't found, the path finder will continue for this amount of time
* @return The final path
*/
PathCalculationResult calculate(long primaryTimeout, long failureTimeout);
Optional<IPath> calculate(long timeout);
/**
* Intended to be called concurrently with calculatePath from a different thread to tell if it's finished yet
@@ -1,31 +0,0 @@
/*
* 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.pathing.calc;
import baritone.api.process.IBaritoneProcess;
import baritone.api.process.PathingCommand;
import java.util.Optional;
public interface IPathingControlManager {
void registerProcess(IBaritoneProcess process);
Optional<IBaritoneProcess> mostRecentInControl();
Optional<PathingCommand> mostRecentCommand();
}
@@ -30,9 +30,6 @@ public interface Goal {
* Returns whether or not the specified position
* meets the requirement for this goal based.
*
* @param x The goal X position
* @param y The goal Y position
* @param z The goal Z position
* @return Whether or not it satisfies this goal
*/
boolean isInGoal(int x, int y, int z);
@@ -40,9 +37,6 @@ public interface Goal {
/**
* Estimate the number of ticks it will take to get to the goal
*
* @param x The goal X position
* @param y The goal Y position
* @param z The goal Z position
* @return The estimate number of ticks to satisfy the goal
*/
double heuristic(int x, int y, int z);
@@ -17,7 +17,10 @@
package baritone.api.pathing.goals;
import net.minecraft.util.math.BlockPos;
import java.util.Arrays;
import java.util.Collection;
/**
* A composite of many goals, any one of which satisfies the composite.
@@ -37,6 +40,14 @@ public class GoalComposite implements Goal {
this.goals = goals;
}
public GoalComposite(BlockPos... blocks) {
this(Arrays.asList(blocks));
}
public GoalComposite(Collection<BlockPos> blocks) {
this(blocks.stream().map(GoalBlock::new).toArray(Goal[]::new));
}
@Override
public boolean isInGoal(int x, int y, int z) {
for (Goal goal : goals) {
@@ -48,7 +48,10 @@ public class GoalGetToBlock implements Goal, IGoalRenderPos {
int xDiff = x - this.x;
int yDiff = y - this.y;
int zDiff = z - this.z;
return Math.abs(xDiff) + Math.abs(yDiff < 0 ? yDiff + 1 : yDiff) + Math.abs(zDiff) <= 1;
if (yDiff < 0) {
yDiff++;
}
return Math.abs(xDiff) + Math.abs(yDiff) + Math.abs(zDiff) <= 1;
}
@Override
@@ -56,7 +59,7 @@ public class GoalGetToBlock implements Goal, IGoalRenderPos {
int xDiff = x - this.x;
int yDiff = y - this.y;
int zDiff = z - this.z;
return GoalBlock.calculate(xDiff, yDiff < 0 ? yDiff + 1 : yDiff, zDiff);
return GoalBlock.calculate(xDiff, yDiff, zDiff);
}
@Override
@@ -32,26 +32,16 @@ public class GoalRunAway implements Goal {
private final double distanceSq;
private final Integer maintainY;
public GoalRunAway(double distance, BlockPos... from) {
this(distance, null, from);
}
public GoalRunAway(double distance, Integer maintainY, BlockPos... from) {
if (from.length == 0) {
throw new IllegalArgumentException();
}
this.from = from;
this.distanceSq = distance * distance;
this.maintainY = maintainY;
}
@Override
public boolean isInGoal(int x, int y, int z) {
if (maintainY != null && maintainY != y) {
return false;
}
for (BlockPos p : from) {
int diffX = x - p.getX();
int diffZ = z - p.getZ();
@@ -72,19 +62,11 @@ public class GoalRunAway implements Goal {
min = h;
}
}
min = -min;
if (maintainY != null) {
min = min * 0.6 + GoalYLevel.calculate(maintainY, y) * 1.5;
}
return min;
return -min;
}
@Override
public String toString() {
if (maintainY != null) {
return "GoalRunAwayFromMaintainY y=" + maintainY + ", " + Arrays.asList(from);
} else {
return "GoalRunAwayFrom" + Arrays.asList(from);
}
return "GoalRunAwayFrom" + Arrays.asList(from);
}
}
@@ -63,7 +63,10 @@ public class GoalTwoBlocks implements Goal, IGoalRenderPos {
int xDiff = x - this.x;
int yDiff = y - this.y;
int zDiff = z - this.z;
return GoalBlock.calculate(xDiff, yDiff < 0 ? yDiff + 1 : yDiff, zDiff);
if (yDiff < 0) {
yDiff++;
}
return GoalBlock.calculate(xDiff, yDiff, zDiff);
}
@Override
@@ -20,6 +20,8 @@ package baritone.api.pathing.movement;
import baritone.api.utils.BetterBlockPos;
import net.minecraft.util.math.BlockPos;
import java.util.List;
/**
* @author Brady
* @since 10/8/2018
@@ -56,4 +58,10 @@ public interface IMovement {
BetterBlockPos getDest();
BlockPos getDirection();
List<BlockPos> toBreak();
List<BlockPos> toPlace();
List<BlockPos> toWalkInto();
}
@@ -1,99 +0,0 @@
/*
* 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.process;
import baritone.api.IBaritone;
import baritone.api.behavior.IPathingBehavior;
import baritone.api.event.events.PathEvent;
/**
* A process that can control the PathingBehavior.
* <p>
* Differences between a baritone process and a behavior:
* Only one baritone process can be active at a time
* PathingBehavior can only be controlled by a process
* <p>
* That's it actually
*
* @author leijurv
*/
public interface IBaritoneProcess {
/**
* Would this process like to be in control?
*
* @return Whether or not this process would like to be in contorl.
*/
boolean isActive();
/**
* Called when this process is in control of pathing; Returns what Baritone should do.
*
* @param calcFailed {@code true} if this specific process was in control last tick,
* and there was a {@link PathEvent#CALC_FAILED} event last tick
* @param isSafeToCancel {@code true} if a {@link PathingCommandType#REQUEST_PAUSE} would happen this tick, and
* {@link IPathingBehavior} wouldn't actually tick. {@code false} if the PathExecutor reported
* pausing would be unsafe at the end of the last tick. Effectively "could request cancel or
* pause and have it happen right away"
* @return What the {@link IPathingBehavior} should do
*/
PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel);
/**
* Returns whether or not this process should be treated as "temporary".
* <p>
* If a process is temporary, it doesn't call {@link #onLostControl} on the processes that aren't execute because of it.
* <p>
* For example, {@code CombatPauserProcess} and {@code PauseForAutoEatProcess} should return {@code true} always,
* and should return {@link #isActive} {@code true} only if there's something in range this tick, or if the player would like
* 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
*/
boolean isTemporary();
/**
* Called if {@link #isActive} returned {@code true}, but another non-temporary
* process has control. Effectively the same as cancel. You want control but you
* don't get it.
*/
void onLostControl();
/**
* Used to determine which Process gains control if multiple are reporting {@link #isActive()}. The one
* that returns the highest value will be given control.
*
* @return A double representing the priority
*/
double priority();
/**
* Returns which bot this process is associated with. (5000000iq forward thinking)
*
* @return The Bot associated with this process
*/
IBaritone associatedWith();
/**
* Returns a user-friendly name for this process. Suitable for a HUD.
*
* @return A display name that's suitable for a HUD
*/
String displayName();
}
@@ -1,28 +0,0 @@
/*
* 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.process;
import net.minecraft.block.Block;
/**
* but it rescans the world every once in a while so it doesn't get fooled by its cache
*/
public interface IGetToBlockProcess extends IBaritoneProcess {
void getToBlock(Block block);
}
@@ -1,56 +0,0 @@
/*
* 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.process;
import baritone.api.pathing.goals.Goal;
import java.util.Objects;
/**
* @author leijurv
*/
public class PathingCommand {
/**
* The target goal, may be {@code null}.
*/
public final Goal goal;
/**
* The command type.
*
* @see PathingCommandType
*/
public final PathingCommandType commandType;
/**
* Create a new {@link PathingCommand}.
*
* @param goal The target goal, may be {@code null}.
* @param commandType The command type, cannot be {@code null}.
* @throws NullPointerException if {@code commandType} is {@code null}.
* @see Goal
* @see PathingCommandType
*/
public PathingCommand(Goal goal, PathingCommandType commandType) {
Objects.requireNonNull(commandType);
this.goal = goal;
this.commandType = commandType;
}
}
@@ -1,55 +0,0 @@
/*
* 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.process;
import baritone.api.Settings;
public enum PathingCommandType {
/**
* Set the goal and path.
* <p>
* If you use this alongside a {@code null} goal, it will continue along its current path and current goal.
*/
SET_GOAL_AND_PATH,
/**
* Has no effect on the current goal or path, just requests a pause
*/
REQUEST_PAUSE,
/**
* Set the goal (regardless of {@code null}), and request a cancel of the current path (when safe)
*/
CANCEL_AND_SET_GOAL,
/**
* Set the goal and path.
* <p>
* If {@link Settings#cancelOnGoalInvalidation} is {@code true}, revalidate the
* current goal, and cancel if it's no longer valid, or if the new goal is {@code null}.
*/
REVALIDATE_GOAL_AND_PATH,
/**
* Set the goal and path.
* <p>
* Cancel the current path if the goals are not equal
*/
FORCE_REVALIDATE_GOAL_AND_PATH
}
@@ -35,15 +35,6 @@ public final class BetterBlockPos extends BlockPos {
public final int x;
public final int y;
public final int z;
public static long numCreated;
static {
numCreated = 0;
}
{
numCreated++;
}
public BetterBlockPos(int x, int y, int z) {
super(x, y, z);
@@ -1,37 +0,0 @@
/*
* 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;
import baritone.api.behavior.IBehavior;
import baritone.api.utils.input.Input;
import net.minecraft.client.settings.KeyBinding;
/**
* @author Brady
* @since 11/12/2018
*/
public interface IInputOverrideHandler extends IBehavior {
Boolean isInputForcedDown(KeyBinding key);
boolean isInputForcedDown(Input input);
void setInputForceState(Input input, boolean forced);
void clearAllKeys();
}
@@ -1,91 +0,0 @@
/*
* 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;
import baritone.api.cache.IWorldData;
import net.minecraft.block.BlockSlab;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import java.util.Optional;
/**
* @author Brady
* @since 11/12/2018
*/
public interface IPlayerContext {
EntityPlayerSP player();
IPlayerController playerController();
World world();
IWorldData worldData();
RayTraceResult objectMouseOver();
default BetterBlockPos playerFeet() {
// TODO find a better way to deal with soul sand!!!!!
BetterBlockPos feet = new BetterBlockPos(player().posX, player().posY + 0.1251, player().posZ);
if (world().getBlockState(feet).getBlock() instanceof BlockSlab) {
return feet.up();
}
return feet;
}
default Vec3d playerFeetAsVec() {
return new Vec3d(player().posX, player().posY, player().posZ);
}
default Vec3d playerHead() {
return new Vec3d(player().posX, player().posY + player().getEyeHeight(), player().posZ);
}
default Rotation playerRotations() {
return new Rotation(player().rotationYaw, player().rotationPitch);
}
/**
* Returns the block that the crosshair is currently placed over. Updated once per tick.
*
* @return The position of the highlighted block
*/
default Optional<BlockPos> getSelectedBlock() {
if (objectMouseOver() != null && objectMouseOver().typeOfHit == RayTraceResult.Type.BLOCK) {
return Optional.of(objectMouseOver().getBlockPos());
}
return Optional.empty();
}
/**
* Returns the entity that the crosshair is currently placed over. Updated once per tick.
*
* @return The entity
*/
default Optional<Entity> getSelectedEntity() {
if (objectMouseOver() != null && objectMouseOver().typeOfHit == RayTraceResult.Type.ENTITY) {
return Optional.of(objectMouseOver().entityHit);
}
return Optional.empty();
}
}
@@ -1,46 +0,0 @@
/*
* 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;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ClickType;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.GameType;
/**
* @author Brady
* @since 12/14/2018
*/
public interface IPlayerController {
boolean onPlayerDamageBlock(BlockPos pos, EnumFacing side);
void resetBlockRemoving();
ItemStack windowClick(int windowId, int slotId, int mouseButton, ClickType type, EntityPlayer player);
void setGameType(GameType type);
GameType getGameType();
default double getBlockReachDistance() {
return this.getGameType().isCreative() ? 5.0F : 4.5F;
}
}
@@ -15,11 +15,13 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils.accessor;
package baritone.api.utils;
/**
* @author Brady
* @since 9/23/2018
*/
public class Logger {
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import net.minecraft.world.chunk.Chunk;
public interface IChunkProviderClient {
Long2ObjectMap<Chunk> loadedChunks();
}
@@ -1,55 +0,0 @@
/*
* 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;
import baritone.api.pathing.calc.IPath;
import java.util.Objects;
import java.util.Optional;
public class PathCalculationResult {
private final IPath path;
private final Type type;
public PathCalculationResult(Type type) {
this(type, null);
}
public PathCalculationResult(Type type, IPath path) {
Objects.requireNonNull(type);
this.path = path;
this.type = type;
}
public final Optional<IPath> getPath() {
return Optional.ofNullable(this.path);
}
public final Type getType() {
return this.type;
}
public enum Type {
SUCCESS_TO_GOAL,
SUCCESS_SEGMENT,
FAILURE,
CANCELLATION,
EXCEPTION,
}
}
@@ -17,36 +17,97 @@
package baritone.api.utils;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import java.util.Optional;
/**
* @author Brady
* @since 8/25/2018
*/
public final class RayTraceUtils {
/**
* The {@link Minecraft} instance
*/
private static final Minecraft mc = Minecraft.getMinecraft();
private RayTraceUtils() {}
/**
* Simulates a "vanilla" raytrace. A RayTraceResult returned by this method
* will be that of the next render pass given that the local player's yaw and
* pitch match the specified yaw and pitch values. This is particularly useful
* when you would like to simulate a "legit" raytrace with certainty that the only
* thing to achieve the desired outcome (whether it is hitting and entity or placing
* a block) can be done just by modifying user input.
*
* @param yaw The yaw to raytrace with
* @param pitch The pitch to raytrace with
* @return The calculated raytrace result
*/
public static RayTraceResult simulateRayTrace(float yaw, float pitch) {
RayTraceResult oldTrace = mc.objectMouseOver;
float oldYaw = mc.player.rotationYaw;
float oldPitch = mc.player.rotationPitch;
mc.player.rotationYaw = yaw;
mc.player.rotationPitch = pitch;
mc.entityRenderer.getMouseOver(1.0F);
RayTraceResult result = mc.objectMouseOver;
mc.objectMouseOver = oldTrace;
mc.player.rotationYaw = oldYaw;
mc.player.rotationPitch = oldPitch;
return result;
}
/**
* Performs a block raytrace with the specified rotations. This should only be used when
* any entity collisions can be ignored, because this method will not recognize if an
* entity is in the way or not. The local player's block reach distance will be used.
*
* @param entity The entity representing the raytrace source
* @param rotation The rotation to raytrace towards
* @param blockReachDistance The block reach distance of the entity
* @param rotation The rotation to raytrace towards
* @return The calculated raytrace result
*/
public static RayTraceResult rayTraceTowards(Entity entity, Rotation rotation, double blockReachDistance) {
Vec3d start = entity.getPositionEyes(1.0F);
public static RayTraceResult rayTraceTowards(Rotation rotation) {
double blockReachDistance = mc.playerController.getBlockReachDistance();
Vec3d start = mc.player.getPositionEyes(1.0F);
Vec3d direction = RotationUtils.calcVec3dFromRotation(rotation);
Vec3d end = start.add(
direction.x * blockReachDistance,
direction.y * blockReachDistance,
direction.z * blockReachDistance
);
return entity.world.rayTraceBlocks(start, end, false, false, true);
return mc.world.rayTraceBlocks(start, end, false, false, true);
}
/**
* Returns the block that the crosshair is currently placed over. Updated once per render tick.
*
* @return The position of the highlighted block
*/
public static Optional<BlockPos> getSelectedBlock() {
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) {
return Optional.of(mc.objectMouseOver.getBlockPos());
}
return Optional.empty();
}
/**
* Returns the entity that the crosshair is currently placed over. Updated once per render tick.
*
* @return The entity
*/
public static Optional<Entity> getSelectedEntity() {
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.ENTITY) {
return Optional.of(mc.objectMouseOver.entityHit);
}
return Optional.empty();
}
}
+4 -42
View File
@@ -86,7 +86,7 @@ public class Rotation {
public Rotation clamp() {
return new Rotation(
this.yaw,
clampPitch(this.pitch)
RotationUtils.clampPitch(this.pitch)
);
}
@@ -95,7 +95,7 @@ public class Rotation {
*/
public Rotation normalize() {
return new Rotation(
normalizeYaw(this.yaw),
RotationUtils.normalizeYaw(this.yaw),
this.pitch
);
}
@@ -105,46 +105,8 @@ public class Rotation {
*/
public Rotation normalizeAndClamp() {
return new Rotation(
normalizeYaw(this.yaw),
clampPitch(this.pitch)
RotationUtils.normalizeYaw(this.yaw),
RotationUtils.clampPitch(this.pitch)
);
}
/**
* Is really close to
*
* @param other another rotation
* @return are they really close
*/
public boolean isReallyCloseTo(Rotation other) {
float yawDiff = Math.abs(this.yaw - other.yaw); // you cant fool me
return (yawDiff < 0.01 || yawDiff > 359.9) && Math.abs(this.pitch - other.pitch) < 0.01;
}
/**
* Clamps the specified pitch value between -90 and 90.
*
* @param pitch The input pitch
* @return The clamped pitch
*/
public static float clampPitch(float pitch) {
return Math.max(-90, Math.min(90, pitch));
}
/**
* Normalizes the specified yaw value between -180 and 180.
*
* @param yaw The input yaw
* @return The normalized yaw
*/
public static float normalizeYaw(float yaw) {
float newYaw = yaw % 360F;
if (newYaw < -180F) {
newYaw += 360F;
}
if (newYaw > 180F) {
newYaw -= 360F;
}
return newYaw;
}
}
@@ -17,11 +17,9 @@
package baritone.api.utils;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import net.minecraft.block.BlockFire;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.*;
@@ -33,6 +31,11 @@ import java.util.Optional;
*/
public final class RotationUtils {
/**
* The {@link Minecraft} instance
*/
private static final Minecraft mc = Minecraft.getMinecraft();
/**
* Constant that a degree value is multiplied by to get the equivalent radian value
*/
@@ -57,6 +60,33 @@ public final class RotationUtils {
private RotationUtils() {}
/**
* Clamps the specified pitch value between -90 and 90.
*
* @param pitch The input pitch
* @return The clamped pitch
*/
public static float clampPitch(float pitch) {
return Math.max(-90, Math.min(90, pitch));
}
/**
* Normalizes the specified yaw value between -180 and 180.
*
* @param yaw The input yaw
* @return The normalized yaw
*/
public static float normalizeYaw(float yaw) {
float newYaw = yaw % 360F;
if (newYaw < -180F) {
newYaw += 360F;
}
if (newYaw >= 180F) {
newYaw -= 360F;
}
return newYaw;
}
/**
* Calculates the rotation from BlockPos<sub>dest</sub> to BlockPos<sub>orig</sub>
*
@@ -127,16 +157,6 @@ public final class RotationUtils {
return new Vec3d((double) (f1 * f2), (double) f3, (double) (f * f2));
}
/**
* @param ctx Context for the viewing entity
* @param pos The target block position
* @return The optional rotation
* @see #reachable(EntityPlayerSP, BlockPos, double)
*/
public static Optional<Rotation> reachable(IPlayerContext ctx, BlockPos pos) {
return reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance());
}
/**
* Determines if the specified entity is able to reach the center of any of the sides
* of the specified block. It first checks if the block center is reachable, and if so,
@@ -144,14 +164,12 @@ public final class RotationUtils {
* side that is reachable. The return type will be {@link Optional#empty()} if the entity is
* unable to reach any of the sides of the block.
*
* @param entity The viewing entity
* @param pos The target block position
* @param blockReachDistance The block reach distance of the entity
* @param entity The viewing entity
* @param pos The target block position
* @return The optional rotation
*/
public static Optional<Rotation> reachable(EntityPlayerSP entity, BlockPos pos, double blockReachDistance) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(entity);
if (pos.equals(baritone.getPlayerContext().getSelectedBlock().orElse(null))) {
public static Optional<Rotation> reachable(Entity entity, BlockPos pos) {
if (pos.equals(RayTraceUtils.getSelectedBlock().orElse(null))) {
/*
* why add 0.0001?
* to indicate that we actually have a desired pitch
@@ -164,19 +182,19 @@ public final class RotationUtils {
*/
return Optional.of(new Rotation(entity.rotationYaw, entity.rotationPitch + 0.0001F));
}
Optional<Rotation> possibleRotation = reachableCenter(entity, pos, blockReachDistance);
Optional<Rotation> possibleRotation = reachableCenter(entity, pos);
//System.out.println("center: " + possibleRotation);
if (possibleRotation.isPresent()) {
return possibleRotation;
}
IBlockState state = entity.world.getBlockState(pos);
IBlockState state = mc.world.getBlockState(pos);
AxisAlignedBB aabb = state.getBoundingBox(entity.world, pos);
for (Vec3d sideOffset : BLOCK_SIDE_MULTIPLIERS) {
double xDiff = aabb.minX * sideOffset.x + aabb.maxX * (1 - sideOffset.x);
double yDiff = aabb.minY * sideOffset.y + aabb.maxY * (1 - sideOffset.y);
double zDiff = aabb.minZ * sideOffset.z + aabb.maxZ * (1 - sideOffset.z);
possibleRotation = reachableOffset(entity, pos, new Vec3d(pos).add(xDiff, yDiff, zDiff), blockReachDistance);
possibleRotation = reachableOffset(entity, pos, new Vec3d(pos).add(xDiff, yDiff, zDiff));
if (possibleRotation.isPresent()) {
return possibleRotation;
}
@@ -189,15 +207,14 @@ public final class RotationUtils {
* the given offsetted position. The return type will be {@link Optional#empty()} if
* the entity is unable to reach the block with the offset applied.
*
* @param entity The viewing entity
* @param pos The target block position
* @param offsetPos The position of the block with the offset applied.
* @param blockReachDistance The block reach distance of the entity
* @param entity The viewing entity
* @param pos The target block position
* @param offsetPos The position of the block with the offset applied.
* @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) {
Rotation rotation = calcRotationFromVec3d(entity.getPositionEyes(1.0F), offsetPos);
RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance);
RayTraceResult result = RayTraceUtils.rayTraceTowards(rotation);
//System.out.println(result);
if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) {
if (result.getBlockPos().equals(pos)) {
@@ -214,12 +231,11 @@ public final class RotationUtils {
* Determines if the specified entity is able to reach the specified block where it is
* looking at the direct center of it's hitbox.
*
* @param entity The viewing entity
* @param pos The target block position
* @param blockReachDistance The block reach distance of the entity
* @param entity The viewing entity
* @param pos The target block position
* @return The optional rotation
*/
public static Optional<Rotation> reachableCenter(Entity entity, BlockPos pos, double blockReachDistance) {
return reachableOffset(entity, pos, VecUtils.calculateBlockCenter(entity.world, pos), blockReachDistance);
public static Optional<Rotation> reachableCenter(Entity entity, BlockPos pos) {
return reachableOffset(entity, pos, VecUtils.calculateBlockCenter(pos));
}
}
@@ -18,77 +18,56 @@
package baritone.api.utils;
import baritone.api.Settings;
import net.minecraft.client.Minecraft;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import java.awt.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static net.minecraft.client.Minecraft.getMinecraft;
public class SettingsUtil {
private static final Path SETTINGS_PATH = getMinecraft().gameDir.toPath().resolve("baritone").resolve("settings.txt");
private static final Pattern SETTING_PATTERN = Pattern.compile("^(?<setting>[^ ]+) +(?<value>[^ ]+)"); // 2 words separated by spaces
private static final File settingsFile = new File(new File(Minecraft.getMinecraft().gameDir, "baritone"), "settings.txt");
private static final Map<Class<?>, SettingsIO> map;
private static boolean isComment(String line) {
return line.startsWith("#") || line.startsWith("//");
}
private static void forEachLine(Path file, Consumer<String> consumer) throws IOException {
try (BufferedReader scan = Files.newBufferedReader(file)) {
String line;
while ((line = scan.readLine()) != null) {
if (line.isEmpty() || isComment(line)) {
public static void readAndApply(Settings settings) {
try (Scanner scan = new Scanner(settingsFile)) {
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.isEmpty()) {
continue;
}
consumer.accept(line);
}
}
}
public static void readAndApply(Settings settings) {
try {
forEachLine(SETTINGS_PATH, line -> {
Matcher matcher = SETTING_PATTERN.matcher(line);
if (!matcher.matches()) {
System.out.println("Invalid syntax in setting file: " + line);
return;
if (line.startsWith("#") || line.startsWith("//")) {
continue;
}
String settingName = matcher.group("setting").toLowerCase();
String settingValue = matcher.group("value");
int space = line.indexOf(" ");
if (space == -1) {
System.out.println("Skipping invalid line with no space: " + line);
continue;
}
String settingName = line.substring(0, space).trim().toLowerCase();
String settingValue = line.substring(space).trim();
try {
parseAndApply(settings, settingName, settingValue);
} catch (Exception ex) {
System.out.println("Unable to parse line " + line);
ex.printStackTrace();
System.out.println("Unable to parse line " + line);
}
});
}
} catch (Exception ex) {
System.out.println("Exception while reading Baritone settings, some settings may be reset to default values!");
ex.printStackTrace();
System.out.println("Exception while reading Baritone settings, some settings may be reset to default values!");
}
}
public static synchronized void save(Settings settings) {
try (BufferedWriter out = Files.newBufferedWriter(SETTINGS_PATH)) {
try (FileOutputStream out = new FileOutputStream(settingsFile)) {
for (Settings.Setting setting : settings.allSettings) {
if (setting.get() == null) {
System.out.println("NULL SETTING?" + setting.getName());
@@ -104,11 +83,11 @@ public class SettingsUtil {
if (io == null) {
throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting + " " + setting.getName());
}
out.write(setting.getName() + " " + io.toString.apply(setting.get()) + "\n");
out.write((setting.getName() + " " + io.toString.apply(setting.get()) + "\n").getBytes());
}
} catch (Exception ex) {
System.out.println("Exception thrown while saving Baritone settings!");
ex.printStackTrace();
System.out.println("Exception while saving Baritone settings!");
}
}
+10 -7
View File
@@ -19,31 +19,34 @@ package baritone.api.utils;
import net.minecraft.block.BlockFire;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
/**
* @author Brady
* @since 10/13/2018
*/
public final class VecUtils {
/**
* The {@link Minecraft} instance
*/
private static final Minecraft mc = Minecraft.getMinecraft();
private VecUtils() {}
/**
* Calculates the center of the block at the specified position's bounding box
*
* @param world The world that the block is in, used to provide the bounding box
* @param pos The block position
* @param pos The block position
* @return The center of the block's bounding box
* @see #getBlockPosCenter(BlockPos)
*/
public static Vec3d calculateBlockCenter(World world, BlockPos pos) {
IBlockState b = world.getBlockState(pos);
AxisAlignedBB bbox = b.getBoundingBox(world, pos);
public static Vec3d calculateBlockCenter(BlockPos pos) {
IBlockState b = mc.world.getBlockState(pos);
AxisAlignedBB bbox = b.getBoundingBox(mc.world, pos);
double xDiff = (bbox.minX + bbox.maxX) / 2;
double yDiff = (bbox.minY + bbox.maxY) / 2;
double zDiff = (bbox.minZ + bbox.maxZ) / 2;
@@ -65,7 +68,7 @@ public final class VecUtils {
*
* @param pos The block position
* @return The assumed center of the position
* @see #calculateBlockCenter(World, BlockPos)
* @see #calculateBlockCenter(BlockPos)
*/
public static Vec3d getBlockPosCenter(BlockPos pos) {
return new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5);
@@ -1,119 +0,0 @@
/*
* 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.input;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.client.settings.KeyBinding;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* An {@link Enum} representing the inputs that control the player's
* behavior. This includes moving, interacting with blocks, jumping,
* sneaking, and sprinting.
*/
public enum Input {
/**
* The move forward input
*/
MOVE_FORWARD(s -> s.keyBindForward),
/**
* The move back input
*/
MOVE_BACK(s -> s.keyBindBack),
/**
* The move left input
*/
MOVE_LEFT(s -> s.keyBindLeft),
/**
* The move right input
*/
MOVE_RIGHT(s -> s.keyBindRight),
/**
* The attack input
*/
CLICK_LEFT(s -> s.keyBindAttack),
/**
* The use item input
*/
CLICK_RIGHT(s -> s.keyBindUseItem),
/**
* The jump input
*/
JUMP(s -> s.keyBindJump),
/**
* The sneak input
*/
SNEAK(s -> s.keyBindSneak),
/**
* The sprint input
*/
SPRINT(s -> s.keyBindSprint);
/**
* Map of {@link KeyBinding} to {@link Input}. Values should be queried through {@link #getInputForBind(KeyBinding)}
*/
private static final Map<KeyBinding, Input> bindToInputMap = new HashMap<>();
/**
* The actual game {@link KeyBinding} being forced.
*/
private final KeyBinding keyBinding;
Input(Function<GameSettings, KeyBinding> keyBindingMapper) {
/*
Here, a Function is used because referring to a static field in this enum for the game instance,
as it was before, wouldn't be possible in an Enum constructor unless the static field was in an
interface that this class implemented. (Helper acted as this interface) I didn't feel like making
an interface with a game instance field just to not have to do this.
*/
this.keyBinding = keyBindingMapper.apply(Minecraft.getMinecraft().gameSettings);
}
/**
* @return The actual game {@link KeyBinding} being forced.
*/
public final KeyBinding getKeyBinding() {
return this.keyBinding;
}
/**
* Finds the {@link Input} constant that is associated with the specified {@link KeyBinding}.
*
* @param binding The {@link KeyBinding} to find the associated {@link Input} for
* @return The {@link Input} associated with the specified {@link KeyBinding}
*/
public static Input getInputForBind(KeyBinding binding) {
return bindToInputMap.computeIfAbsent(binding, b -> Arrays.stream(values()).filter(input -> input.keyBinding == b).findFirst().orElse(null));
}
}
@@ -15,36 +15,40 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.process;
package baritone.api.utils.interfaces;
import baritone.api.pathing.goals.Goal;
public interface ICustomGoalProcess extends IBaritoneProcess {
/**
* @author Brady
* @since 8/20/2018
*/
public interface Toggleable {
/**
* Sets the pathing goal
* Toggles the enabled state of this {@link Toggleable}.
*
* @param goal The new goal
* @return The new state.
*/
void setGoal(Goal goal);
boolean toggle();
/**
* Starts path calculation and execution.
*/
void path();
/**
* @return The current goal
*/
Goal getGoal();
/**
* Sets the goal and begins the path execution.
* Sets the enabled state of this {@link Toggleable}.
*
* @param goal The new goal
* @return The new state.
*/
default void setGoalAndPath(Goal goal) {
this.setGoal(goal);
this.path();
}
boolean setEnabled(boolean enabled);
/**
* @return Whether or not this {@link Toggleable} object is enabled
*/
boolean isEnabled();
/**
* Called when the state changes from disabled to enabled
*/
default void onEnable() {}
/**
* Called when the state changes from enabled to disabled
*/
default void onDisable() {}
}
@@ -29,7 +29,7 @@ import java.util.List;
/**
* @author Brady
* @since 7/31/2018
* @since 7/31/2018 9:59 PM
*/
public class BaritoneTweaker extends SimpleTweaker {
@@ -32,9 +32,7 @@ import java.io.File;
@Mixin(AnvilChunkLoader.class)
public class MixinAnvilChunkLoader implements IAnvilChunkLoader {
@Shadow
@Final
private File chunkSaveLocation;
@Shadow @Final private File chunkSaveLocation;
@Override
public File getChunkSaveLocation() {
@@ -35,12 +35,6 @@ public class MixinBlockPos extends Vec3i {
super(xIn, yIn, zIn);
}
/**
* The purpose of this was to ensure a friendly name for when we print raw
* block positions to chat in the context of an obfuscated environment.
*
* @return a string representation of the object.
*/
@Override
@Nonnull
public String toString() {
@@ -1,39 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.utils.accessor.IChunkProviderClient;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import net.minecraft.client.multiplayer.ChunkProviderClient;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(ChunkProviderClient.class)
public class MixinChunkProviderClient implements IChunkProviderClient {
@Shadow
@Final
private Long2ObjectMap<Chunk> loadedChunks;
@Override
public Long2ObjectMap<Chunk> loadedChunks() {
return this.loadedChunks;
}
}
@@ -31,9 +31,7 @@ import org.spongepowered.asm.mixin.Shadow;
@Mixin(ChunkProviderServer.class)
public class MixinChunkProviderServer implements IChunkProviderServer {
@Shadow
@Final
private IChunkLoader chunkLoader;
@Shadow @Final private IChunkLoader chunkLoader;
@Override
public IChunkLoader getChunkLoader() {
@@ -17,19 +17,16 @@
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.Baritone;
import baritone.api.event.events.RotationMoveEvent;
import baritone.api.event.events.type.EventState;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import static org.spongepowered.asm.lib.Opcodes.GETFIELD;
/**
* @author Brady
* @since 8/21/2018
@@ -37,38 +34,23 @@ import static org.spongepowered.asm.lib.Opcodes.GETFIELD;
@Mixin(Entity.class)
public class MixinEntity {
@Shadow
public float rotationYaw;
/**
* Event called to override the movement direction when walking
*/
private RotationMoveEvent motionUpdateRotationEvent;
@Inject(
method = "moveRelative",
at = @At("HEAD")
)
private void preMoveRelative(float strafe, float up, float forward, float friction, CallbackInfo ci) {
// noinspection ConstantConditions
if (EntityPlayerSP.class.isInstance(this)) {
this.motionUpdateRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw);
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.motionUpdateRotationEvent);
}
Entity _this = (Entity) (Object) this;
if (EntityPlayerSP.class.isInstance(_this))
Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.PRE, RotationMoveEvent.Type.MOTION_UPDATE));
}
@Redirect(
@Inject(
method = "moveRelative",
at = @At(
value = "FIELD",
opcode = GETFIELD,
target = "net/minecraft/entity/Entity.rotationYaw:F"
)
at = @At("RETURN")
)
private float overrideYaw(Entity self) {
if (self instanceof EntityPlayerSP) {
return this.motionUpdateRotationEvent.getYaw();
}
return self.rotationYaw;
private void postMoveRelative(float strafe, float up, float forward, float friction, CallbackInfo ci) {
Entity _this = (Entity) (Object) this;
if (EntityPlayerSP.class.isInstance(_this))
Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.POST, RotationMoveEvent.Type.MOTION_UPDATE));
}
}
@@ -17,61 +17,43 @@
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.Baritone;
import baritone.api.event.events.RotationMoveEvent;
import baritone.api.event.events.type.EventState;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import static org.spongepowered.asm.lib.Opcodes.GETFIELD;
/**
* @author Brady
* @since 9/10/2018
*/
@Mixin(EntityLivingBase.class)
public abstract class MixinEntityLivingBase extends Entity {
/**
* Event called to override the movement direction when jumping
*/
private RotationMoveEvent jumpRotationEvent;
public MixinEntityLivingBase(World worldIn, RotationMoveEvent jumpRotationEvent) {
super(worldIn);
this.jumpRotationEvent = jumpRotationEvent;
}
public class MixinEntityLivingBase {
@Inject(
method = "jump",
at = @At("HEAD")
)
private void preMoveRelative(CallbackInfo ci) {
// noinspection ConstantConditions
if (EntityPlayerSP.class.isInstance(this)) {
this.jumpRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.JUMP, this.rotationYaw);
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent);
}
private void preJump(CallbackInfo ci) {
EntityLivingBase _this = (EntityLivingBase) (Object) this;
// This uses Class.isInstance instead of instanceof since proguard optimizes out the instanceof (since MixinEntityLivingBase could never be instanceof EntityLivingBase in normal java)
// but proguard isn't smart enough to optimize out this Class.isInstance =)
if (EntityPlayerSP.class.isInstance(_this))
Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.PRE, RotationMoveEvent.Type.JUMP));
}
@Redirect(
@Inject(
method = "jump",
at = @At(
value = "FIELD",
opcode = GETFIELD,
target = "net/minecraft/entity/EntityLivingBase.rotationYaw:F"
)
at = @At("RETURN")
)
private float overrideYaw(EntityLivingBase self) {
if (self instanceof EntityPlayerSP) {
return this.jumpRotationEvent.getYaw();
}
return self.rotationYaw;
private void postJump(CallbackInfo ci) {
EntityLivingBase _this = (EntityLivingBase) (Object) this;
// See above
if (EntityPlayerSP.class.isInstance(_this))
Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(new RotationMoveEvent((EntityPlayerSP) _this, EventState.POST, RotationMoveEvent.Type.JUMP));
}
}
@@ -17,11 +17,11 @@
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.behavior.IPathingBehavior;
import baritone.Baritone;
import baritone.api.event.events.ChatEvent;
import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.type.EventState;
import baritone.behavior.PathingBehavior;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.player.PlayerCapabilities;
import org.spongepowered.asm.mixin.Mixin;
@@ -32,7 +32,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* @author Brady
* @since 8/1/2018
* @since 8/1/2018 5:06 PM
*/
@Mixin(EntityPlayerSP.class)
public class MixinEntityPlayerSP {
@@ -44,7 +44,7 @@ public class MixinEntityPlayerSP {
)
private void sendChatMessage(String msg, CallbackInfo ci) {
ChatEvent event = new ChatEvent((EntityPlayerSP) (Object) this, msg);
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onSendChatMessage(event);
Baritone.INSTANCE.getGameEventHandler().onSendChatMessage(event);
if (event.isCancelled()) {
ci.cancel();
}
@@ -60,7 +60,7 @@ public class MixinEntityPlayerSP {
)
)
private void onPreUpdate(CallbackInfo ci) {
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.PRE));
Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.PRE));
}
@Inject(
@@ -73,7 +73,7 @@ public class MixinEntityPlayerSP {
)
)
private void onPostUpdate(CallbackInfo ci) {
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST));
Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST));
}
@Redirect(
@@ -84,7 +84,7 @@ public class MixinEntityPlayerSP {
)
)
private boolean isAllowFlying(PlayerCapabilities capabilities) {
IPathingBehavior pathingBehavior = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getPathingBehavior();
return !pathingBehavior.isPathing() && capabilities.allowFlying;
PathingBehavior pathingBehavior = Baritone.INSTANCE.getPathingBehavior();
return (!pathingBehavior.isEnabled() || !pathingBehavior.isPathing()) && capabilities.allowFlying;
}
}
@@ -17,8 +17,7 @@
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.Baritone;
import baritone.api.event.events.RenderEvent;
import net.minecraft.client.renderer.EntityRenderer;
import org.spongepowered.asm.mixin.Mixin;
@@ -34,12 +33,10 @@ public class MixinEntityRenderer {
at = @At(
value = "INVOKE_STRING",
target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V",
args = {"ldc=hand"}
args = { "ldc=hand" }
)
)
private void renderWorldPass(int pass, float partialTicks, long finishTimeNano, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks));
}
Baritone.INSTANCE.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks));
}
}
@@ -17,52 +17,28 @@
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.utils.Helper;
import baritone.Baritone;
import net.minecraft.client.settings.KeyBinding;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
/**
* @author Brady
* @since 7/31/2018
* @since 7/31/2018 11:44 PM
*/
@Mixin(KeyBinding.class)
public class MixinKeyBinding {
@Shadow
public int pressTime;
@Inject(
method = "isKeyDown",
at = @At("HEAD"),
cancellable = true
)
private void isKeyDown(CallbackInfoReturnable<Boolean> cir) {
// only the primary baritone forces keys
Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this);
if (force != null) {
cir.setReturnValue(force); // :sunglasses:
}
}
@Inject(
method = "isPressed",
at = @At("HEAD"),
cancellable = true
)
private void isPressed(CallbackInfoReturnable<Boolean> cir) {
// only the primary baritone forces keys
Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this);
if (force != null && force == false) { // <-- cursed
if (pressTime > 0) {
Helper.HELPER.logDirect("You're trying to press this mouse button but I won't let you");
pressTime--;
}
cir.setReturnValue(force); // :sunglasses:
if (Baritone.INSTANCE.getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this)) {
cir.setReturnValue(true);
}
}
}
@@ -18,8 +18,6 @@
package baritone.launch.mixins;
import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.BlockInteractEvent;
import baritone.api.event.events.TickEvent;
import baritone.api.event.events.WorldEvent;
@@ -44,7 +42,7 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
/**
* @author Brady
* @since 7/31/2018
* @since 7/31/2018 10:51 PM
*/
@Mixin(Minecraft.class)
public class MixinMinecraft {
@@ -59,7 +57,7 @@ public class MixinMinecraft {
at = @At("RETURN")
)
private void postInit(CallbackInfo ci) {
((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).init();
Baritone.INSTANCE.init();
}
@Inject(
@@ -85,15 +83,21 @@ public class MixinMinecraft {
)
)
private void runTick(CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
TickEvent.Type type = ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().world() != null
? TickEvent.Type.IN
: TickEvent.Type.OUT;
ibaritone.getGameEventHandler().onTick(new TickEvent(EventState.PRE, type));
}
Minecraft mc = (Minecraft) (Object) this;
Baritone.INSTANCE.getGameEventHandler().onTick(new TickEvent(
EventState.PRE,
(mc.player != null && mc.world != null)
? TickEvent.Type.IN
: TickEvent.Type.OUT
));
}
@Inject(
method = "processKeyBinds",
at = @At("HEAD")
)
private void runTickKeyboard(CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onProcessKeyBinds();
}
@Inject(
@@ -106,9 +110,7 @@ public class MixinMinecraft {
return;
}
// mc.world changing is only the primary baritone
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onWorldEvent(
Baritone.INSTANCE.getGameEventHandler().onWorldEvent(
new WorldEvent(
world,
EventState.PRE
@@ -123,8 +125,7 @@ public class MixinMinecraft {
private void postLoadWorld(WorldClient world, String loadingMessage, CallbackInfo ci) {
// still fire event for both null, as that means we've just finished exiting a world
// mc.world changing is only the primary baritone
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onWorldEvent(
Baritone.INSTANCE.getGameEventHandler().onWorldEvent(
new WorldEvent(
world,
EventState.POST
@@ -141,8 +142,7 @@ public class MixinMinecraft {
)
)
private boolean isAllowUserInput(GuiScreen screen) {
// allow user input is only the primary baritone
return (BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().getCurrent() != null && player != null) || screen.allowUserInput;
return (Baritone.INSTANCE.getPathingBehavior().getCurrent() != null && Baritone.INSTANCE.getPathingBehavior().isEnabled() && player != null) || screen.allowUserInput;
}
@Inject(
@@ -154,8 +154,7 @@ public class MixinMinecraft {
locals = LocalCapture.CAPTURE_FAILHARD
)
private void onBlockBreak(CallbackInfo ci, BlockPos pos) {
// clickMouse is only for the main player
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(pos, BlockInteractEvent.Type.START_BREAK));
Baritone.INSTANCE.getGameEventHandler().onBlockInteract(new BlockInteractEvent(pos, BlockInteractEvent.Type.BREAK));
}
@Inject(
@@ -167,7 +166,6 @@ public class MixinMinecraft {
locals = LocalCapture.CAPTURE_FAILHARD
)
private void onBlockUse(CallbackInfo ci, EnumHand var1[], int var2, int var3, EnumHand enumhand, ItemStack itemstack, BlockPos blockpos, int i, EnumActionResult enumactionresult) {
// rightClickMouse is only for the main player
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(blockpos, BlockInteractEvent.Type.USE));
Baritone.INSTANCE.getGameEventHandler().onBlockInteract(new BlockInteractEvent(blockpos, BlockInteractEvent.Type.USE));
}
}
@@ -17,8 +17,7 @@
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.Baritone;
import baritone.api.event.events.ChunkEvent;
import baritone.api.event.events.type.EventState;
import net.minecraft.client.network.NetHandlerPlayClient;
@@ -31,7 +30,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* @author Brady
* @since 8/3/2018
* @since 8/3/2018 12:54 AM
*/
@Mixin(NetHandlerPlayClient.class)
public class MixinNetHandlerPlayClient {
@@ -44,18 +43,14 @@ public class MixinNetHandlerPlayClient {
)
)
private void preRead(SPacketChunkData packetIn, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.PRE,
packetIn.isFullChunk() ? ChunkEvent.Type.POPULATE_FULL : ChunkEvent.Type.POPULATE_PARTIAL,
packetIn.getChunkX(),
packetIn.getChunkZ()
)
);
}
}
Baritone.INSTANCE.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.PRE,
ChunkEvent.Type.POPULATE,
packetIn.getChunkX(),
packetIn.getChunkZ()
)
);
}
@Inject(
@@ -63,18 +58,14 @@ public class MixinNetHandlerPlayClient {
at = @At("RETURN")
)
private void postHandleChunkData(SPacketChunkData packetIn, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.POST,
packetIn.isFullChunk() ? ChunkEvent.Type.POPULATE_FULL : ChunkEvent.Type.POPULATE_PARTIAL,
packetIn.getChunkX(),
packetIn.getChunkZ()
)
);
}
}
Baritone.INSTANCE.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.POST,
ChunkEvent.Type.POPULATE,
packetIn.getChunkX(),
packetIn.getChunkZ()
)
);
}
@Inject(
@@ -85,10 +76,6 @@ public class MixinNetHandlerPlayClient {
)
)
private void onPlayerDeath(SPacketCombatEvent packetIn, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) {
ibaritone.getGameEventHandler().onPlayerDeath();
}
}
Baritone.INSTANCE.getGameEventHandler().onPlayerDeath();
}
}
@@ -17,8 +17,7 @@
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.Baritone;
import baritone.api.event.events.PacketEvent;
import baritone.api.event.events.type.EventState;
import io.netty.channel.Channel;
@@ -37,7 +36,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* @author Brady
* @since 8/6/2018
* @since 8/6/2018 9:30 PM
*/
@Mixin(NetworkManager.class)
public class MixinNetworkManager {
@@ -54,14 +53,8 @@ public class MixinNetworkManager {
at = @At("HEAD")
)
private void preDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>>[] futureListeners, CallbackInfo ci) {
if (this.direction != EnumPacketDirection.CLIENTBOUND) {
return;
}
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) {
ibaritone.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, inPacket));
}
if (this.direction == EnumPacketDirection.CLIENTBOUND) {
Baritone.INSTANCE.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, inPacket));
}
}
@@ -70,14 +63,8 @@ public class MixinNetworkManager {
at = @At("RETURN")
)
private void postDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>>[] futureListeners, CallbackInfo ci) {
if (this.direction != EnumPacketDirection.CLIENTBOUND) {
return;
}
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) {
ibaritone.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, inPacket));
}
if (this.direction == EnumPacketDirection.CLIENTBOUND) {
Baritone.INSTANCE.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, inPacket));
}
}
@@ -89,14 +76,8 @@ public class MixinNetworkManager {
)
)
private void preProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) {
if (this.direction != EnumPacketDirection.CLIENTBOUND) {
return;
}
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) {
ibaritone.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, packet));
}
}
if (this.direction == EnumPacketDirection.CLIENTBOUND) {
Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, packet));}
}
@Inject(
@@ -104,13 +85,8 @@ public class MixinNetworkManager {
at = @At("RETURN")
)
private void postProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) {
if (!this.channel.isOpen() || this.direction != EnumPacketDirection.CLIENTBOUND) {
return;
}
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) {
ibaritone.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, packet));
}
if (this.channel.isOpen() && this.direction == EnumPacketDirection.CLIENTBOUND) {
Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, packet));
}
}
}
@@ -17,8 +17,7 @@
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.Baritone;
import baritone.api.event.events.ChunkEvent;
import baritone.api.event.events.type.EventState;
import net.minecraft.client.multiplayer.WorldClient;
@@ -29,7 +28,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/**
* @author Brady
* @since 8/2/2018
* @since 8/2/2018 12:41 AM
*/
@Mixin(WorldClient.class)
public class MixinWorldClient {
@@ -39,19 +38,14 @@ public class MixinWorldClient {
at = @At("HEAD")
)
private void preDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().world() == (WorldClient) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.PRE,
loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD,
chunkX,
chunkZ
)
);
}
}
Baritone.INSTANCE.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.PRE,
loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD,
chunkX,
chunkZ
)
);
}
@Inject(
@@ -59,17 +53,13 @@ public class MixinWorldClient {
at = @At("RETURN")
)
private void postDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().world() == (WorldClient) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.POST,
loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD,
chunkX,
chunkZ
)
);
}
}
Baritone.INSTANCE.getGameEventHandler().onChunkEvent(
new ChunkEvent(
EventState.POST,
loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD,
chunkX,
chunkZ
)
);
}
}
@@ -10,7 +10,6 @@
"client": [
"MixinAnvilChunkLoader",
"MixinBlockPos",
"MixinChunkProviderClient",
"MixinChunkProviderServer",
"MixinEntity",
"MixinEntityLivingBase",
+80 -95
View File
@@ -18,22 +18,16 @@
package baritone;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.IBaritoneProvider;
import baritone.api.Settings;
import baritone.api.event.listener.IEventBus;
import baritone.api.utils.IPlayerContext;
import baritone.api.event.listener.IGameEventListener;
import baritone.behavior.*;
import baritone.cache.WorldProvider;
import baritone.cache.WorldScanner;
import baritone.event.GameEventHandler;
import baritone.process.CustomGoalProcess;
import baritone.process.FollowProcess;
import baritone.process.GetToBlockProcess;
import baritone.process.MineProcess;
import baritone.utils.BaritoneAutoTest;
import baritone.utils.ExampleBaritoneControl;
import baritone.utils.InputOverrideHandler;
import baritone.utils.PathingControlManager;
import baritone.utils.player.PrimaryPlayerContext;
import net.minecraft.client.Minecraft;
import java.io.File;
@@ -48,23 +42,14 @@ import java.util.concurrent.TimeUnit;
/**
* @author Brady
* @since 7/31/2018
* @since 7/31/2018 10:50 PM
*/
public class Baritone implements IBaritone {
public enum Baritone implements IBaritoneProvider {
private static ThreadPoolExecutor threadPool;
private static File dir;
static {
threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>());
dir = new File(Minecraft.getMinecraft().gameDir, "baritone");
if (!Files.exists(dir.toPath())) {
try {
Files.createDirectories(dir.toPath());
} catch (IOException ignored) {}
}
}
/**
* Singleton instance of this class
*/
INSTANCE;
/**
* Whether or not {@link Baritone#init()} has been called yet
@@ -72,34 +57,37 @@ public class Baritone implements IBaritone {
private boolean initialized;
private GameEventHandler gameEventHandler;
private InputOverrideHandler inputOverrideHandler;
private Settings settings;
private File dir;
private ThreadPoolExecutor threadPool;
private List<Behavior> behaviors;
private PathingBehavior pathingBehavior;
private LookBehavior lookBehavior;
private MemoryBehavior memoryBehavior;
private InputOverrideHandler inputOverrideHandler;
private FollowBehavior followBehavior;
private MineBehavior mineBehavior;
private FollowProcess followProcess;
private MineProcess mineProcess;
private GetToBlockProcess getToBlockProcess;
private CustomGoalProcess customGoalProcess;
private PathingControlManager pathingControlManager;
private IPlayerContext playerContext;
private WorldProvider worldProvider;
/**
* Whether or not Baritone is active
*/
private boolean active;
Baritone() {
this.gameEventHandler = new GameEventHandler(this);
this.gameEventHandler = new GameEventHandler();
}
public synchronized void init() {
if (initialized) {
return;
}
this.threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>());
this.inputOverrideHandler = new InputOverrideHandler();
// Define this before behaviors try and get it, or else it will be null and the builds will fail!
this.playerContext = PrimaryPlayerContext.INSTANCE;
// Acquire the "singleton" instance of the settings directly from the API
// We might want to change this...
this.settings = BaritoneAPI.getSettings();
this.behaviors = new ArrayList<>();
{
@@ -107,105 +95,102 @@ public class Baritone implements IBaritone {
pathingBehavior = new PathingBehavior(this);
lookBehavior = new LookBehavior(this);
memoryBehavior = new MemoryBehavior(this);
new InventoryBehavior(this);
inputOverrideHandler = new InputOverrideHandler(this);
followBehavior = new FollowBehavior(this);
mineBehavior = new MineBehavior(this);
new ExampleBaritoneControl(this);
}
this.pathingControlManager = new PathingControlManager(this);
{
followProcess = new FollowProcess(this);
mineProcess = new MineProcess(this);
customGoalProcess = new CustomGoalProcess(this); // very high iq
getToBlockProcess = new GetToBlockProcess(this);
}
this.worldProvider = new WorldProvider();
if (BaritoneAutoTest.ENABLE_AUTO_TEST) {
this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE);
registerEventListener(BaritoneAutoTest.INSTANCE);
}
this.dir = new File(Minecraft.getMinecraft().gameDir, "baritone");
if (!Files.exists(dir.toPath())) {
try {
Files.createDirectories(dir.toPath());
} catch (IOException ignored) {}
}
this.active = true;
this.initialized = true;
}
@Override
public PathingControlManager getPathingControlManager() {
return this.pathingControlManager;
public boolean isInitialized() {
return this.initialized;
}
public IGameEventListener getGameEventHandler() {
return this.gameEventHandler;
}
public InputOverrideHandler getInputOverrideHandler() {
return this.inputOverrideHandler;
}
public List<Behavior> getBehaviors() {
return this.behaviors;
}
public Executor getExecutor() {
return threadPool;
}
public void registerBehavior(Behavior behavior) {
this.behaviors.add(behavior);
this.gameEventHandler.registerEventListener(behavior);
this.registerEventListener(behavior);
}
@Override
public InputOverrideHandler getInputOverrideHandler() {
return this.inputOverrideHandler;
}
@Override
public CustomGoalProcess getCustomGoalProcess() { // Iffy
return this.customGoalProcess;
}
@Override
public GetToBlockProcess getGetToBlockProcess() { // Iffy
return this.getToBlockProcess;
}
@Override
public IPlayerContext getPlayerContext() {
return this.playerContext;
}
public MemoryBehavior getMemoryBehavior() {
return this.memoryBehavior;
}
@Override
public FollowProcess getFollowProcess() {
return this.followProcess;
public FollowBehavior getFollowBehavior() {
return followBehavior;
}
@Override
public LookBehavior getLookBehavior() {
return this.lookBehavior;
return lookBehavior;
}
@Override
public MineProcess getMineProcess() {
return this.mineProcess;
public MemoryBehavior getMemoryBehavior() {
return memoryBehavior;
}
@Override
public MineBehavior getMineBehavior() {
return mineBehavior;
}
@Override
public PathingBehavior getPathingBehavior() {
return this.pathingBehavior;
return pathingBehavior;
}
@Override
public WorldProvider getWorldProvider() {
return this.worldProvider;
return WorldProvider.INSTANCE;
}
@Override
public IEventBus getGameEventHandler() {
return this.gameEventHandler;
public WorldScanner getWorldScanner() {
return WorldScanner.INSTANCE;
}
@Override
public void registerEventListener(IGameEventListener listener) {
this.gameEventHandler.registerEventListener(listener);
}
public boolean isActive() {
return this.active;
}
public Settings getSettings() {
return this.settings;
}
public static Settings settings() {
return BaritoneAPI.getSettings();
return Baritone.INSTANCE.settings; // yolo
}
public static File getDir() {
return dir;
}
public static Executor getExecutor() {
return threadPool;
public File getDir() {
return this.dir;
}
}
+35 -11
View File
@@ -17,35 +17,59 @@
package baritone;
import baritone.api.IBaritone;
import baritone.api.IBaritoneProvider;
import baritone.api.behavior.*;
import baritone.api.cache.IWorldProvider;
import baritone.api.cache.IWorldScanner;
import baritone.api.event.listener.IGameEventListener;
import baritone.cache.WorldProvider;
import baritone.cache.WorldScanner;
import java.util.Collections;
import java.util.List;
/**
* todo fix this cancer
*
* @author Brady
* @since 9/29/2018
*/
public final class BaritoneProvider implements IBaritoneProvider {
private final Baritone primary = new Baritone();
@Override
public IBaritone getPrimaryBaritone() {
return primary;
public IFollowBehavior getFollowBehavior() {
return Baritone.INSTANCE.getFollowBehavior();
}
@Override
public List<IBaritone> getAllBaritones() {
// TODO return a CopyOnWriteArrayList
return Collections.singletonList(primary);
public ILookBehavior getLookBehavior() {
return Baritone.INSTANCE.getLookBehavior();
}
@Override
public IMemoryBehavior getMemoryBehavior() {
return Baritone.INSTANCE.getMemoryBehavior();
}
@Override
public IMineBehavior getMineBehavior() {
return Baritone.INSTANCE.getMineBehavior();
}
@Override
public IPathingBehavior getPathingBehavior() {
return Baritone.INSTANCE.getPathingBehavior();
}
@Override
public IWorldProvider getWorldProvider() {
return WorldProvider.INSTANCE;
}
@Override
public IWorldScanner getWorldScanner() {
return WorldScanner.INSTANCE;
}
@Override
public void registerEventListener(IGameEventListener listener) {
Baritone.INSTANCE.registerEventListener(listener);
}
}
+43 -5
View File
@@ -19,22 +19,60 @@ package baritone.behavior;
import baritone.Baritone;
import baritone.api.behavior.IBehavior;
import baritone.api.utils.IPlayerContext;
/**
* A type of game event listener that is given {@link Baritone} instance context.
* A type of game event listener that can be toggled.
*
* @author Brady
* @since 8/1/2018
* @since 8/1/2018 6:29 PM
*/
public class Behavior implements IBehavior {
public final Baritone baritone;
public final IPlayerContext ctx;
/**
* Whether or not this behavior is enabled
*/
private boolean enabled = true;
protected Behavior(Baritone baritone) {
this.baritone = baritone;
this.ctx = baritone.getPlayerContext();
baritone.registerBehavior(this);
}
/**
* Toggles the enabled state of this {@link Behavior}.
*
* @return The new state.
*/
@Override
public final boolean toggle() {
return this.setEnabled(!this.isEnabled());
}
/**
* Sets the enabled state of this {@link Behavior}.
*
* @return The new state.
*/
@Override
public final boolean setEnabled(boolean enabled) {
if (enabled == this.enabled) {
return this.enabled;
}
if (this.enabled = enabled) {
this.onEnable();
} else {
this.onDisable();
}
return this.enabled;
}
/**
* @return Whether or not this {@link Behavior} is active.
*/
@Override
public final boolean isEnabled() {
return this.enabled;
}
}
@@ -0,0 +1,79 @@
/*
* 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.behavior;
import baritone.Baritone;
import baritone.api.behavior.IFollowBehavior;
import baritone.api.event.events.TickEvent;
import baritone.api.pathing.goals.GoalNear;
import baritone.api.pathing.goals.GoalXZ;
import baritone.utils.Helper;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
/**
* Follow an entity
*
* @author leijurv
*/
public final class FollowBehavior extends Behavior implements IFollowBehavior, Helper {
private Entity following;
public FollowBehavior(Baritone baritone) {
super(baritone);
}
@Override
public void onTick(TickEvent event) {
if (event.getType() == TickEvent.Type.OUT) {
following = null;
return;
}
if (following == null) {
return;
}
// lol this is trashy but it works
BlockPos pos;
if (Baritone.settings().followOffsetDistance.get() == 0) {
pos = following.getPosition();
} else {
GoalXZ g = GoalXZ.fromDirection(following.getPositionVector(), Baritone.settings().followOffsetDirection.get(), Baritone.settings().followOffsetDistance.get());
pos = new BlockPos(g.getX(), following.posY, g.getZ());
}
baritone.getPathingBehavior().setGoal(new GoalNear(pos, Baritone.settings().followRadius.get()));
((PathingBehavior) baritone.getPathingBehavior()).revalidateGoal();
baritone.getPathingBehavior().path();
}
@Override
public void follow(Entity entity) {
this.following = entity;
}
@Override
public Entity following() {
return this.following;
}
@Override
public void cancel() {
baritone.getPathingBehavior().cancel();
follow(null);
}
}
@@ -1,90 +0,0 @@
/*
* 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.behavior;
import baritone.Baritone;
import baritone.api.event.events.TickEvent;
import baritone.utils.ToolSet;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.ClickType;
import net.minecraft.item.ItemPickaxe;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import net.minecraft.util.NonNullList;
public class InventoryBehavior extends Behavior {
public InventoryBehavior(Baritone baritone) {
super(baritone);
}
@Override
public void onTick(TickEvent event) {
if (!Baritone.settings().allowInventory.get()) {
return;
}
if (event.getType() == TickEvent.Type.OUT) {
return;
}
if (ctx.player().openContainer != ctx.player().inventoryContainer) {
// we have a crafting table or a chest or something open
return;
}
if (firstValidThrowaway() >= 9) { // aka there are none on the hotbar, but there are some in main inventory
swapWithHotBar(firstValidThrowaway(), 8);
}
int pick = bestToolAgainst(Blocks.STONE, ItemPickaxe.class);
if (pick >= 9) {
swapWithHotBar(pick, 0);
}
}
private void swapWithHotBar(int inInventory, int inHotbar) {
ctx.playerController().windowClick(ctx.player().inventoryContainer.windowId, inInventory < 9 ? inInventory + 36 : inInventory, inHotbar, ClickType.SWAP, ctx.player());
}
private int firstValidThrowaway() { // TODO offhand idk
NonNullList<ItemStack> invy = ctx.player().inventory.mainInventory;
for (int i = 0; i < invy.size(); i++) {
if (Baritone.settings().acceptableThrowawayItems.get().contains(invy.get(i).getItem())) {
return i;
}
}
return -1;
}
private int bestToolAgainst(Block against, Class<? extends ItemTool> klass) {
NonNullList<ItemStack> invy = ctx.player().inventory.mainInventory;
int bestInd = -1;
double bestSpeed = -1;
for (int i = 0; i < invy.size(); i++) {
ItemStack stack = invy.get(i);
if (stack.isEmpty()) {
continue;
}
if (klass.isInstance(stack.getItem())) {
double speed = ToolSet.calculateSpeedVsBlock(stack, against.getDefaultState()); // takes into account enchants
if (speed > bestSpeed) {
bestSpeed = speed;
bestInd = i;
}
}
}
return bestInd;
}
}
@@ -23,9 +23,9 @@ import baritone.api.behavior.ILookBehavior;
import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.RotationMoveEvent;
import baritone.api.utils.Rotation;
import baritone.utils.Helper;
public final class LookBehavior extends Behavior implements ILookBehavior {
public final class LookBehavior extends Behavior implements ILookBehavior, Helper {
/**
* Target's values are as follows:
* <p>
@@ -63,29 +63,28 @@ public final class LookBehavior extends Behavior implements ILookBehavior {
}
// Whether or not we're going to silently set our angles
boolean silent = Baritone.settings().antiCheatCompatibility.get() && !this.force;
boolean silent = Baritone.settings().antiCheatCompatibility.get();
switch (event.getState()) {
case PRE: {
if (this.force) {
ctx.player().rotationYaw = this.target.getYaw();
float oldPitch = ctx.player().rotationPitch;
player().rotationYaw = this.target.getYaw();
float oldPitch = player().rotationPitch;
float desiredPitch = this.target.getPitch();
ctx.player().rotationPitch = desiredPitch;
player().rotationPitch = desiredPitch;
if (desiredPitch == oldPitch) {
nudgeToLevel();
}
this.target = null;
}
if (silent) {
this.lastYaw = ctx.player().rotationYaw;
ctx.player().rotationYaw = this.target.getYaw();
} else if (silent) {
this.lastYaw = player().rotationYaw;
player().rotationYaw = this.target.getYaw();
}
break;
}
case POST: {
if (silent) {
ctx.player().rotationYaw = this.lastYaw;
if (!this.force && silent) {
player().rotationYaw = this.lastYaw;
this.target = null;
}
break;
@@ -98,25 +97,31 @@ public final class LookBehavior extends Behavior implements ILookBehavior {
@Override
public void onPlayerRotationMove(RotationMoveEvent event) {
if (this.target != null && !this.force) {
switch (event.getState()) {
case PRE:
this.lastYaw = player().rotationYaw;
player().rotationYaw = this.target.getYaw();
break;
case POST:
player().rotationYaw = this.lastYaw;
event.setYaw(this.target.getYaw());
// 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
if (!Baritone.settings().antiCheatCompatibility.get() && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE) {
this.target = null;
// 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
if (!Baritone.settings().antiCheatCompatibility.get() && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE) {
this.target = null;
}
break;
default:
break;
}
}
}
/**
* Nudges the player's pitch to a regular level. (Between {@code -20} and {@code 10}, increments are by {@code 1})
*/
private void nudgeToLevel() {
if (ctx.player().rotationPitch < -20) {
ctx.player().rotationPitch++;
} else if (ctx.player().rotationPitch > 10) {
ctx.player().rotationPitch--;
if (player().rotationPitch < -20) {
player().rotationPitch++;
} else if (player().rotationPitch > 10) {
player().rotationPitch--;
}
}
}
@@ -18,18 +18,18 @@
package baritone.behavior;
import baritone.Baritone;
import baritone.api.behavior.IMemoryBehavior;
import baritone.api.behavior.memory.IRememberedInventory;
import baritone.api.cache.IWorldData;
import baritone.api.event.events.BlockInteractEvent;
import baritone.api.event.events.PacketEvent;
import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.TickEvent;
import baritone.api.event.events.type.EventState;
import baritone.cache.ContainerMemory;
import baritone.cache.Waypoint;
import baritone.pathing.movement.CalculationContext;
import baritone.cache.WorldProvider;
import baritone.utils.BlockStateInterface;
import net.minecraft.block.Block;
import baritone.utils.Helper;
import net.minecraft.block.BlockBed;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.CPacketCloseWindow;
@@ -38,37 +38,22 @@ import net.minecraft.network.play.server.SPacketCloseWindow;
import net.minecraft.network.play.server.SPacketOpenWindow;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityLockable;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentTranslation;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
/**
* @author Brady
* @since 8/6/2018
* @since 8/6/2018 9:47 PM
*/
public final class MemoryBehavior extends Behavior {
public final class MemoryBehavior extends Behavior implements IMemoryBehavior, Helper {
private final List<FutureInventory> futureInventories = new ArrayList<>(); // this is per-bot
private Integer enderChestWindowId; // nae nae
private final Map<IWorldData, WorldDataContainer> worldDataContainers = new HashMap<>();
public MemoryBehavior(Baritone baritone) {
super(baritone);
}
@Override
public synchronized void onTick(TickEvent event) {
if (event.getType() == TickEvent.Type.OUT) {
enderChestWindowId = null;
futureInventories.clear();
}
}
@Override
public synchronized void onPlayerUpdate(PlayerUpdateEvent event) {
if (event.getState() == EventState.PRE) {
@@ -84,31 +69,20 @@ public final class MemoryBehavior extends Behavior {
if (p instanceof CPacketPlayerTryUseItemOnBlock) {
CPacketPlayerTryUseItemOnBlock packet = event.cast();
TileEntity tileEntity = ctx.world().getTileEntity(packet.getPos());
// if tileEntity is an ender chest, we don't need to do anything. ender chests are treated the same regardless of what coordinate right clicked
TileEntity tileEntity = world().getTileEntity(packet.getPos());
// Ensure the TileEntity is a container of some sort
if (tileEntity instanceof TileEntityLockable) {
TileEntityLockable lockable = (TileEntityLockable) tileEntity;
int size = lockable.getSizeInventory();
BlockPos position = tileEntity.getPos();
BlockPos adj = neighboringConnectedBlock(position);
System.out.println(position + " " + adj);
if (adj != null) {
size *= 2; // double chest or double trapped chest
if (adj.getX() < position.getX() || adj.getZ() < position.getZ()) {
position = adj; // standardize on the lower coordinate, regardless of which side of the large chest we right clicked
}
}
this.futureInventories.add(new FutureInventory(System.nanoTime() / 1000000L, size, lockable.getGuiID(), position));
this.getCurrentContainer().futureInventories.add(new FutureInventory(System.nanoTime() / 1000000L, size, lockable.getGuiID(), tileEntity.getPos()));
}
}
if (p instanceof CPacketCloseWindow) {
updateInventory();
getCurrent().save();
}
}
}
@@ -120,82 +94,80 @@ public final class MemoryBehavior extends Behavior {
if (event.getState() == EventState.PRE) {
if (p instanceof SPacketOpenWindow) {
SPacketOpenWindow packet = event.cast();
// Remove any entries that were created over a second ago, this should make up for INSANE latency
futureInventories.removeIf(i -> System.nanoTime() / 1000000L - i.time > 1000);
System.out.println("Received packet " + packet.getGuiId() + " " + packet.getEntityId() + " " + packet.getSlotCount() + " " + packet.getWindowId());
System.out.println(packet.getWindowTitle());
if (packet.getWindowTitle() instanceof TextComponentTranslation && ((TextComponentTranslation) packet.getWindowTitle()).getKey().equals("container.enderchest")) {
// title is not customized (i.e. this isn't just a renamed shulker)
enderChestWindowId = packet.getWindowId();
return;
}
futureInventories.stream()
WorldDataContainer container = this.getCurrentContainer();
// Remove any entries that were created over a second ago, this should make up for INSANE latency
container.futureInventories.removeIf(i -> System.nanoTime() / 1000000L - i.time > 1000);
container.futureInventories.stream()
.filter(i -> i.type.equals(packet.getGuiId()) && i.slots == packet.getSlotCount())
.findFirst().ifPresent(matched -> {
// Remove the future inventory
futureInventories.remove(matched);
container.futureInventories.remove(matched);
// Setup the remembered inventory
getCurrentContainer().setup(matched.pos, packet.getWindowId(), packet.getSlotCount());
RememberedInventory inventory = container.rememberedInventories.computeIfAbsent(matched.pos, pos -> new RememberedInventory());
inventory.windowId = packet.getWindowId();
inventory.size = packet.getSlotCount();
});
}
if (p instanceof SPacketCloseWindow) {
updateInventory();
getCurrent().save();
}
}
}
@Override
public void onBlockInteract(BlockInteractEvent event) {
if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(ctx, event.getPos()) instanceof BlockBed) {
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, event.getPos()));
if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(event.getPos()) instanceof BlockBed) {
WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, event.getPos()));
}
}
@Override
public void onPlayerDeath() {
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, ctx.playerFeet()));
WorldProvider.INSTANCE.getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, playerFeet()));
}
private Optional<RememberedInventory> getInventoryFromWindow(int windowId) {
return this.getCurrentContainer().rememberedInventories.values().stream().filter(i -> i.windowId == windowId).findFirst();
}
private void updateInventory() {
int windowId = ctx.player().openContainer.windowId;
if (enderChestWindowId != null) {
if (windowId == enderChestWindowId) {
getCurrent().contents = ctx.player().openContainer.getInventory().subList(0, 27);
} else {
getCurrent().save();
enderChestWindowId = null;
}
}
if (getCurrentContainer() != null) {
getCurrentContainer().getInventoryFromWindow(windowId).ifPresent(inventory -> inventory.updateFromOpenWindow(ctx));
}
getInventoryFromWindow(player().openContainer.windowId).ifPresent(inventory -> {
inventory.items.clear();
inventory.items.addAll(player().openContainer.getInventory().subList(0, inventory.size));
});
}
private ContainerMemory getCurrentContainer() {
if (baritone.getWorldProvider().getCurrentWorld() == null) {
return null;
}
return (ContainerMemory) baritone.getWorldProvider().getCurrentWorld().getContainerMemory();
private WorldDataContainer getCurrentContainer() {
return this.worldDataContainers.computeIfAbsent(WorldProvider.INSTANCE.getCurrentWorld(), data -> new WorldDataContainer());
}
private BlockPos neighboringConnectedBlock(BlockPos in) {
BlockStateInterface bsi = new CalculationContext(baritone).bsi;
Block block = bsi.get0(in).getBlock();
if (block != Blocks.TRAPPED_CHEST && block != Blocks.CHEST) {
return null; // other things that have contents, but can be placed adjacent without combining
}
for (int i = 0; i < 4; i++) {
BlockPos adj = in.offset(EnumFacing.byHorizontalIndex(i));
if (bsi.get0(adj).getBlock() == block) {
return adj;
}
}
return null;
@Override
public final synchronized RememberedInventory getInventoryByPos(BlockPos pos) {
return this.getCurrentContainer().rememberedInventories.get(pos);
}
@Override
public final synchronized Map<BlockPos, IRememberedInventory> getRememberedInventories() {
// make a copy since this map is modified from the packet thread
return new HashMap<>(this.getCurrentContainer().rememberedInventories);
}
private static final class WorldDataContainer {
/**
* Possible future inventories that we will be able to remember
*/
private final List<FutureInventory> futureInventories = new ArrayList<>();
/**
* The current remembered inventories
*/
private final Map<BlockPos, RememberedInventory> rememberedInventories = new HashMap<>();
}
/**
@@ -228,51 +200,43 @@ public final class MemoryBehavior extends Behavior {
this.slots = slots;
this.type = type;
this.pos = pos;
System.out.println("Future inventory created " + time + " " + slots + " " + type + " " + pos);
}
}
public Optional<List<ItemStack>> echest() {
return Optional.ofNullable(getCurrent().contents).map(Collections::unmodifiableList);
}
/**
* An inventory that we are aware of.
* <p>
* Associated with a {@link BlockPos} in {@link WorldDataContainer#rememberedInventories}.
*/
public static class RememberedInventory implements IRememberedInventory {
public EnderChestMemory getCurrent() {
Path path = baritone.getWorldProvider().getCurrentWorld().directory;
return EnderChestMemory.getByServerAndPlayer(path.getParent(), ctx.player().getUniqueID());
}
/**
* The list of items in the inventory
*/
private final List<ItemStack> items;
public static class EnderChestMemory {
private static final Map<Path, EnderChestMemory> memory = new HashMap<>();
private final Path enderChest;
private List<ItemStack> contents;
/**
* The last known window ID of the inventory
*/
private int windowId;
private EnderChestMemory(Path enderChest) {
this.enderChest = enderChest;
System.out.println("Echest storing in " + enderChest);
try {
this.contents = ContainerMemory.readItemStacks(Files.readAllBytes(enderChest));
} catch (IOException e) {
e.printStackTrace();
System.out.println("CANNOT read echest =( =(");
this.contents = null;
}
/**
* The size of the inventory
*/
private int size;
private RememberedInventory() {
this.items = new ArrayList<>();
}
public synchronized void save() {
System.out.println("Saving");
if (contents != null) {
try {
enderChest.getParent().toFile().mkdir();
Files.write(enderChest, ContainerMemory.writeItemStacks(contents));
} catch (IOException e) {
e.printStackTrace();
System.out.println("CANNOT save echest =( =(");
}
}
@Override
public final List<ItemStack> getContents() {
return Collections.unmodifiableList(this.items);
}
private static synchronized EnderChestMemory getByServerAndPlayer(Path serverStorage, UUID player) {
return memory.computeIfAbsent(serverStorage.resolve("echests").resolve(player.toString()), EnderChestMemory::new);
@Override
public final int getSize() {
return this.size;
}
}
}
@@ -15,22 +15,20 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.process;
package baritone.behavior;
import baritone.Baritone;
import baritone.api.behavior.IMineBehavior;
import baritone.api.event.events.TickEvent;
import baritone.api.pathing.goals.*;
import baritone.api.process.IMineProcess;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.api.utils.IPlayerContext;
import baritone.api.utils.RotationUtils;
import baritone.cache.CachedChunk;
import baritone.cache.ChunkPacker;
import baritone.cache.WorldProvider;
import baritone.cache.WorldScanner;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.BaritoneProcessHelper;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
@@ -39,6 +37,7 @@ import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.EmptyChunk;
import java.util.*;
import java.util.stream.Collectors;
@@ -48,136 +47,119 @@ import java.util.stream.Collectors;
*
* @author leijurv
*/
public final class MineProcess extends BaritoneProcessHelper implements IMineProcess {
private static final int ORE_LOCATIONS_COUNT = 64;
public final class MineBehavior extends Behavior implements IMineBehavior, Helper {
public static final int ORE_LOCATIONS_COUNT = 64;
private List<Block> mining;
private List<BlockPos> knownOreLocations;
private BlockPos branchPoint;
private GoalRunAway branchPointRunaway;
private int desiredQuantity;
private int tickCount;
public MineProcess(Baritone baritone) {
super(baritone, 0);
public MineBehavior(Baritone baritone) {
super(baritone);
}
@Override
public boolean isActive() {
return mining != null;
}
@Override
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
public void onTick(TickEvent event) {
if (event.getType() == TickEvent.Type.OUT) {
cancel();
return;
}
if (mining == null) {
return;
}
if (desiredQuantity > 0) {
Item item = mining.get(0).getItemDropped(mining.get(0).getDefaultState(), new Random(), 0);
int curr = ctx.player().inventory.mainInventory.stream().filter(stack -> item.equals(stack.getItem())).mapToInt(ItemStack::getCount).sum();
int curr = player().inventory.mainInventory.stream().filter(stack -> item.equals(stack.getItem())).mapToInt(ItemStack::getCount).sum();
System.out.println("Currently have " + curr + " " + item);
if (curr >= desiredQuantity) {
logDirect("Have " + curr + " " + item.getItemStackDisplayName(new ItemStack(item, 1)));
cancel();
return null;
return;
}
}
if (calcFailed) {
logDirect("Unable to find any path to " + mining + ", canceling Mine");
cancel();
return null;
}
int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get();
if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain
List<BlockPos> curr = new ArrayList<>(knownOreLocations);
CalculationContext context = new CalculationContext(baritone, true);
Baritone.getExecutor().execute(() -> rescan(curr, context));
if (mineGoalUpdateInterval != 0 && event.getCount() % mineGoalUpdateInterval == 0) {
Baritone.INSTANCE.getExecutor().execute(this::rescan);
}
if (Baritone.settings().legitMine.get()) {
addNearby();
}
Goal goal = updateGoal();
if (goal == null) {
// none in range
// maybe say something in chat? (ahem impact)
cancel();
return null;
updateGoal();
baritone.getPathingBehavior().revalidateGoal();
}
private void updateGoal() {
if (mining == null || world() == null || player() == null) {
return;
}
return new PathingCommand(goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH);
}
@Override
public void onLostControl() {
mine(0, (Block[]) null);
}
@Override
public String displayName() {
return "Mine " + mining;
}
private Goal updateGoal() {
List<BlockPos> locs = knownOreLocations;
if (!locs.isEmpty()) {
List<BlockPos> locs2 = prune(new CalculationContext(baritone), new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT);
List<BlockPos> locs2 = prune(new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT, world());
// can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final
Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(ctx, loc, locs2)).toArray(Goal[]::new));
baritone.getPathingBehavior().setGoalAndPath(new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new)));
knownOreLocations = locs2;
return goal;
return;
}
// we don't know any ore locations at the moment
if (!Baritone.settings().legitMine.get()) {
return null;
return;
}
// only in non-Xray mode (aka legit mode) do we do this
int y = Baritone.settings().legitMineYLevel.get();
if (branchPoint == null) {
/*if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) {
int y = Baritone.settings().legitMineYLevel.get();
if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) {
// cool, path is over and we are at desired y
branchPoint = playerFeet();
branchPointRunaway = null;
} else {
return new GoalYLevel(y);
}*/
branchPoint = ctx.playerFeet();
baritone.getPathingBehavior().setGoalAndPath(new GoalYLevel(y));
return;
}
}
// TODO shaft mode, mine 1x1 shafts to either side
// TODO also, see if the GoalRunAway with maintain Y at 11 works even from the surface
if (branchPointRunaway == null) {
branchPointRunaway = new GoalRunAway(1, y, branchPoint) {
@Override
public boolean isInGoal(int x, int y, int z) {
return false;
}
};
if (playerFeet().equals(branchPoint)) {
// TODO mine 1x1 shafts to either side
branchPoint = branchPoint.north(10);
}
return branchPointRunaway;
baritone.getPathingBehavior().setGoalAndPath(new GoalBlock(branchPoint));
}
private void rescan(List<BlockPos> already, CalculationContext context) {
if (mining == null) {
private void rescan() {
if (mining == null || world() == null || player() == null) {
return;
}
if (Baritone.settings().legitMine.get()) {
return;
}
List<BlockPos> locs = searchWorld(context, mining, ORE_LOCATIONS_COUNT, already);
locs.addAll(droppedItemsScan(mining, ctx.world()));
List<BlockPos> locs = searchWorld(mining, ORE_LOCATIONS_COUNT, world());
locs.addAll(droppedItemsScan(mining, world()));
if (locs.isEmpty()) {
logDebug("No locations for " + mining + " known, cancelling");
cancel();
mine(0, (String[]) null);
return;
}
knownOreLocations = locs;
}
private static Goal coalesce(IPlayerContext ctx, BlockPos loc, List<BlockPos> locs) {
private static Goal coalesce(BlockPos loc, List<BlockPos> locs) {
if (!Baritone.settings().forceInternalMining.get()) {
return new GoalTwoBlocks(loc);
}
// Here, BlockStateInterface is used because the position may be in a cached chunk (the targeted block is one that is kept track of)
boolean upwardGoal = locs.contains(loc.up()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(ctx, loc.up()) == Blocks.AIR);
boolean downwardGoal = locs.contains(loc.down()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(ctx, loc.down()) == Blocks.AIR);
return upwardGoal == downwardGoal ? new GoalTwoBlocks(loc) : upwardGoal ? new GoalBlock(loc) : new GoalBlock(loc.down());
boolean upwardGoal = locs.contains(loc.up()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(loc.up()) == Blocks.AIR);
boolean downwardGoal = locs.contains(loc.down()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(loc.up()) == Blocks.AIR);
if (upwardGoal) {
if (downwardGoal) {
return new GoalTwoBlocks(loc);
} else {
return new GoalBlock(loc);
}
} else {
if (downwardGoal) {
return new GoalBlock(loc.down());
} else {
return new GoalTwoBlocks(loc);
}
}
}
public static List<BlockPos> droppedItemsScan(List<Block> mining, World world) {
@@ -196,20 +178,20 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
if (entity instanceof EntityItem) {
EntityItem ei = (EntityItem) entity;
if (searchingFor.contains(ei.getItem().getItem())) {
ret.add(new BlockPos(entity));
ret.add(entity.getPosition());
}
}
}
return ret;
}
public static List<BlockPos> searchWorld(CalculationContext ctx, List<Block> mining, int max, List<BlockPos> alreadyKnown) {
public static List<BlockPos> searchWorld(List<Block> mining, int max, World world) {
List<BlockPos> locs = new ArrayList<>();
List<Block> uninteresting = new ArrayList<>();
//long b = System.currentTimeMillis();
for (Block m : mining) {
if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(m)) {
locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 2));
locs.addAll(WorldProvider.INSTANCE.getCurrentWorld().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, 1));
} else {
uninteresting.add(m);
}
@@ -220,47 +202,40 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
}
if (!uninteresting.isEmpty()) {
//long before = System.currentTimeMillis();
locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), uninteresting, max, 10, 26));
locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(uninteresting, max, 10, 26));
//System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms");
}
locs.addAll(alreadyKnown);
return prune(ctx, locs, mining, max);
return prune(locs, mining, max, world);
}
public void addNearby() {
knownOreLocations.addAll(droppedItemsScan(mining, ctx.world()));
BlockPos playerFeet = ctx.playerFeet();
BlockStateInterface bsi = new BlockStateInterface(ctx);
int searchDist = 10;
double fakedBlockReachDistance = 20; // at least 10 * sqrt(3) with some extra space to account for positioning within the block
BlockPos playerFeet = playerFeet();
int searchDist = 4;//why four? idk
for (int x = playerFeet.getX() - searchDist; x <= playerFeet.getX() + searchDist; x++) {
for (int y = playerFeet.getY() - searchDist; y <= playerFeet.getY() + searchDist; y++) {
for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) {
// crucial to only add blocks we can see because otherwise this
// 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()) {
knownOreLocations.add(new BlockPos(x, y, z));
BlockPos pos = new BlockPos(x, y, z);
if (mining.contains(BlockStateInterface.getBlock(pos)) && RotationUtils.reachable(player(), pos).isPresent()) {//crucial to only add blocks we can see because otherwise this is an x-ray and it'll get caught
knownOreLocations.add(pos);
}
}
}
}
knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, mining, ORE_LOCATIONS_COUNT);
knownOreLocations = prune(knownOreLocations, mining, ORE_LOCATIONS_COUNT, world());
}
public static List<BlockPos> prune(CalculationContext ctx, List<BlockPos> locs2, List<Block> mining, int max) {
List<BlockPos> dropped = droppedItemsScan(mining, ctx.world);
public static List<BlockPos> prune(List<BlockPos> locs2, List<Block> mining, int max, World world) {
List<BlockPos> dropped = droppedItemsScan(mining, world);
List<BlockPos> locs = locs2
.stream()
.distinct()
// 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 -> world.getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock()) || dropped.contains(pos))
// remove any that are implausible to mine (encased in bedrock, or touching lava)
.filter(pos -> MineProcess.plausibleToBreak(ctx.bsi, pos))
.filter(MineBehavior::plausibleToBreak)
.sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().playerFeet()::distanceSq))
.sorted(Comparator.comparingDouble(Helper.HELPER.playerFeet()::distanceSq))
.collect(Collectors.toList());
if (locs.size() > max) {
@@ -269,18 +244,22 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
return locs;
}
public static boolean plausibleToBreak(BlockStateInterface bsi, BlockPos pos) {
if (MovementHelper.avoidBreaking(bsi, pos.getX(), pos.getY(), pos.getZ(), bsi.get0(pos))) {
public static boolean plausibleToBreak(BlockPos pos) {
if (MovementHelper.avoidBreaking(pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(pos))) {
return false;
}
// bedrock above and below makes it implausible, otherwise we're good
return !(bsi.get0(pos.up()).getBlock() == Blocks.BEDROCK && bsi.get0(pos.down()).getBlock() == Blocks.BEDROCK);
return !(BlockStateInterface.getBlock(pos.up()) == Blocks.BEDROCK && BlockStateInterface.getBlock(pos.down()) == Blocks.BEDROCK);
}
@Override
public void mineByName(int quantity, String... blocks) {
mine(quantity, blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlock).toArray(Block[]::new));
public void mine(int quantity, String... blocks) {
this.mining = blocks == null || blocks.length == 0 ? null : Arrays.stream(blocks).map(ChunkPacker::stringToBlock).collect(Collectors.toList());
this.desiredQuantity = quantity;
this.knownOreLocations = new ArrayList<>();
this.branchPoint = null;
rescan();
updateGoal();
}
@Override
@@ -289,9 +268,13 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
this.desiredQuantity = quantity;
this.knownOreLocations = new ArrayList<>();
this.branchPoint = null;
this.branchPointRunaway = null;
if (mining != null) {
rescan(new ArrayList<>(), new CalculationContext(baritone));
}
rescan();
updateGoal();
}
@Override
public void cancel() {
mine(0, (String[]) null);
baritone.getPathingBehavior().cancel();
}
}
@@ -24,26 +24,26 @@ import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.RenderEvent;
import baritone.api.event.events.TickEvent;
import baritone.api.pathing.calc.IPath;
import baritone.api.pathing.calc.IPathFinder;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalXZ;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.PathCalculationResult;
import baritone.api.utils.interfaces.IGoalRenderPos;
import baritone.pathing.calc.AStarPathFinder;
import baritone.pathing.calc.AbstractNodeCostSearch;
import baritone.pathing.calc.CutoffPath;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.MovementHelper;
import baritone.pathing.path.CutoffPath;
import baritone.pathing.path.PathExecutor;
import baritone.utils.BlockBreakHelper;
import baritone.utils.Helper;
import baritone.utils.PathRenderer;
import baritone.utils.pathing.Favoring;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.EmptyChunk;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.LinkedBlockingQueue;
@@ -54,12 +54,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
private Goal goal;
private boolean safeToCancel;
private boolean pauseRequestedLastTick;
private boolean cancelRequested;
private boolean calcFailedLastTick;
private volatile AbstractNodeCostSearch inProgress;
private volatile boolean isPathCalcInProgress;
private final Object pathCalcLock = new Object();
private final Object pathPlanLock = new Object();
@@ -79,9 +74,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
private void dispatchEvents() {
ArrayList<PathEvent> curr = new ArrayList<>();
toDispatch.drainTo(curr);
calcFailedLastTick = curr.contains(PathEvent.CALC_FAILED);
for (PathEvent event : curr) {
baritone.getGameEventHandler().onPathEvent(event);
Baritone.INSTANCE.getGameEventHandler().onPathEvent(event);
}
}
@@ -89,40 +83,28 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
public void onTick(TickEvent event) {
dispatchEvents();
if (event.getType() == TickEvent.Type.OUT) {
secretInternalSegmentCancel();
baritone.getPathingControlManager().cancelEverything();
cancel();
return;
}
baritone.getPathingControlManager().preTick();
tickPath();
dispatchEvents();
}
private void tickPath() {
if (pauseRequestedLastTick && safeToCancel) {
pauseRequestedLastTick = false;
baritone.getInputOverrideHandler().clearAllKeys();
baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock();
return;
}
if (cancelRequested) {
cancelRequested = false;
baritone.getInputOverrideHandler().clearAllKeys();
}
if (current == null) {
return;
}
safeToCancel = current.onTick();
boolean safe = current.onTick();
synchronized (pathPlanLock) {
if (current.failed() || current.finished()) {
current = null;
if (goal == null || goal.isInGoal(ctx.playerFeet())) {
if (goal == null || goal.isInGoal(playerFeet())) {
logDebug("All done. At " + goal);
queuePathEvent(PathEvent.AT_GOAL);
next = null;
return;
}
if (next != null && !next.getPath().positions().contains(ctx.playerFeet())) {
if (next != null && !next.getPath().positions().contains(playerFeet())) {
// 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");
// for example if we had a nicely planned ahead path that starts where current ends
@@ -143,18 +125,18 @@ 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
synchronized (pathCalcLock) {
if (inProgress != null) {
if (isPathCalcInProgress) {
queuePathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING);
// if we aren't calculating right now
return;
}
queuePathEvent(PathEvent.CALC_STARTED);
findPathInNewThread(pathStart(), true);
findPathInNewThread(pathStart(), true, Optional.empty());
}
return;
}
// at this point, we know current is in progress
if (safeToCancel && next != null && next.snipsnapifpossible()) {
if (safe && next != null && player().onGround && next.snipsnapifpossible()) {
// a movement just ended; jump directly onto the next path
logDebug("Splicing into planned next path early...");
queuePathEvent(PathEvent.SPLICING_ONTO_NEXT_EARLY);
@@ -163,12 +145,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
current.onTick();
return;
}
current = current.trySplice(next);
if (next != null && current.getPath().getDest().equals(next.getPath().getDest())) {
next = null;
}
synchronized (pathCalcLock) {
if (inProgress != null) {
if (isPathCalcInProgress) {
// if we aren't calculating right now
return;
}
@@ -184,7 +162,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
// and this path has 5 seconds or less left
logDebug("Path almost over. Planning ahead...");
queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED);
findPathInNewThread(current.getPath().getDest(), false);
findPathInNewThread(current.getPath().getDest(), false, Optional.of(current.getPath()));
}
}
}
@@ -215,13 +193,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
return Optional.of(current.getPath().ticksRemainingFrom(current.getPosition()));
}
public void secretInternalSetGoal(Goal goal) {
@Override
public void setGoal(Goal goal) {
this.goal = goal;
}
public boolean secretInternalSetGoalAndPath(Goal goal) {
secretInternalSetGoal(goal);
return secretInternalPath();
public boolean setGoalAndPath(Goal goal) {
setGoal(goal);
return path();
}
@Override
@@ -240,8 +219,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
}
@Override
public Optional<AbstractNodeCostSearch> getInProgress() {
return Optional.ofNullable(inProgress);
public Optional<IPathFinder> getPathFinder() {
return Optional.ofNullable(AbstractNodeCostSearch.currentlyRunning());
}
@Override
@@ -249,65 +228,18 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
return this.current != null;
}
public boolean isSafeToCancel() {
return current == null || safeToCancel;
}
public void requestPause() {
pauseRequestedLastTick = true;
}
public boolean cancelSegmentIfSafe() {
if (isSafeToCancel()) {
secretInternalSegmentCancel();
return true;
}
return false;
}
@Override
public boolean cancelEverything() {
boolean doIt = isSafeToCancel();
if (doIt) {
secretInternalSegmentCancel();
}
baritone.getPathingControlManager().cancelEverything();
return doIt;
}
public boolean calcFailedLastTick() { // NOT exposed on public api
return calcFailedLastTick;
}
public void softCancelIfSafe() {
synchronized (pathPlanLock) {
if (!isSafeToCancel()) {
return;
}
current = null;
next = null;
}
cancelRequested = true;
getInProgress().ifPresent(AbstractNodeCostSearch::cancel); // only cancel ours
// do everything BUT clear keys
}
// just cancel the current path
public void secretInternalSegmentCancel() {
public void cancel() {
queuePathEvent(PathEvent.CANCELED);
synchronized (pathPlanLock) {
current = null;
next = null;
}
baritone.getInputOverrideHandler().clearAllKeys();
getInProgress().ifPresent(AbstractNodeCostSearch::cancel);
baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock();
current = null;
next = null;
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(AbstractNodeCostSearch::cancel);
BlockBreakHelper.stopBreakingBlock();
}
public void forceCancel() { // NOT exposed on public api
cancelEverything();
secretInternalSegmentCancel();
inProgress = null;
isPathCalcInProgress = false;
}
/**
@@ -315,11 +247,12 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
*
* @return true if this call started path calculation, false if it was already calculating or executing a path
*/
public boolean secretInternalPath() {
@Override
public boolean path() {
if (goal == null) {
return false;
}
if (goal.isInGoal(ctx.playerFeet())) {
if (goal.isInGoal(playerFeet())) {
return false;
}
synchronized (pathPlanLock) {
@@ -327,33 +260,27 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
return false;
}
synchronized (pathCalcLock) {
if (inProgress != null) {
if (isPathCalcInProgress) {
return false;
}
queuePathEvent(PathEvent.CALC_STARTED);
findPathInNewThread(pathStart(), true);
findPathInNewThread(pathStart(), true, Optional.empty());
return true;
}
}
}
public void secretCursedFunctionDoNotCall(IPath path) {
synchronized (pathPlanLock) {
current = new PathExecutor(this, path);
}
}
/**
* See issue #209
*
* @return The starting {@link BlockPos} for a new path
*/
public BetterBlockPos pathStart() { // TODO move to a helper or util class
BetterBlockPos feet = ctx.playerFeet();
if (!MovementHelper.canWalkOn(ctx, feet.down())) {
if (ctx.player().onGround) {
double playerX = ctx.player().posX;
double playerZ = ctx.player().posZ;
public BlockPos pathStart() {
BetterBlockPos feet = playerFeet();
if (!MovementHelper.canWalkOn(feet.down())) {
if (player().onGround) {
double playerX = player().posX;
double playerZ = player().posZ;
ArrayList<BetterBlockPos> closest = new ArrayList<>();
for (int dx = -1; dx <= 1; dx++) {
for (int dz = -1; dz <= 1; dz++) {
@@ -369,7 +296,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
// can't possibly be sneaking off of this one, we're too far away
continue;
}
if (MovementHelper.canWalkOn(ctx, possibleSupport.down()) && MovementHelper.canWalkThrough(ctx, possibleSupport) && MovementHelper.canWalkThrough(ctx, possibleSupport.up())) {
if (MovementHelper.canWalkOn(possibleSupport.down()) && MovementHelper.canWalkThrough(possibleSupport) && MovementHelper.canWalkThrough(possibleSupport.up())) {
// this is plausible
logDebug("Faking path start assuming player is standing off the edge of a block");
return possibleSupport;
@@ -379,7 +306,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
} else {
// !onGround
// we're in the middle of a jump
if (MovementHelper.canWalkOn(ctx, feet.down().down())) {
if (MovementHelper.canWalkOn(feet.down().down())) {
logDebug("Faking path start assuming player is midair and falling");
return feet.down();
}
@@ -394,46 +321,23 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
* @param start
* @param talkAboutIt
*/
private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt) {
// this must be called with synchronization on pathCalcLock!
// actually, we can check this, muahaha
if (!Thread.holdsLock(pathCalcLock)) {
throw new IllegalStateException("Must be called with synchronization on pathCalcLock");
// why do it this way? it's already indented so much that putting the whole thing in a synchronized(pathCalcLock) was just too much lol
private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt, final Optional<IPath> previous) {
synchronized (pathCalcLock) {
if (isPathCalcInProgress) {
throw new IllegalStateException("Already doing it");
}
isPathCalcInProgress = true;
}
if (inProgress != null) {
throw new IllegalStateException("Already doing it"); // should have been checked by caller
}
Goal goal = this.goal;
if (goal == null) {
logDebug("no goal"); // TODO should this be an exception too? definitely should be checked by caller
return;
}
long primaryTimeout;
long failureTimeout;
if (current == null) {
primaryTimeout = Baritone.settings().primaryTimeoutMS.get();
failureTimeout = Baritone.settings().failureTimeoutMS.get();
} else {
primaryTimeout = Baritone.settings().planAheadPrimaryTimeoutMS.get();
failureTimeout = Baritone.settings().planAheadFailureTimeoutMS.get();
}
CalculationContext context = new CalculationContext(baritone, true); // not safe to create on the other thread, it looks up a lot of stuff in minecraft
AbstractNodeCostSearch pathfinder = createPathfinder(start, goal, current == null ? null : current.getPath(), context);
if (!Objects.equals(pathfinder.getGoal(), goal)) { // will return the exact same object if simplification didn't happen
logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance");
}
inProgress = pathfinder;
Baritone.getExecutor().execute(() -> {
CalculationContext context = new CalculationContext(); // not safe to create on the other thread, it looks up a lot of stuff in minecraft
Baritone.INSTANCE.getExecutor().execute(() -> {
if (talkAboutIt) {
logDebug("Starting to search for path from " + start + " to " + goal);
}
PathCalculationResult calcResult = pathfinder.calculate(primaryTimeout, failureTimeout);
Optional<IPath> path = calcResult.getPath();
Optional<IPath> path = findPath(start, previous, context);
if (Baritone.settings().cutoffAtLoadBoundary.get()) {
path = path.map(p -> {
IPath result = p.cutoffAtLoadedChunks(context.bsi);
IPath result = p.cutoffAtLoadedChunks();
if (result instanceof CutoffPath) {
logDebug("Cutting off path at edge of loaded chunks");
@@ -454,7 +358,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
}
return result;
}).map(p -> new PathExecutor(this, p));
}).map(PathExecutor::new);
synchronized (pathPlanLock) {
if (current == null) {
@@ -462,10 +366,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
queuePathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING);
current = executor.get();
} else {
if (calcResult.getType() != PathCalculationResult.Type.CANCELLATION && calcResult.getType() != PathCalculationResult.Type.EXCEPTION) {
// don't dispatch CALC_FAILED on cancellation
queuePathEvent(PathEvent.CALC_FAILED);
}
queuePathEvent(PathEvent.CALC_FAILED);
}
} else {
if (next == null) {
@@ -476,39 +377,91 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
queuePathEvent(PathEvent.NEXT_CALC_FAILED);
}
} else {
//throw new IllegalStateException("I have no idea what to do with this path");
// no point in throwing an exception here, and it gets it stuck with inProgress being not null
logDirect("Warning: PathingBehaivor illegal state! Discarding invalid path!");
throw new IllegalStateException("I have no idea what to do with this path");
}
}
if (talkAboutIt && current != null && current.getPath() != null) {
if (goal == null || goal.isInGoal(current.getPath().getDest())) {
logDebug("Finished finding a path from " + start + " to " + goal + ". " + current.getPath().getNumNodesConsidered() + " nodes considered");
} else {
logDebug("Found path segment from " + start + " towards " + goal + ". " + current.getPath().getNumNodesConsidered() + " nodes considered");
}
}
synchronized (pathCalcLock) {
inProgress = null;
}
if (talkAboutIt && current != null && current.getPath() != null) {
if (goal == null || goal.isInGoal(current.getPath().getDest())) {
logDebug("Finished finding a path from " + start + " to " + goal + ". " + current.getPath().getNumNodesConsidered() + " nodes considered");
} else {
logDebug("Found path segment from " + start + " towards " + goal + ". " + current.getPath().getNumNodesConsidered() + " nodes considered");
}
}
synchronized (pathCalcLock) {
isPathCalcInProgress = false;
}
});
}
public static AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, IPath previous, CalculationContext context) {
Goal transformed = goal;
/**
* Actually do the pathing
*
* @param start
* @return
*/
private Optional<IPath> findPath(BlockPos start, Optional<IPath> previous, CalculationContext context) {
Goal goal = this.goal;
if (goal == null) {
logDebug("no goal");
return Optional.empty();
}
if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) {
BlockPos pos = ((IGoalRenderPos) goal).getGoalPos();
if (!context.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ())) {
transformed = new GoalXZ(pos.getX(), pos.getZ());
if (world().getChunk(pos) instanceof EmptyChunk) {
logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance");
goal = new GoalXZ(pos.getX(), pos.getZ());
}
}
long timeout;
if (current == null) {
timeout = Baritone.settings().pathTimeoutMS.<Long>get();
} else {
timeout = Baritone.settings().planAheadTimeoutMS.<Long>get();
}
Optional<LongOpenHashSet> favoredPositions = Optional.empty();
if (Baritone.settings().backtrackCostFavoringCoefficient.get() != 1D && previous.isPresent()) {
LongOpenHashSet tmp = new LongOpenHashSet();
previous.get().positions().forEach(pos -> tmp.add(BetterBlockPos.longHash(pos)));
favoredPositions = Optional.of(tmp);
}
try {
IPathFinder pf = new AStarPathFinder(start.getX(), start.getY(), start.getZ(), goal, favoredPositions, context);
return pf.calculate(timeout);
} catch (Exception e) {
logDebug("Pathing exception: " + e);
e.printStackTrace();
return Optional.empty();
}
}
public void revalidateGoal() {
if (!Baritone.settings().cancelOnGoalInvalidation.get()) {
return;
}
synchronized (pathPlanLock) {
if (current == null || goal == null) {
return;
}
Goal intended = current.getPath().getGoal();
BlockPos end = current.getPath().getDest();
if (intended.isInGoal(end) && !goal.isInGoal(end)) {
// this path used to end in the goal
// but the goal has changed, so there's no reason to continue...
cancel();
}
}
Favoring favoring = new Favoring(context.getBaritone().getPlayerContext(), previous);
return new AStarPathFinder(start.getX(), start.getY(), start.getZ(), transformed, favoring, context);
}
@Override
public void onRenderPass(RenderEvent event) {
PathRenderer.render(event, this);
}
@Override
public void onDisable() {
Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys();
}
}
+9 -6
View File
@@ -17,6 +17,8 @@
package baritone.cache;
import baritone.api.cache.IBlockTypeAccess;
import baritone.utils.Helper;
import baritone.utils.pathing.PathingBlockType;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
@@ -27,15 +29,15 @@ import java.util.*;
/**
* @author Brady
* @since 8/3/2018
* @since 8/3/2018 1:04 AM
*/
public final class CachedChunk {
public final class CachedChunk implements IBlockTypeAccess, Helper {
public static final Set<Block> BLOCKS_TO_KEEP_TRACK_OF;
static {
HashSet<Block> temp = new HashSet<>();
//temp.add(Blocks.DIAMOND_ORE);
temp.add(Blocks.DIAMOND_ORE);
temp.add(Blocks.DIAMOND_BLOCK);
//temp.add(Blocks.COAL_ORE);
temp.add(Blocks.COAL_BLOCK);
@@ -141,7 +143,8 @@ public final class CachedChunk {
calculateHeightMap();
}
public final IBlockState getBlock(int x, int y, int z, int dimension) {
@Override
public final IBlockState getBlock(int x, int y, int z) {
int internalPos = z << 4 | x;
if (heightMap[internalPos] == y) {
// we have this exact block, it's a surface block
@@ -152,10 +155,10 @@ public final class CachedChunk {
return overview[internalPos];
}
PathingBlockType type = getType(x, y, z);
if (type == PathingBlockType.SOLID && y == 127 && dimension == -1) {
if (type == PathingBlockType.SOLID && y == 127 && mc.player.dimension == -1) {
return Blocks.BEDROCK.getDefaultState();
}
return ChunkPacker.pathingTypeToBlock(type, dimension);
return ChunkPacker.pathingTypeToBlock(type);
}
private PathingBlockType getType(int x, int y, int z) {
+3 -6
View File
@@ -32,7 +32,7 @@ import java.util.zip.GZIPOutputStream;
/**
* @author Brady
* @since 8/3/2018
* @since 8/3/2018 9:35 PM
*/
public final class CachedRegion implements ICachedRegion {
@@ -59,25 +59,22 @@ public final class CachedRegion implements ICachedRegion {
*/
private final int z;
private final int dimension;
/**
* Has this region been modified since its most recent load or save
*/
private boolean hasUnsavedChanges;
CachedRegion(int x, int z, int dimension) {
CachedRegion(int x, int z) {
this.x = x;
this.z = z;
this.hasUnsavedChanges = false;
this.dimension = dimension;
}
@Override
public final IBlockState getBlock(int x, int y, int z) {
CachedChunk chunk = chunks[x >> 4][z >> 4];
if (chunk != null) {
return chunk.getBlock(x & 15, y, z & 15, dimension);
return chunk.getBlock(x & 15, y, z & 15);
}
return null;
}
+16 -31
View File
@@ -18,10 +18,7 @@
package baritone.cache;
import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.cache.ICachedWorld;
import baritone.api.cache.IWorldData;
import baritone.utils.Helper;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
@@ -38,7 +35,7 @@ import java.util.concurrent.LinkedBlockingQueue;
/**
* @author Brady
* @since 8/4/2018
* @since 8/4/2018 12:02 AM
*/
public final class CachedWorld implements ICachedWorld, Helper {
@@ -59,9 +56,7 @@ public final class CachedWorld implements ICachedWorld, Helper {
private final LinkedBlockingQueue<Chunk> toPack = new LinkedBlockingQueue<>();
private final int dimension;
CachedWorld(Path directory, int dimension) {
CachedWorld(Path directory) {
if (!Files.exists(directory)) {
try {
Files.createDirectories(directory);
@@ -69,12 +64,11 @@ public final class CachedWorld implements ICachedWorld, Helper {
}
}
this.directory = directory.toString();
this.dimension = dimension;
System.out.println("Cached world directory: " + directory);
// Insert an invalid region element
cachedRegions.put(0, null);
Baritone.getExecutor().execute(new PackerThread());
Baritone.getExecutor().execute(() -> {
Baritone.INSTANCE.getExecutor().execute(new PackerThread());
Baritone.INSTANCE.getExecutor().execute(() -> {
try {
Thread.sleep(30000);
while (true) {
@@ -109,10 +103,10 @@ public final class CachedWorld implements ICachedWorld, Helper {
}
@Override
public final LinkedList<BlockPos> getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq) {
public final LinkedList<BlockPos> getLocationsOf(String block, int maximum, int maxRegionDistanceSq) {
LinkedList<BlockPos> res = new LinkedList<>();
int centerRegionX = centerX >> 9;
int centerRegionZ = centerZ >> 9;
int playerRegionX = playerFeet().getX() >> 9;
int playerRegionZ = playerFeet().getZ() >> 9;
int searchRadius = 0;
while (searchRadius <= maxRegionDistanceSq) {
@@ -122,8 +116,8 @@ public final class CachedWorld implements ICachedWorld, Helper {
if (distance != searchRadius) {
continue;
}
int regionX = xoff + centerRegionX;
int regionZ = zoff + centerRegionZ;
int regionX = xoff + playerRegionX;
int regionZ = zoff + playerRegionZ;
CachedRegion region = getOrCreateRegion(regionX, regionZ);
if (region != null) {
// TODO: 100% verify if this or addAll is faster.
@@ -171,16 +165,13 @@ public final class CachedWorld implements ICachedWorld, Helper {
* Delete regions that are too far from the player
*/
private synchronized void prune() {
if (!Baritone.settings().pruneRegionsFromRAM.get()) {
return;
}
BlockPos pruneCenter = guessPosition();
for (CachedRegion region : allRegions()) {
if (region == null) {
continue;
}
int distX = (region.getX() << 9 + 256) - pruneCenter.getX();
int distZ = (region.getZ() << 9 + 256) - pruneCenter.getZ();
int distX = (region.getX() * 512 + 256) - pruneCenter.getX();
int distZ = (region.getZ() * 512 + 256) - pruneCenter.getZ();
double dist = Math.sqrt(distX * distX + distZ * distZ);
if (dist > 1024) {
logDebug("Deleting cached region " + region.getX() + "," + region.getZ() + " from ram");
@@ -193,11 +184,9 @@ public final class CachedWorld implements ICachedWorld, Helper {
* If we are still in this world and dimension, return player feet, otherwise return most recently modified chunk
*/
private BlockPos guessPosition() {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
IWorldData data = ibaritone.getWorldProvider().getCurrentWorld();
if (data != null && data.getCachedWorld() == this) {
return ibaritone.getPlayerContext().playerFeet();
}
WorldData data = WorldProvider.INSTANCE.getCurrentWorld();
if (data != null && data.getCachedWorld() == this) {
return playerFeet();
}
CachedChunk mostRecentlyModified = null;
for (CachedRegion region : allRegions()) {
@@ -215,7 +204,7 @@ public final class CachedWorld implements ICachedWorld, Helper {
if (mostRecentlyModified == null) {
return new BlockPos(0, 0, 0);
}
return new BlockPos(mostRecentlyModified.x << 4 + 8, 0, mostRecentlyModified.z << 4 + 8);
return new BlockPos(mostRecentlyModified.x * 16 + 8, 0, mostRecentlyModified.z * 16 + 8);
}
private synchronized List<CachedRegion> allRegions() {
@@ -249,16 +238,12 @@ public final class CachedWorld implements ICachedWorld, Helper {
*/
private synchronized CachedRegion getOrCreateRegion(int regionX, int regionZ) {
return cachedRegions.computeIfAbsent(getRegionID(regionX, regionZ), id -> {
CachedRegion newRegion = new CachedRegion(regionX, regionZ, dimension);
CachedRegion newRegion = new CachedRegion(regionX, regionZ);
newRegion.load(this.directory);
return newRegion;
});
}
public void tryLoadFromDisk(int regionX, int regionZ) {
getOrCreateRegion(regionX, regionZ);
}
/**
* Returns the region ID based on the region coordinates. 0 will be
* returned if the specified region coordinates are out of bounds.
+9 -5
View File
@@ -18,6 +18,7 @@
package baritone.cache;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.Helper;
import baritone.utils.pathing.PathingBlockType;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDoublePlant;
@@ -35,9 +36,9 @@ import java.util.*;
/**
* @author Brady
* @since 8/3/2018
* @since 8/3/2018 1:09 AM
*/
public final class ChunkPacker {
public final class ChunkPacker implements Helper {
private static final Map<String, Block> resourceCache = new HashMap<>();
@@ -93,7 +94,10 @@ public final class ChunkPacker {
IBlockState[] blocks = new IBlockState[256];
for (int z = 0; z < 16; z++) {
https://www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html
// @formatter:off
https:
//www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html
// @formatter:on
for (int x = 0; x < 16; x++) {
for (int y = 255; y >= 0; y--) {
int index = CachedChunk.getPositionIndex(x, y, z);
@@ -143,7 +147,7 @@ public final class ChunkPacker {
return PathingBlockType.SOLID;
}
public static IBlockState pathingTypeToBlock(PathingBlockType type, int dimension) {
public static IBlockState pathingTypeToBlock(PathingBlockType type) {
switch (type) {
case AIR:
return Blocks.AIR.getDefaultState();
@@ -153,7 +157,7 @@ public final class ChunkPacker {
return Blocks.LAVA.getDefaultState();
case SOLID:
// Dimension solid types
switch (dimension) {
switch (mc.player.dimension) {
case -1:
return Blocks.NETHERRACK.getDefaultState();
case 0:
-176
View File
@@ -1,176 +0,0 @@
/*
* 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.cache;
import baritone.api.cache.IContainerMemory;
import baritone.api.cache.IRememberedInventory;
import baritone.api.utils.IPlayerContext;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.math.BlockPos;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
public class ContainerMemory implements IContainerMemory {
private final Path saveTo;
/**
* The current remembered inventories
*/
private final Map<BlockPos, RememberedInventory> inventories = new HashMap<>();
public ContainerMemory(Path saveTo) {
this.saveTo = saveTo;
try {
read(Files.readAllBytes(saveTo));
} catch (Exception ex) {
ex.printStackTrace();
inventories.clear();
}
}
private void read(byte[] bytes) throws IOException {
PacketBuffer in = new PacketBuffer(Unpooled.wrappedBuffer(bytes));
int chests = in.readInt();
for (int i = 0; i < chests; i++) {
int x = in.readInt();
int y = in.readInt();
int z = in.readInt();
RememberedInventory rem = new RememberedInventory();
rem.items.addAll(readItemStacks(in));
rem.size = rem.items.size();
rem.windowId = -1;
if (rem.items.isEmpty()) {
continue; // this only happens if the list has no elements, not if the list has elements that are all empty item stacks
}
inventories.put(new BlockPos(x, y, z), rem);
}
}
public synchronized void save() throws IOException {
ByteBuf buf = Unpooled.buffer(0, Integer.MAX_VALUE);
PacketBuffer out = new PacketBuffer(buf);
out.writeInt(inventories.size());
for (Map.Entry<BlockPos, RememberedInventory> entry : inventories.entrySet()) {
out = new PacketBuffer(out.writeInt(entry.getKey().getX()));
out = new PacketBuffer(out.writeInt(entry.getKey().getY()));
out = new PacketBuffer(out.writeInt(entry.getKey().getZ()));
out = writeItemStacks(entry.getValue().getContents(), out);
}
Files.write(saveTo, out.array());
}
public synchronized void setup(BlockPos pos, int windowId, int slotCount) {
RememberedInventory inventory = inventories.computeIfAbsent(pos, x -> new RememberedInventory());
inventory.windowId = windowId;
inventory.size = slotCount;
}
public synchronized Optional<RememberedInventory> getInventoryFromWindow(int windowId) {
return inventories.values().stream().filter(i -> i.windowId == windowId).findFirst();
}
@Override
public final synchronized RememberedInventory getInventoryByPos(BlockPos pos) {
return inventories.get(pos);
}
@Override
public final synchronized Map<BlockPos, IRememberedInventory> getRememberedInventories() {
// make a copy since this map is modified from the packet thread
return new HashMap<>(inventories);
}
public static List<ItemStack> readItemStacks(byte[] bytes) throws IOException {
PacketBuffer in = new PacketBuffer(Unpooled.wrappedBuffer(bytes));
return readItemStacks(in);
}
public static List<ItemStack> readItemStacks(PacketBuffer in) throws IOException {
int count = in.readInt();
List<ItemStack> result = new ArrayList<>();
for (int i = 0; i < count; i++) {
result.add(in.readItemStack());
}
return result;
}
public static byte[] writeItemStacks(List<ItemStack> write) {
ByteBuf buf = Unpooled.buffer(0, Integer.MAX_VALUE);
PacketBuffer out = new PacketBuffer(buf);
out = writeItemStacks(write, out);
return out.array();
}
public static PacketBuffer writeItemStacks(List<ItemStack> write, PacketBuffer out2) {
PacketBuffer out = out2; // avoid reassigning an argument LOL
out = new PacketBuffer(out.writeInt(write.size()));
for (ItemStack stack : write) {
out = out.writeItemStack(stack);
}
return out;
}
/**
* An inventory that we are aware of.
* <p>
* Associated with a {@link BlockPos} in {@link ContainerMemory#inventories}.
*/
public static class RememberedInventory implements IRememberedInventory {
/**
* The list of items in the inventory
*/
private final List<ItemStack> items;
/**
* The last known window ID of the inventory
*/
private int windowId;
/**
* The size of the inventory
*/
private int size;
private RememberedInventory() {
this.items = new ArrayList<>();
}
@Override
public final List<ItemStack> getContents() {
return Collections.unmodifiableList(this.items);
}
@Override
public final int getSize() {
return this.size;
}
public void updateFromOpenWindow(IPlayerContext ctx) {
items.clear();
items.addAll(ctx.player().openContainer.getInventory().subList(0, size));
}
}
}
+3 -3
View File
@@ -42,9 +42,9 @@ public class Waypoint implements IWaypoint {
* Constructor called when a Waypoint is read from disk, adds the creationTimestamp
* as a parameter so that it is reserved after a waypoint is wrote to the disk.
*
* @param name The waypoint name
* @param tag The waypoint tag
* @param location The waypoint location
* @param name The waypoint name
* @param tag The waypoint tag
* @param location The waypoint location
* @param creationTimestamp When the waypoint was created
*/
Waypoint(String name, Tag tag, BlockPos location, long creationTimestamp) {
@@ -32,7 +32,7 @@ import java.util.stream.Collectors;
*
* @author leijurv
*/
public class WaypointCollection implements IWaypointCollection {
public class Waypoints implements IWaypointCollection {
/**
* Magic value to detect invalid waypoint files
@@ -42,7 +42,7 @@ public class WaypointCollection implements IWaypointCollection {
private final Path directory;
private final Map<IWaypoint.Tag, Set<IWaypoint>> waypoints;
WaypointCollection(Path directory) {
Waypoints(Path directory) {
this.directory = directory;
if (!Files.exists(directory)) {
try {
+5 -25
View File
@@ -19,11 +19,9 @@ package baritone.cache;
import baritone.Baritone;
import baritone.api.cache.ICachedWorld;
import baritone.api.cache.IContainerMemory;
import baritone.api.cache.IWaypointCollection;
import baritone.api.cache.IWorldData;
import java.io.IOException;
import java.nio.file.Path;
/**
@@ -34,34 +32,21 @@ import java.nio.file.Path;
public class WorldData implements IWorldData {
public final CachedWorld cache;
private final WaypointCollection waypoints;
private final ContainerMemory containerMemory;
private final Waypoints waypoints;
//public final MapData map;
public final Path directory;
public final int dimension;
WorldData(Path directory, int dimension) {
WorldData(Path directory) {
this.directory = directory;
this.cache = new CachedWorld(directory.resolve("cache"), dimension);
this.waypoints = new WaypointCollection(directory.resolve("waypoints"));
this.containerMemory = new ContainerMemory(directory.resolve("containers"));
this.dimension = dimension;
this.cache = new CachedWorld(directory.resolve("cache"));
this.waypoints = new Waypoints(directory.resolve("waypoints"));
}
public void onClose() {
Baritone.getExecutor().execute(() -> {
Baritone.INSTANCE.getExecutor().execute(() -> {
System.out.println("Started saving the world in a new thread");
cache.save();
});
Baritone.getExecutor().execute(() -> {
System.out.println("Started saving saved containers in a new thread");
try {
containerMemory.save();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to save saved containers");
}
});
}
@Override
@@ -73,9 +58,4 @@ public class WorldData implements IWorldData {
public IWaypointCollection getWaypoints() {
return this.waypoints;
}
@Override
public IContainerMemory getContainerMemory() {
return this.containerMemory;
}
}
+17 -23
View File
@@ -22,6 +22,7 @@ import baritone.api.cache.IWorldProvider;
import baritone.utils.Helper;
import baritone.utils.accessor.IAnvilChunkLoader;
import baritone.utils.accessor.IChunkProviderServer;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.world.WorldServer;
@@ -36,11 +37,13 @@ import java.util.function.Consumer;
/**
* @author Brady
* @since 8/4/2018
* @since 8/4/2018 11:06 AM
*/
public class WorldProvider implements IWorldProvider, Helper {
public enum WorldProvider implements IWorldProvider, Helper {
private static final Map<Path, WorldData> worldCache = new HashMap<>(); // this is how the bots have the same cached world
INSTANCE;
private final Map<Path, WorldData> worldCache = new HashMap<>();
private WorldData currentWorld;
@@ -49,20 +52,13 @@ public class WorldProvider implements IWorldProvider, Helper {
return this.currentWorld;
}
/**
* Called when a new world is initialized to discover the
*
* @param dimension The ID of the world's dimension
*/
public final void initWorld(int dimension) {
public final void initWorld(WorldClient world) {
int dimensionID = world.provider.getDimensionType().getId();
File directory;
File readme;
IntegratedServer integratedServer = mc.getIntegratedServer();
// If there is an integrated server running (Aka Singleplayer) then do magic to find the world save file
if (integratedServer != null) {
WorldServer localServerWorld = integratedServer.getWorld(dimension);
WorldServer localServerWorld = integratedServer.getWorld(dimensionID);
IChunkProviderServer provider = (IChunkProviderServer) localServerWorld.getChunkProvider();
IAnvilChunkLoader loader = (IAnvilChunkLoader) provider.getChunkLoader();
directory = loader.getChunkSaveLocation();
@@ -75,29 +71,27 @@ public class WorldProvider implements IWorldProvider, Helper {
directory = new File(directory, "baritone");
readme = directory;
} else { // Otherwise, the server must be remote...
directory = new File(Baritone.getDir(), mc.getCurrentServerData().serverIP);
readme = Baritone.getDir();
}
} else {
//remote
directory = new File(Baritone.INSTANCE.getDir(), mc.getCurrentServerData().serverIP);
readme = Baritone.INSTANCE.getDir();
}
// lol wtf is this baritone folder in my minecraft save?
try (FileOutputStream out = new FileOutputStream(new File(readme, "readme.txt"))) {
// good thing we have a readme
out.write("https://github.com/cabaletta/baritone\n".getBytes());
} catch (IOException ignored) {}
// We will actually store the world data in a subfolder: "DIM<id>"
Path dir = new File(directory, "DIM" + dimension).toPath();
directory = new File(directory, "DIM" + dimensionID);
Path dir = directory.toPath();
if (!Files.exists(dir)) {
try {
Files.createDirectories(dir);
} catch (IOException ignored) {}
}
System.out.println("Baritone world data dir: " + dir);
synchronized (worldCache) {
this.currentWorld = worldCache.computeIfAbsent(dir, d -> new WorldData(d, dimension));
}
this.currentWorld = this.worldCache.computeIfAbsent(dir, WorldData::new);
}
public final void closeWorld() {
+36 -60
View File
@@ -18,40 +18,37 @@
package baritone.cache;
import baritone.api.cache.IWorldScanner;
import baritone.api.utils.IPlayerContext;
import baritone.utils.Helper;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.multiplayer.ChunkProviderClient;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.chunk.BlockStateContainer;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public enum WorldScanner implements IWorldScanner {
public enum WorldScanner implements IWorldScanner, Helper {
INSTANCE;
@Override
public List<BlockPos> scanChunkRadius(IPlayerContext ctx, List<Block> blocks, int max, int yLevelThreshold, int maxSearchRadius) {
public List<BlockPos> scanChunkRadius(List<Block> blocks, int max, int yLevelThreshold, int maxSearchRadius) {
if (blocks.contains(null)) {
throw new IllegalStateException("Invalid block name should have been caught earlier: " + blocks.toString());
}
ArrayList<BlockPos> res = new ArrayList<>();
LinkedList<BlockPos> res = new LinkedList<>();
if (blocks.isEmpty()) {
return res;
}
ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider();
ChunkProviderClient chunkProvider = world().getChunkProvider();
int maxSearchRadiusSq = maxSearchRadius * maxSearchRadius;
int playerChunkX = ctx.playerFeet().getX() >> 4;
int playerChunkZ = ctx.playerFeet().getZ() >> 4;
int playerY = ctx.playerFeet().getY();
int playerChunkX = playerFeet().getX() >> 4;
int playerChunkZ = playerFeet().getZ() >> 4;
int playerY = playerFeet().getY();
int searchRadiusSq = 0;
boolean foundWithinY = false;
@@ -72,7 +69,33 @@ public enum WorldScanner implements IWorldScanner {
continue;
}
allUnloaded = false;
scanChunkInto(chunkX << 4, chunkZ << 4, chunk, blocks, res, max, yLevelThreshold, playerY);
ExtendedBlockStorage[] chunkInternalStorageArray = chunk.getBlockStorageArray();
chunkX = chunkX << 4;
chunkZ = chunkZ << 4;
for (int y0 = 0; y0 < 16; y0++) {
ExtendedBlockStorage extendedblockstorage = chunkInternalStorageArray[y0];
if (extendedblockstorage == null) {
continue;
}
int yReal = y0 << 4;
BlockStateContainer bsc = extendedblockstorage.getData();
// the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x;
// for better cache locality, iterate in that order
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
IBlockState state = bsc.get(x, y, z);
if (blocks.contains(state.getBlock())) {
int yy = yReal | y;
res.add(new BlockPos(chunkX | x, yy, chunkZ | z));
if (Math.abs(yy - playerY) < yLevelThreshold) {
foundWithinY = true;
}
}
}
}
}
}
}
}
if ((allUnloaded && foundChunks)
@@ -84,51 +107,4 @@ public enum WorldScanner implements IWorldScanner {
searchRadiusSq++;
}
}
@Override
public List<BlockPos> scanChunk(IPlayerContext ctx, List<Block> blocks, ChunkPos pos, int max, int yLevelThreshold) {
if (blocks.isEmpty()) {
return Collections.emptyList();
}
ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider();
Chunk chunk = chunkProvider.getLoadedChunk(pos.x, pos.z);
int playerY = ctx.playerFeet().getY();
if (chunk == null || chunk.isEmpty()) {
return Collections.emptyList();
}
ArrayList<BlockPos> res = new ArrayList<>();
scanChunkInto(pos.x << 4, pos.z << 4, chunk, blocks, res, max, yLevelThreshold, playerY);
return res;
}
public void scanChunkInto(int chunkX, int chunkZ, Chunk chunk, List<Block> search, Collection<BlockPos> result, int max, int yLevelThreshold, int playerY) {
ExtendedBlockStorage[] chunkInternalStorageArray = chunk.getBlockStorageArray();
for (int y0 = 0; y0 < 16; y0++) {
ExtendedBlockStorage extendedblockstorage = chunkInternalStorageArray[y0];
if (extendedblockstorage == null) {
continue;
}
int yReal = y0 << 4;
BlockStateContainer bsc = extendedblockstorage.getData();
// the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x;
// for better cache locality, iterate in that order
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
IBlockState state = bsc.get(x, y, z);
if (search.contains(state.getBlock())) {
int yy = yReal | y;
result.add(new BlockPos(chunkX | x, yy, chunkZ | z));
if (result.size() >= max && Math.abs(yy - playerY) < yLevelThreshold) {
return;
}
}
}
}
}
}
}
}
@@ -20,43 +20,75 @@ package baritone.event;
import baritone.Baritone;
import baritone.api.event.events.*;
import baritone.api.event.events.type.EventState;
import baritone.api.event.listener.IEventBus;
import baritone.api.event.listener.IGameEventListener;
import baritone.api.utils.interfaces.Toggleable;
import baritone.cache.WorldProvider;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
import net.minecraft.world.World;
import baritone.utils.InputOverrideHandler;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.world.chunk.Chunk;
import org.lwjgl.input.Keyboard;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.ArrayList;
/**
* @author Brady
* @since 7/31/2018
* @since 7/31/2018 11:04 PM
*/
public final class GameEventHandler implements IEventBus, Helper {
public final class GameEventHandler implements IGameEventListener, Helper {
private final Baritone baritone;
private final List<IGameEventListener> listeners = new CopyOnWriteArrayList<>();
public GameEventHandler(Baritone baritone) {
this.baritone = baritone;
}
private final ArrayList<IGameEventListener> listeners = new ArrayList<>();
@Override
public final void onTick(TickEvent event) {
listeners.forEach(l -> l.onTick(event));
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onTick(event);
}
});
}
@Override
public final void onPlayerUpdate(PlayerUpdateEvent event) {
listeners.forEach(l -> l.onPlayerUpdate(event));
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onPlayerUpdate(event);
}
});
}
@Override
public final void onProcessKeyBinds() {
InputOverrideHandler inputHandler = Baritone.INSTANCE.getInputOverrideHandler();
// Simulate the key being held down this tick
for (InputOverrideHandler.Input input : InputOverrideHandler.Input.values()) {
KeyBinding keyBinding = input.getKeyBinding();
if (inputHandler.isInputForcedDown(keyBinding) && !keyBinding.isKeyDown()) {
int keyCode = keyBinding.getKeyCode();
if (keyCode < Keyboard.KEYBOARD_SIZE) {
KeyBinding.onTick(keyCode < 0 ? keyCode + 100 : keyCode);
}
}
}
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onProcessKeyBinds();
}
});
}
@Override
public final void onSendChatMessage(ChatEvent event) {
listeners.forEach(l -> l.onSendChatMessage(event));
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onSendChatMessage(event);
}
});
}
@Override
@@ -65,79 +97,118 @@ public final class GameEventHandler implements IEventBus, Helper {
ChunkEvent.Type type = event.getType();
boolean isPostPopulate = state == EventState.POST
&& (type == ChunkEvent.Type.POPULATE_FULL || type == ChunkEvent.Type.POPULATE_PARTIAL);
World world = baritone.getPlayerContext().world();
&& type == ChunkEvent.Type.POPULATE;
// Whenever the server sends us to another dimension, chunks are unloaded
// technically after the new world has been loaded, so we perform a check
// to make sure the chunk being unloaded is already loaded.
boolean isPreUnload = state == EventState.PRE
&& type == ChunkEvent.Type.UNLOAD
&& world.getChunkProvider().isChunkGeneratedAt(event.getX(), event.getZ());
&& mc.world.getChunkProvider().isChunkGeneratedAt(event.getX(), event.getZ());
if (isPostPopulate || isPreUnload) {
baritone.getWorldProvider().ifWorldLoaded(worldData -> {
Chunk chunk = world.getChunk(event.getX(), event.getZ());
worldData.getCachedWorld().queueForPacking(chunk);
WorldProvider.INSTANCE.ifWorldLoaded(world -> {
Chunk chunk = mc.world.getChunk(event.getX(), event.getZ());
world.getCachedWorld().queueForPacking(chunk);
});
}
listeners.forEach(l -> l.onChunkEvent(event));
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onChunkEvent(event);
}
});
}
@Override
public final void onRenderPass(RenderEvent event) {
listeners.forEach(l -> l.onRenderPass(event));
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onRenderPass(event);
}
});
}
@Override
public final void onWorldEvent(WorldEvent event) {
WorldProvider cache = baritone.getWorldProvider();
WorldProvider cache = WorldProvider.INSTANCE;
BlockStateInterface.clearCachedChunk();
if (event.getState() == EventState.POST) {
cache.closeWorld();
if (event.getWorld() != null) {
cache.initWorld(event.getWorld().provider.getDimensionType().getId());
cache.initWorld(event.getWorld());
}
}
listeners.forEach(l -> l.onWorldEvent(event));
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onWorldEvent(event);
}
});
}
@Override
public final void onSendPacket(PacketEvent event) {
listeners.forEach(l -> l.onSendPacket(event));
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onSendPacket(event);
}
});
}
@Override
public final void onReceivePacket(PacketEvent event) {
listeners.forEach(l -> l.onReceivePacket(event));
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onReceivePacket(event);
}
});
}
@Override
public void onPlayerRotationMove(RotationMoveEvent event) {
listeners.forEach(l -> l.onPlayerRotationMove(event));
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onPlayerRotationMove(event);
}
});
}
@Override
public void onBlockInteract(BlockInteractEvent event) {
listeners.forEach(l -> l.onBlockInteract(event));
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onBlockInteract(event);
}
});
}
@Override
public void onPlayerDeath() {
listeners.forEach(IGameEventListener::onPlayerDeath);
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onPlayerDeath();
}
});
}
@Override
public void onPathEvent(PathEvent event) {
listeners.forEach(l -> l.onPathEvent(event));
listeners.forEach(l -> {
if (canDispatch(l)) {
l.onPathEvent(event);
}
});
}
@Override
public final void registerEventListener(IGameEventListener listener) {
this.listeners.add(listener);
}
private boolean canDispatch(IGameEventListener listener) {
return !(listener instanceof Toggleable) || ((Toggleable) listener).isEnabled();
}
}
@@ -28,12 +28,9 @@ import baritone.pathing.movement.Moves;
import baritone.utils.BlockStateInterface;
import baritone.utils.Helper;
import baritone.utils.pathing.BetterWorldBorder;
import baritone.utils.pathing.Favoring;
import baritone.utils.pathing.MutableMoveResult;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Optional;
/**
@@ -43,22 +40,23 @@ import java.util.Optional;
*/
public final class AStarPathFinder extends AbstractNodeCostSearch implements Helper {
private final Favoring favoring;
private final Optional<LongOpenHashSet> favoredPositions;
private final CalculationContext calcContext;
public AStarPathFinder(int startX, int startY, int startZ, Goal goal, Favoring favoring, CalculationContext context) {
super(startX, startY, startZ, goal, context);
this.favoring = favoring;
public AStarPathFinder(int startX, int startY, int startZ, Goal goal, Optional<LongOpenHashSet> favoredPositions, CalculationContext context) {
super(startX, startY, startZ, goal);
this.favoredPositions = favoredPositions;
this.calcContext = context;
}
@Override
protected Optional<IPath> calculate0(long primaryTimeout, long failureTimeout) {
protected Optional<IPath> calculate0(long timeout) {
startNode = getNodeAtPosition(startX, startY, startZ, BetterBlockPos.longHash(startX, startY, startZ));
startNode.cost = 0;
startNode.combinedCost = startNode.estimatedCostToGoal;
BinaryHeapOpenSet openSet = new BinaryHeapOpenSet();
openSet.insert(startNode);
startNode.isOpen = true;
bestSoFar = new PathNode[COEFFICIENTS.length];//keep track of the best node by the metric of (estimatedCostToGoal + cost / COEFFICIENTS[i])
double[] bestHeuristicSoFar = new double[COEFFICIENTS.length];
for (int i = 0; i < bestHeuristicSoFar.length; i++) {
@@ -66,85 +64,47 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel
bestSoFar[i] = startNode;
}
MutableMoveResult res = new MutableMoveResult();
Favoring favored = favoring;
BetterWorldBorder worldBorder = new BetterWorldBorder(calcContext.world.getWorldBorder());
long startTime = System.currentTimeMillis();
BetterWorldBorder worldBorder = new BetterWorldBorder(world().getWorldBorder());
BlockStateInterface.clearCachedChunk();
LongOpenHashSet favored = favoredPositions.orElse(null);
long startTime = System.nanoTime() / 1000000L;
boolean slowPath = Baritone.settings().slowPath.get();
if (slowPath) {
logDebug("slowPath is on, path timeout will be " + Baritone.settings().slowPathTimeoutMS.<Long>get() + "ms instead of " + primaryTimeout + "ms");
logDebug("slowPath is on, path timeout will be " + Baritone.settings().slowPathTimeoutMS.<Long>get() + "ms instead of " + timeout + "ms");
}
long primaryTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.<Long>get() : primaryTimeout);
long failureTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.<Long>get() : failureTimeout);
boolean failing = true;
long timeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.<Long>get() : timeout);
//long lastPrintout = 0;
int numNodes = 0;
int numMovementsConsidered = 0;
int numEmptyChunk = 0;
boolean favoring = !favored.isEmpty();
int timeCheckInterval = 1 << 6;
boolean favoring = favoredPositions.isPresent();
int pathingMaxChunkBorderFetch = Baritone.settings().pathingMaxChunkBorderFetch.get(); // grab all settings beforehand so that changing settings during pathing doesn't cause a crash or unpredictable behavior
double favorCoeff = Baritone.settings().backtrackCostFavoringCoefficient.get();
boolean minimumImprovementRepropagation = Baritone.settings().minimumImprovementRepropagation.get();
long[] timeConsumed = new long[Moves.values().length];
int[] count = new int[Moves.values().length];
int[] stateLookup = new int[Moves.values().length];
long[] posCreation = new long[Moves.values().length];
long heapRemove = 0;
int heapRemoveCount = 0;
long heapAdd = 0;
int heapAddCount = 0;
long heapUpdate = 0;
int heapUpdateCount = 0;
long chunk = 0;
int chunkCount = 0;
long goalCheck = 0;
int goalCheckCount = 0;
long getNode = 0;
int getNodeCount = 0;
int startVal = BlockStateInterface.numTimesChunkSucceeded;
int startVal2 = BlockStateInterface.numBlockStateLookups;
long startVal3 = BetterBlockPos.numCreated;
while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && !cancelRequested) {
if ((numNodes & (timeCheckInterval - 1)) == 0) { // only call this once every 64 nodes (about half a millisecond)
long now = System.currentTimeMillis(); // since nanoTime is slow on windows (takes many microseconds)
if (now - failureTimeoutTime >= 0 || (!failing && now - primaryTimeoutTime >= 0)) {
break;
}
}
loopBegin();
while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && System.nanoTime() / 1000000L - timeoutTime < 0 && !cancelRequested) {
if (slowPath) {
try {
Thread.sleep(Baritone.settings().slowPathTimeDelayMS.<Long>get());
} catch (InterruptedException ex) {
}
}
long before = System.nanoTime();
PathNode currentNode = openSet.removeLowest();
long t = System.nanoTime();
heapRemove += t - before;
heapRemoveCount++;
currentNode.isOpen = false;
mostRecentConsidered = currentNode;
numNodes++;
if (goal.isInGoal(currentNode.x, currentNode.y, currentNode.z)) {
logDebug("Took " + (System.currentTimeMillis() - startTime) + "ms, " + numMovementsConsidered + " movements considered");
return Optional.of(new Path(startNode, currentNode, numNodes, goal, calcContext));
logDebug("Took " + (System.nanoTime() / 1000000L - startTime) + "ms, " + numMovementsConsidered + " movements considered");
return Optional.of(new Path(startNode, currentNode, numNodes, goal));
}
goalCheck += System.nanoTime() - t;
goalCheckCount++;
for (Moves moves : Moves.values()) {
long s = System.nanoTime();
int newX = currentNode.x + moves.xOffset;
int newZ = currentNode.z + moves.zOffset;
if ((newX >> 4 != currentNode.x >> 4 || newZ >> 4 != currentNode.z >> 4) && !calcContext.isLoaded(newX, newZ)) {
if ((newX >> 4 != currentNode.x >> 4 || newZ >> 4 != currentNode.z >> 4) && !BlockStateInterface.isLoaded(newX, newZ)) {
// only need to check if the destination is a loaded chunk if it's in a different chunk than the start of the movement
if (!moves.dynamicXZ) { // only increment the counter if the movement would have gone out of bounds guaranteed
numEmptyChunk++;
}
long costStart = System.nanoTime();
chunk += costStart - s;
chunkCount++;
continue;
}
if (!moves.dynamicXZ && !worldBorder.entirelyContains(newX, newZ)) {
@@ -153,31 +113,20 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel
if (currentNode.y + moves.yOffset > 256 || currentNode.y + moves.yOffset < 0) {
continue;
}
long costStart = System.nanoTime();
chunk += costStart - s;
chunkCount++;
// TODO cache cost
int numLookupsBefore = BlockStateInterface.numBlockStateLookups;
long numCreatedBefore = BetterBlockPos.numCreated;
res.reset();
moves.apply(calcContext, currentNode.x, currentNode.y, currentNode.z, res);
long costEnd = System.nanoTime();
stateLookup[moves.ordinal()] += BlockStateInterface.numBlockStateLookups - numLookupsBefore;
posCreation[moves.ordinal()] += BetterBlockPos.numCreated - numCreatedBefore;
timeConsumed[moves.ordinal()] += costEnd - costStart;
count[moves.ordinal()]++;
numMovementsConsidered++;
double actionCost = res.cost;
if (actionCost >= ActionCosts.COST_INF) {
continue;
}
if (actionCost <= 0 || Double.isNaN(actionCost)) {
if (actionCost <= 0) {
throw new IllegalStateException(moves + " calculated implausible cost " + actionCost);
}
// check destination after verifying it's not COST_INF -- some movements return a static IMPOSSIBLE object with COST_INF and destination being 0,0,0 to avoid allocating a new result for every failed calculation
if (moves.dynamicXZ && !worldBorder.entirelyContains(res.x, res.z)) { // see issue #218
continue;
}
// check destination after verifying it's not COST_INF -- some movements return a static IMPOSSIBLE object with COST_INF and destination being 0,0,0 to avoid allocating a new result for every failed calculation
if (!moves.dynamicXZ && (res.x != newX || res.z != newZ)) {
throw new IllegalStateException(moves + " " + res.x + " " + newX + " " + res.z + " " + newZ);
}
@@ -185,16 +134,16 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel
throw new IllegalStateException(moves + " " + res.y + " " + (currentNode.y + moves.yOffset));
}
long hashCode = BetterBlockPos.longHash(res.x, res.y, res.z);
if (favoring) {
if (favoring && favored.contains(hashCode)) {
// see issue #18
actionCost *= favored.calculate(hashCode);
actionCost *= favorCoeff;
}
long st = System.nanoTime();
PathNode neighbor = getNodeAtPosition(res.x, res.y, res.z, hashCode);
getNode += System.nanoTime() - st;
getNodeCount++;
double tentativeCost = currentNode.cost + actionCost;
if (tentativeCost < neighbor.cost) {
if (tentativeCost < 0) {
throw new IllegalStateException(moves + " overflowed into negative " + actionCost + " " + neighbor.cost + " " + tentativeCost);
}
double improvementBy = neighbor.cost - tentativeCost;
// there are floating point errors caused by random combinations of traverse and diagonal over a flat area
// that means that sometimes there's a cost improvement of like 10 ^ -16
@@ -206,16 +155,11 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel
neighbor.previous = currentNode;
neighbor.cost = tentativeCost;
neighbor.combinedCost = tentativeCost + neighbor.estimatedCostToGoal;
if (neighbor.isOpen()) {
long bef = System.nanoTime();
if (neighbor.isOpen) {
openSet.update(neighbor);
heapUpdate += System.nanoTime() - bef;
heapUpdateCount++;
} else {
long bef = System.nanoTime();
neighbor.isOpen = true;
openSet.insert(neighbor);//dont double count, dont insert into open set if it's already there
heapAdd += System.nanoTime() - bef;
heapAddCount++;
}
for (int i = 0; i < bestSoFar.length; i++) {
double heuristic = neighbor.estimatedCostToGoal + neighbor.cost / COEFFICIENTS[i];
@@ -225,51 +169,18 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel
}
bestHeuristicSoFar[i] = heuristic;
bestSoFar[i] = neighbor;
if (getDistFromStartSq(neighbor) > MIN_DIST_PATH * MIN_DIST_PATH) {
failing = false;
}
}
}
}
}
}
int numBlockState = BlockStateInterface.numBlockStateLookups - startVal2;
int numSucc = BlockStateInterface.numTimesChunkSucceeded - startVal;
long numSuccc = BetterBlockPos.numCreated - startVal3;
long totalAccountedTimeMS = 0;
totalAccountedTimeMS += heapRemove / 1000000;
totalAccountedTimeMS += heapAdd / 1000000;
totalAccountedTimeMS += heapUpdate / 1000000;
totalAccountedTimeMS += chunk / 1000000;
totalAccountedTimeMS += getNode / 1000000;
totalAccountedTimeMS += goalCheck / 1000000;
System.out.println("Out of " + numBlockState + " block state lookups, " + numSucc + " were in the same chunk as the previous and could be cached");
System.out.println("Instantiated " + numSuccc + " BetterBlockPos objects");
System.out.println("Remove " + (heapRemove / heapRemoveCount) + " " + heapRemove / 1000000 + "ms " + heapRemoveCount);
System.out.println("Add " + (heapAdd / heapAddCount) + " " + heapAdd / 1000000 + "ms " + heapAddCount);
System.out.println("Update " + (heapUpdate / heapUpdateCount) + " " + heapUpdate / 1000000 + "ms " + heapUpdateCount);
System.out.println("Chunk " + (chunk / chunkCount) + " " + chunk / 1000000 + "ms " + chunkCount);
System.out.println("GetNode " + (getNode / getNodeCount) + " " + getNode / 1000000 + "ms " + getNodeCount);
System.out.println("GoalCheck " + (goalCheck / goalCheckCount) + " " + goalCheck / 1000000 + "ms " + goalCheckCount);
ArrayList<Moves> moves = new ArrayList<>(Arrays.asList(Moves.values()));
moves.sort(Comparator.comparingLong(k -> timeConsumed[k.ordinal()] / count[k.ordinal()]));
for (Moves move : moves) {
int num = count[move.ordinal()];
long nanoTime = timeConsumed[move.ordinal()];
totalAccountedTimeMS += nanoTime / 1000000;
System.out.println(nanoTime / num + " " + move + " " + nanoTime / 1000000 + "ms " + num);
System.out.println(stateLookup[move.ordinal()] / num + " " + stateLookup[move.ordinal()]);
System.out.println(posCreation[move.ordinal()] / num + " " + posCreation[move.ordinal()]);
}
System.out.println("Total accounted time: " + totalAccountedTimeMS);
if (cancelRequested) {
return Optional.empty();
}
System.out.println(numMovementsConsidered + " movements considered");
System.out.println("Open set size: " + openSet.size());
System.out.println("PathNode map size: " + mapSize());
System.out.println((int) (numNodes * 1.0 / ((System.currentTimeMillis() - startTime) / 1000F)) + " nodes per second");
System.out.println((int) (numNodes * 1.0 / ((System.nanoTime() / 1000000L - startTime) / 1000F)) + " nodes per second");
double bestDist = 0;
for (int i = 0; i < bestSoFar.length; i++) {
if (bestSoFar[i] == null) {
@@ -280,14 +191,14 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel
bestDist = dist;
}
if (dist > MIN_DIST_PATH * MIN_DIST_PATH) { // square the comparison since distFromStartSq is squared
logDebug("Took " + (System.currentTimeMillis() - startTime) + "ms, A* cost coefficient " + COEFFICIENTS[i] + ", " + numMovementsConsidered + " movements considered");
logDebug("Took " + (System.nanoTime() / 1000000L - startTime) + "ms, A* cost coefficient " + COEFFICIENTS[i] + ", " + numMovementsConsidered + " movements considered");
if (COEFFICIENTS[i] >= 3) {
System.out.println("Warning: cost coefficient is greater than three! Probably means that");
System.out.println("the path I found is pretty terrible (like sneak-bridging for dozens of blocks)");
System.out.println("But I'm going to do it anyway, because yolo");
}
System.out.println("Path goes for " + Math.sqrt(dist) + " blocks");
return Optional.of(new Path(startNode, bestSoFar[i], numNodes, goal, calcContext));
return Optional.of(new Path(startNode, bestSoFar[i], numNodes, goal));
}
}
logDebug("Even with a cost coefficient of " + COEFFICIENTS[COEFFICIENTS.length - 1] + ", I couldn't get more than " + Math.sqrt(bestDist) + " blocks");
@@ -21,10 +21,6 @@ import baritone.Baritone;
import baritone.api.pathing.calc.IPath;
import baritone.api.pathing.calc.IPathFinder;
import baritone.api.pathing.goals.Goal;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.PathCalculationResult;
import baritone.pathing.movement.CalculationContext;
import baritone.utils.Helper;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import java.util.Optional;
@@ -36,14 +32,17 @@ import java.util.Optional;
*/
public abstract class AbstractNodeCostSearch implements IPathFinder {
/**
* The currently running search task
*/
private static AbstractNodeCostSearch currentlyRunning = null;
protected final int startX;
protected final int startY;
protected final int startZ;
protected final Goal goal;
private final CalculationContext context;
/**
* @see <a href="https://github.com/cabaletta/baritone/issues/107">Issue #107</a>
*/
@@ -71,12 +70,11 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
*/
protected final static double MIN_DIST_PATH = 5;
AbstractNodeCostSearch(int startX, int startY, int startZ, Goal goal, CalculationContext context) {
AbstractNodeCostSearch(int startX, int startY, int startZ, Goal goal) {
this.startX = startX;
this.startY = startY;
this.startZ = startZ;
this.goal = goal;
this.context = context;
this.map = new Long2ObjectOpenHashMap<>(Baritone.settings().pathingMapDefaultSize.value, Baritone.settings().pathingMapLoadFactor.get());
}
@@ -84,37 +82,32 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
cancelRequested = true;
}
@Override
public synchronized PathCalculationResult calculate(long primaryTimeout, long failureTimeout) {
public synchronized Optional<IPath> calculate(long timeout) {
if (isFinished) {
throw new IllegalStateException("Path finder cannot be reused!");
throw new IllegalStateException("Path Finder is currently in use, and cannot be reused!");
}
cancelRequested = false;
this.cancelRequested = false;
try {
IPath path = calculate0(primaryTimeout, failureTimeout).map(IPath::postProcess).orElse(null);
Optional<IPath> path = calculate0(timeout);
path.ifPresent(IPath::postProcess);
isFinished = true;
if (cancelRequested) {
return new PathCalculationResult(PathCalculationResult.Type.CANCELLATION, path);
}
if (path == null) {
return new PathCalculationResult(PathCalculationResult.Type.FAILURE);
}
if (goal.isInGoal(path.getDest())) {
return new PathCalculationResult(PathCalculationResult.Type.SUCCESS_TO_GOAL, path);
} else {
return new PathCalculationResult(PathCalculationResult.Type.SUCCESS_SEGMENT, path);
}
} catch (Exception e) {
Helper.HELPER.logDebug("Pathing exception: " + e);
e.printStackTrace();
return new PathCalculationResult(PathCalculationResult.Type.EXCEPTION);
return path;
} finally {
// this is run regardless of what exception may or may not be raised by calculate0
currentlyRunning = null;
isFinished = true;
}
}
protected abstract Optional<IPath> calculate0(long primaryTimeout, long failureTimeout);
/**
* Don't set currentlyRunning to this until everything is all ready to go, and we're about to enter the main loop.
* For example, bestSoFar is null so bestPathSoFar (which gets bestSoFar[0]) could NPE if we set currentlyRunning before calculate0
*/
protected void loopBegin() {
currentlyRunning = this;
}
protected abstract Optional<IPath> calculate0(long timeout);
/**
* Determines the distance squared from the specified node to the start
@@ -136,14 +129,9 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
* for the node mapped to the specified pos. If no node is found,
* a new node is created.
*
* @param x The x position of the node
* @param y The y position of the node
* @param z The z position of the node
* @param hashCode The hash code of the node, provided by {@link BetterBlockPos#longHash(int, int, int)}
* @return The associated node
* @see <a href="https://github.com/cabaletta/baritone/issues/107">Issue #107</a>
*/
protected PathNode getNodeAtPosition(int x, int y, int z, long hashCode) {
PathNode node = map.get(hashCode);
if (node == null) {
@@ -153,9 +141,30 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
return node;
}
public static void forceCancel() {
currentlyRunning = null;
}
public PathNode mostRecentNodeConsidered() {
return mostRecentConsidered;
}
public PathNode bestNodeSoFar() {
return bestSoFar[0];
}
public PathNode startNode() {
return startNode;
}
@Override
public Optional<IPath> pathToMostRecentNodeConsidered() {
return Optional.ofNullable(mostRecentConsidered).map(node -> new Path(startNode, node, 0, goal, context));
try {
return Optional.ofNullable(mostRecentConsidered).map(node -> new Path(startNode, node, 0, goal));
} catch (IllegalStateException ex) {
System.out.println("Unable to construct path to render");
return Optional.empty();
}
}
protected int mapSize() {
@@ -164,7 +173,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
@Override
public Optional<IPath> bestPathSoFar() {
if (startNode == null || bestSoFar == null) {
if (startNode == null || bestSoFar[0] == null) {
return Optional.empty();
}
for (int i = 0; i < bestSoFar.length; i++) {
@@ -172,7 +181,12 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
continue;
}
if (getDistFromStartSq(bestSoFar[i]) > MIN_DIST_PATH * MIN_DIST_PATH) { // square the comparison since distFromStartSq is squared
return Optional.of(new Path(startNode, bestSoFar[i], 0, goal, context));
try {
return Optional.of(new Path(startNode, bestSoFar[i], 0, goal));
} catch (IllegalStateException ex) {
System.out.println("Unable to construct path to render");
return Optional.empty();
}
}
}
// instead of returning bestSoFar[0], be less misleading
@@ -189,4 +203,12 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
public final Goal getGoal() {
return goal;
}
public static Optional<AbstractNodeCostSearch> getCurrentlyRunning() {
return Optional.ofNullable(currentlyRunning);
}
public static AbstractNodeCostSearch currentlyRunning() {
return currentlyRunning;
}
}
@@ -15,18 +15,17 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.pathing.path;
package baritone.pathing.calc;
import baritone.api.pathing.calc.IPath;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.movement.IMovement;
import baritone.api.utils.BetterBlockPos;
import baritone.utils.pathing.PathBase;
import java.util.Collections;
import java.util.List;
public class CutoffPath extends PathBase {
public class CutoffPath implements IPath {
private final List<BetterBlockPos> path;
@@ -36,16 +35,11 @@ public class CutoffPath extends PathBase {
private final Goal goal;
public CutoffPath(IPath prev, int firstPositionToInclude, int lastPositionToInclude) {
path = prev.positions().subList(firstPositionToInclude, lastPositionToInclude + 1);
movements = prev.movements().subList(firstPositionToInclude, lastPositionToInclude);
CutoffPath(IPath prev, int lastPositionToInclude) {
path = prev.positions().subList(0, lastPositionToInclude + 1);
movements = prev.movements().subList(0, lastPositionToInclude + 1);
numNodes = prev.getNumNodesConsidered();
goal = prev.getGoal();
sanityCheck();
}
public CutoffPath(IPath prev, int lastPositionToInclude) {
this(prev, 0, lastPositionToInclude);
}
@Override
+73 -49
View File
@@ -17,16 +17,16 @@
package baritone.pathing.calc;
import baritone.api.BaritoneAPI;
import baritone.api.pathing.calc.IPath;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.movement.IMovement;
import baritone.api.utils.BetterBlockPos;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.Moves;
import baritone.pathing.path.CutoffPath;
import baritone.utils.Helper;
import baritone.utils.pathing.PathBase;
import net.minecraft.client.Minecraft;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.EmptyChunk;
import java.util.ArrayList;
import java.util.Collections;
@@ -38,7 +38,7 @@ import java.util.List;
*
* @author leijurv
*/
class Path extends PathBase {
class Path implements IPath {
/**
* The start position of this path
@@ -58,26 +58,20 @@ class Path extends PathBase {
private final List<Movement> movements;
private final List<PathNode> nodes;
private final Goal goal;
private final int numNodes;
private final CalculationContext context;
private volatile boolean verified;
Path(PathNode start, PathNode end, int numNodes, Goal goal, CalculationContext context) {
Path(PathNode start, PathNode end, int numNodes, Goal goal) {
this.start = new BetterBlockPos(start.x, start.y, start.z);
this.end = new BetterBlockPos(end.x, end.y, end.z);
this.numNodes = numNodes;
this.path = new ArrayList<>();
this.movements = new ArrayList<>();
this.nodes = new ArrayList<>();
this.goal = goal;
this.context = context;
assemblePath(end);
assemblePath(start, end);
}
@Override
@@ -86,82 +80,88 @@ class Path extends PathBase {
}
/**
* Assembles this path given the end node.
* Assembles this path given the start and end nodes.
*
* @param end The end node
* @param start The start node
* @param end The end node
*/
private void assemblePath(PathNode end) {
private void assemblePath(PathNode start, PathNode end) {
if (!path.isEmpty() || !movements.isEmpty()) {
throw new IllegalStateException();
}
PathNode current = end;
LinkedList<BetterBlockPos> tempPath = new LinkedList<>();
LinkedList<PathNode> tempNodes = new LinkedList();
// Repeatedly inserting to the beginning of an arraylist is O(n^2)
// Instead, do it into a linked list, then convert at the end
while (current != null) {
tempNodes.addFirst(current);
while (!current.equals(start)) {
tempPath.addFirst(new BetterBlockPos(current.x, current.y, current.z));
current = current.previous;
}
tempPath.addFirst(this.start);
// Can't directly convert from the PathNode pseudo linked list to an array because we don't know how long it is
// inserting into a LinkedList<E> keeps track of length, then when we addall (which calls .toArray) it's able
// to performantly do that conversion since it knows the length.
path.addAll(tempPath);
nodes.addAll(tempNodes);
}
private boolean assembleMovements() {
/**
* Performs a series of checks to ensure that the assembly of the path went as expected.
*/
private void sanityCheck() {
if (!start.equals(path.get(0))) {
throw new IllegalStateException("Start node does not equal first path element");
}
if (!end.equals(path.get(path.size() - 1))) {
throw new IllegalStateException("End node does not equal last path element");
}
if (path.size() != movements.size() + 1) {
throw new IllegalStateException("Size of path array is unexpected");
}
for (int i = 0; i < path.size() - 1; i++) {
BlockPos src = path.get(i);
BlockPos dest = path.get(i + 1);
Movement movement = movements.get(i);
if (!src.equals(movement.getSrc())) {
throw new IllegalStateException("Path source is not equal to the movement source");
}
if (!dest.equals(movement.getDest())) {
throw new IllegalStateException("Path destination is not equal to the movement destination");
}
}
}
private void assembleMovements() {
if (path.isEmpty() || !movements.isEmpty()) {
throw new IllegalStateException();
}
for (int i = 0; i < path.size() - 1; i++) {
double cost = nodes.get(i + 1).cost - nodes.get(i).cost;
Movement move = runBackwards(path.get(i), path.get(i + 1), cost);
if (move == null) {
return true;
} else {
movements.add(move);
}
movements.add(runBackwards(path.get(i), path.get(i + 1)));
}
return false;
}
private Movement runBackwards(BetterBlockPos src, BetterBlockPos dest, double cost) {
private static Movement runBackwards(BetterBlockPos src, BetterBlockPos dest) { // TODO this is horrifying
for (Moves moves : Moves.values()) {
Movement move = moves.apply0(context, src);
Movement move = moves.apply0(src);
if (move.getDest().equals(dest)) {
// have to calculate the cost at calculation time so we can accurately judge whether a cost increase happened between cached calculation and real execution
// however, taking into account possible favoring that could skew the node cost, we really want the stricter limit of the two
// so we take the minimum of the path node cost difference, and the calculated cost
move.override(Math.min(move.calculateCost(context), cost));
// TODO instead of recalculating here, could we take pathNode.cost - pathNode.prevNode.cost to get the cost as-calculated?
move.recalculateCost(); // have to calculate the cost at calculation time so we can accurately judge whether a cost increase happened between cached calculation and real execution
return move;
}
}
// this is no longer called from bestPathSoFar, now it's in postprocessing
Helper.HELPER.logDebug("Movement became impossible during calculation " + src + " " + dest + " " + dest.subtract(src));
return null;
throw new IllegalStateException("Movement became impossible during calculation " + src + " " + dest + " " + dest.subtract(src));
}
@Override
public IPath postProcess() {
public void postProcess() {
if (verified) {
throw new IllegalStateException();
}
verified = true;
boolean failed = assembleMovements();
movements.forEach(m -> m.checkLoadedChunk(context));
if (failed) { // at least one movement became impossible during calculation
CutoffPath res = new CutoffPath(this, movements().size());
if (res.movements().size() != movements.size()) {
throw new IllegalStateException();
}
return res;
}
assembleMovements();
// more post processing here
movements.forEach(Movement::checkLoadedChunk);
sanityCheck();
return this;
}
@Override
@@ -191,4 +191,28 @@ class Path extends PathBase {
public BetterBlockPos getDest() {
return end;
}
@Override
public IPath cutoffAtLoadedChunks() {
for (int i = 0; i < positions().size(); i++) {
BlockPos pos = positions().get(i);
if (Minecraft.getMinecraft().world.getChunk(pos) instanceof EmptyChunk) {
return new CutoffPath(this, i);
}
}
return this;
}
@Override
public IPath staticCutoff(Goal destination) {
if (length() < BaritoneAPI.getSettings().pathCutoffMinimumLength.get()) {
return this;
}
if (destination == null || destination.isInGoal(getDest())) {
return this;
}
double factor = BaritoneAPI.getSettings().pathCutoffFactor.get();
int newLength = (int) (length() * factor);
return new CutoffPath(this, newLength);
}
}

Some files were not shown because too many files have changed in this diff Show More