diff --git a/README.md b/README.md index 9fa8a2c9..904f3d61 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Building Baritone: $ gradlew build ``` -For example, 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"`). +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"`). ## IntelliJ's Gradle UI - Open the project in IntelliJ as a Gradle project diff --git a/build.gradle b/build.gradle index 6120aa47..0c151541 100755 --- a/build.gradle +++ b/build.gradle @@ -111,7 +111,6 @@ 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) diff --git a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java index 251508f9..714c3842 100644 --- a/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java +++ b/buildSrc/src/main/java/baritone/gradle/task/ProguardTask.java @@ -18,15 +18,19 @@ package baritone.gradle.task; import baritone.gradle.util.Determinizer; -import com.google.gson.*; +import baritone.gradle.util.MappingType; +import baritone.gradle.util.ReobfWrapper; 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; @@ -34,6 +38,7 @@ import java.nio.file.Paths; 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; @@ -53,10 +58,6 @@ public class ProguardTask extends BaritoneGradleTask { @Input private String extract; - @Input - private String versionManifest; - - private Map versionDownloadMap; private List requiredLibraries; @TaskAction @@ -68,7 +69,6 @@ public class ProguardTask extends BaritoneGradleTask { downloadProguard(); extractProguard(); generateConfigs(); - downloadVersionManifest(); acquireDependencies(); proguardApi(); proguardStandalone(); @@ -134,20 +134,6 @@ 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 @@ -165,15 +151,13 @@ public class ProguardTask extends BaritoneGradleTask { // Iterate the required libraries to copy them to tempLibraries for (String lib : this.requiredLibraries) { - // 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); - } + // copy from the forgegradle cache + if (lib.equals("minecraft")) { + Path cachedJar = getMinecraftJar(); + Path inTempDir = getTemporaryFile("tempLibraries/minecraft.jar"); + // TODO: maybe try not to copy every time + Files.copy(cachedJar, inTempDir, REPLACE_EXISTING); + continue; } @@ -197,6 +181,89 @@ 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(); + Field f_replacer = class_baseExtension.getDeclaredField("replacer"); + f_replacer.setAccessible(true); + Object replacer = f_replacer.get(extension); + Class class_replacementProvider = replacer.getClass(); + Field replacement_replaceMap = class_replacementProvider.getDeclaredField("replaceMap"); + replacement_replaceMap.setAccessible(true); + + Map replacements = (Map) replacement_replaceMap.get(replacer); + String cacheDir = replacements.get("CACHE_DIR").toString() + "/net/minecraft"; + String mcVersion = replacements.get("MC_VERSION").toString(); + String mcpInsert = replacements.get("MAPPING_CHANNEL").toString() + "/" + replacements.get("MAPPING_VERSION").toString(); + String fullJarName = "minecraft-" + mcVersion + suffix + ".jar"; + + String baseDir = String.format("%s/minecraft/%s/", cacheDir, mcVersion); + + String jarPath; + if (mappingType == MappingType.SEARGE) { + jarPath = String.format("%s/%s/%s", baseDir, mcpInsert, fullJarName); + } else { + jarPath = baseDir + fullJarName; + } + jarPath = jarPath + .replace("/", File.separator) + .replace("\\", File.separator); // hecking regex + + 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 reobf = (NamedDomainObjectContainer) this.getProject().getExtensions().getByName("reobf"); + + List mappingTypes = getUsedMappingTypes(reobf); + long mappingTypesUsed = mappingTypes.size(); + if (mappingTypesUsed == 0) { + throw new IllegalStateException("Failed to find mapping type (no jar task?)"); + } + if (mappingTypesUsed > 1) { + throw new IllegalStateException("Ambiguous mapping type (multiple jars with different mapping types?)"); + } + + return mappingTypes.get(0); + } + + private List getUsedMappingTypes(Set 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()); @@ -221,10 +288,6 @@ 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)) { @@ -254,7 +317,7 @@ public class ProguardTask extends BaritoneGradleTask { while ((line = reader.readLine()) != null) { System.out.println(line); } - } catch (final Exception e) { + } catch (Exception e) { e.printStackTrace(); } }).start(); diff --git a/buildSrc/src/main/java/baritone/gradle/util/MappingType.java b/buildSrc/src/main/java/baritone/gradle/util/MappingType.java new file mode 100644 index 00000000..4a6c10ff --- /dev/null +++ b/buildSrc/src/main/java/baritone/gradle/util/MappingType.java @@ -0,0 +1,29 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.gradle.util; + +/** + * All credits go to AsmLibGradle and its contributors. + * + * @see Original Source + */ +public enum MappingType { + SEARGE, + NOTCH, + CUSTOM // forgegradle +} \ No newline at end of file diff --git a/buildSrc/src/main/java/baritone/gradle/util/ReobfWrapper.java b/buildSrc/src/main/java/baritone/gradle/util/ReobfWrapper.java new file mode 100644 index 00000000..92f38a9f --- /dev/null +++ b/buildSrc/src/main/java/baritone/gradle/util/ReobfWrapper.java @@ -0,0 +1,63 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package baritone.gradle.util; + +import java.lang.reflect.Field; +import java.util.Objects; + +/** + * All credits go to AsmLibGradle and its contributors. + * + * @see Original Source + */ +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); + } + } +} \ No newline at end of file diff --git a/scripts/proguard.pro b/scripts/proguard.pro index 270a0631..07e1ec41 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -31,7 +31,8 @@ # copy all necessary libraries into tempLibraries to build --libraryjars 'tempLibraries/minecraft-1.12.2.jar' +# The correct jar will be copied from the forgegradle cache based on the mapping type being compiled with +-libraryjars 'tempLibraries/minecraft.jar' -libraryjars 'tempLibraries/SimpleTweaker-1.2.jar' diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index a835ed73..1a3fef08 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -553,6 +553,12 @@ public class Settings { */ public final List> allSettings; + public void reset() { + for (Setting setting : allSettings) { + setting.value = setting.defaultValue; + } + } + public class Setting { public T value; public final T defaultValue; diff --git a/src/api/java/baritone/api/pathing/calc/IPath.java b/src/api/java/baritone/api/pathing/calc/IPath.java index 133de5ef..8f0cb68e 100644 --- a/src/api/java/baritone/api/pathing/calc/IPath.java +++ b/src/api/java/baritone/api/pathing/calc/IPath.java @@ -109,8 +109,9 @@ public interface IPath { default double ticksRemainingFrom(int pathPosition) { double sum = 0; //this is fast because we aren't requesting recalculation, it's just cached - for (int i = pathPosition; i < movements().size(); i++) { - sum += movements().get(i).getCost(); + List movements = movements(); + for (int i = pathPosition; i < movements.size(); i++) { + sum += movements.get(i).getCost(); } return sum; } diff --git a/src/api/java/baritone/api/pathing/movement/IMovement.java b/src/api/java/baritone/api/pathing/movement/IMovement.java index 7b3eca5f..c9b9ea4b 100644 --- a/src/api/java/baritone/api/pathing/movement/IMovement.java +++ b/src/api/java/baritone/api/pathing/movement/IMovement.java @@ -20,8 +20,6 @@ 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 @@ -58,10 +56,4 @@ public interface IMovement { BetterBlockPos getDest(); BlockPos getDirection(); - - List toBreak(); - - List toPlace(); - - List toWalkInto(); } diff --git a/src/api/java/baritone/api/utils/Rotation.java b/src/api/java/baritone/api/utils/Rotation.java index ea10c7ec..28afbf65 100644 --- a/src/api/java/baritone/api/utils/Rotation.java +++ b/src/api/java/baritone/api/utils/Rotation.java @@ -110,6 +110,17 @@ public class Rotation { ); } + /** + * 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. * diff --git a/src/api/java/baritone/api/utils/VecUtils.java b/src/api/java/baritone/api/utils/VecUtils.java index 090cb9d7..1df01163 100644 --- a/src/api/java/baritone/api/utils/VecUtils.java +++ b/src/api/java/baritone/api/utils/VecUtils.java @@ -81,10 +81,9 @@ public final class VecUtils { * @see #getBlockPosCenter(BlockPos) */ public static double distanceToCenter(BlockPos pos, double x, double y, double z) { - Vec3d center = getBlockPosCenter(pos); - double xdiff = x - center.x; - double ydiff = y - center.y; - double zdiff = z - center.z; + double xdiff = pos.getX() + 0.5 - x; + double ydiff = pos.getY() + 0.5 - y; + double zdiff = pos.getZ() + 0.5 - z; return Math.sqrt(xdiff * xdiff + ydiff * ydiff + zdiff * zdiff); } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 42186b5b..bd2146b8 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -37,12 +37,15 @@ import baritone.pathing.path.CutoffPath; import baritone.pathing.path.PathExecutor; import baritone.utils.Helper; import baritone.utils.PathRenderer; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; -import java.util.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Objects; +import java.util.Optional; import java.util.concurrent.LinkedBlockingQueue; -import java.util.stream.Collectors; public final class PathingBehavior extends Behavior implements IPathingBehavior, Helper { @@ -277,11 +280,13 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } public void softCancelIfSafe() { - if (!isSafeToCancel()) { - return; + synchronized (pathPlanLock) { + if (!isSafeToCancel()) { + return; + } + current = null; + next = null; } - current = null; - next = null; cancelRequested = true; getInProgress().ifPresent(AbstractNodeCostSearch::cancel); // only cancel ours // do everything BUT clear keys @@ -290,8 +295,10 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // just cancel the current path public void secretInternalSegmentCancel() { queuePathEvent(PathEvent.CANCELED); - current = null; - next = null; + synchronized (pathPlanLock) { + current = null; + next = null; + } baritone.getInputOverrideHandler().clearAllKeys(); getInProgress().ifPresent(AbstractNodeCostSearch::cancel); baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); @@ -330,12 +337,18 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } } + 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 BlockPos pathStart() { // TODO move to a helper or util class + 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) { @@ -405,8 +418,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, primaryTimeout = Baritone.settings().planAheadPrimaryTimeoutMS.get(); failureTimeout = Baritone.settings().planAheadFailureTimeoutMS.get(); } - CalculationContext context = new CalculationContext(baritone); // 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); + 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, true); if (!Objects.equals(pathfinder.getGoal(), goal)) { logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance"); } @@ -463,7 +476,9 @@ 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"); + //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!"); } } if (talkAboutIt && current != null && current.getPath() != null) { @@ -480,17 +495,19 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, }); } - public static AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, IPath previous, CalculationContext context) { + public static AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, IPath previous, CalculationContext context, boolean allowSimplifyUnloaded) { Goal transformed = goal; - if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) { + if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos && allowSimplifyUnloaded) { BlockPos pos = ((IGoalRenderPos) goal).getGoalPos(); if (context.world().getChunk(pos) instanceof EmptyChunk) { transformed = new GoalXZ(pos.getX(), pos.getZ()); } } - HashSet favoredPositions = null; + LongOpenHashSet favoredPositions = null; if (Baritone.settings().backtrackCostFavoringCoefficient.get() != 1D && previous != null) { - favoredPositions = previous.positions().stream().map(BetterBlockPos::longHash).collect(Collectors.toCollection(HashSet::new)); + LongOpenHashSet tmp = new LongOpenHashSet(); + previous.positions().forEach(pos -> tmp.add(BetterBlockPos.longHash(pos))); + favoredPositions = tmp; } return new AStarPathFinder(start.getX(), start.getY(), start.getZ(), transformed, favoredPositions, context); } diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 1e55cb64..ebf0bfc9 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -35,7 +35,7 @@ public final class CachedChunk { static { HashSet 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); diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index 31bcceab..e9caddfe 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -255,6 +255,10 @@ public final class CachedWorld implements ICachedWorld, Helper { }); } + 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. diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index cd072bb6..60ac6331 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -39,6 +39,8 @@ import java.util.*; */ public final class ChunkPacker { + private static final Map resourceCache = new HashMap<>(); + private ChunkPacker() {} public static CachedChunk pack(Chunk chunk) { @@ -91,10 +93,7 @@ public final class ChunkPacker { IBlockState[] blocks = new IBlockState[256]; for (int z = 0; z < 16; z++) { - // @formatter:off - https: -//www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html - // @formatter:on + https://www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html for (int x = 0; x < 16; x++) { for (int y = 255; y >= 0; y--) { int index = CachedChunk.getPositionIndex(x, y, z); @@ -120,7 +119,7 @@ public final class ChunkPacker { } public static Block stringToBlock(String name) { - return Block.getBlockFromName(name.contains(":") ? name : "minecraft:" + name); + return resourceCache.computeIfAbsent(name, n -> Block.getBlockFromName(n.contains(":") ? n : "minecraft:" + n)); } private static PathingBlockType getPathingBlockType(IBlockState state) { diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index d0061921..d7292da7 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -28,6 +28,7 @@ import baritone.pathing.movement.Moves; import baritone.utils.Helper; import baritone.utils.pathing.BetterWorldBorder; import baritone.utils.pathing.MutableMoveResult; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import java.util.HashSet; import java.util.Optional; @@ -39,10 +40,10 @@ import java.util.Optional; */ public final class AStarPathFinder extends AbstractNodeCostSearch implements Helper { - private final HashSet favoredPositions; + private final LongOpenHashSet favoredPositions; private final CalculationContext calcContext; - public AStarPathFinder(int startX, int startY, int startZ, Goal goal, HashSet favoredPositions, CalculationContext context) { + public AStarPathFinder(int startX, int startY, int startZ, Goal goal, LongOpenHashSet favoredPositions, CalculationContext context) { super(startX, startY, startZ, goal, context); this.favoredPositions = favoredPositions; this.calcContext = context; @@ -63,7 +64,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel bestSoFar[i] = startNode; } MutableMoveResult res = new MutableMoveResult(); - HashSet favored = favoredPositions; + LongOpenHashSet favored = favoredPositions; BetterWorldBorder worldBorder = new BetterWorldBorder(calcContext.world().getWorldBorder()); long startTime = System.nanoTime() / 1000000L; boolean slowPath = Baritone.settings().slowPath.get(); @@ -143,9 +144,6 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel PathNode neighbor = getNodeAtPosition(res.x, res.y, res.z, hashCode); 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 diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index f2dcf4b1..2a1681b7 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -86,7 +86,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { @Override public synchronized PathCalculationResult calculate(long primaryTimeout, long failureTimeout) { if (isFinished) { - throw new IllegalStateException("Path Finder is currently in use, and cannot be reused!"); + throw new IllegalStateException("Path finder cannot be reused!"); } cancelRequested = false; try { diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index cb4727cc..ace7670c 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -60,11 +60,15 @@ public class CalculationContext { private final BetterWorldBorder worldBorder; public CalculationContext(IBaritone baritone) { + this(baritone, false); + } + + public CalculationContext(IBaritone baritone, boolean forUseOnAnotherThread) { this.baritone = baritone; this.player = baritone.getPlayerContext().player(); this.world = baritone.getPlayerContext().world(); this.worldData = (WorldData) baritone.getWorldProvider().getCurrentWorld(); - this.bsi = new BlockStateInterface(world, worldData); // TODO TODO TODO + this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); // TODO TODO TODO // new CalculationContext() needs to happen, can't add an argument (i'll beat you), can we get the world provider from currentlyTicking? this.toolSet = new ToolSet(player); this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(baritone.getPlayerContext(), false); diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index a3e841c6..4105b5e7 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -151,9 +151,10 @@ public abstract class Movement implements IMovement, MovementHelper { somethingInTheWay = true; Optional reachable = RotationUtils.reachable(ctx.player(), blockPos, ctx.playerController().getBlockReachDistance()); if (reachable.isPresent()) { + Rotation rotTowardsBlock = reachable.get(); MovementHelper.switchToBestToolFor(ctx, BlockStateInterface.get(ctx, blockPos)); - state.setTarget(new MovementState.MovementTarget(reachable.get(), true)); - if (Objects.equals(ctx.getSelectedBlock().orElse(null), blockPos)) { + state.setTarget(new MovementState.MovementTarget(rotTowardsBlock, true)); + if (Objects.equals(ctx.getSelectedBlock().orElse(null), blockPos) || ctx.playerRotations().isReallyCloseTo(rotTowardsBlock)) { state.setInput(Input.CLICK_LEFT, true); } return false; @@ -244,14 +245,13 @@ public abstract class Movement implements IMovement, MovementHelper { toWalkIntoCached = null; } - @Override - public List toBreak() { + public List toBreak(BlockStateInterface bsi) { if (toBreakCached != null) { return toBreakCached; } List result = new ArrayList<>(); for (BetterBlockPos positionToBreak : positionsToBreak) { - if (!MovementHelper.canWalkThrough(ctx, positionToBreak)) { + if (!MovementHelper.canWalkThrough(bsi, positionToBreak.x, positionToBreak.y, positionToBreak.z)) { result.add(positionToBreak); } } @@ -259,21 +259,19 @@ public abstract class Movement implements IMovement, MovementHelper { return result; } - @Override - public List toPlace() { + public List toPlace(BlockStateInterface bsi) { if (toPlaceCached != null) { return toPlaceCached; } List result = new ArrayList<>(); - if (positionToPlace != null && !MovementHelper.canWalkOn(ctx, positionToPlace)) { + if (positionToPlace != null && !MovementHelper.canWalkOn(bsi, positionToPlace.x, positionToPlace.y, positionToPlace.z)) { result.add(positionToPlace); } toPlaceCached = result; return result; } - @Override - public List toWalkInto() { // overridden by movementdiagonal + public List toWalkInto(BlockStateInterface bsi) { // overridden by movementdiagonal if (toWalkIntoCached == null) { toWalkIntoCached = new ArrayList<>(); } diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 917adc7c..9d31a379 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -70,7 +70,7 @@ public interface MovementHelper extends ActionCosts, Helper { if (block == Blocks.AIR) { // early return for most common case return true; } - if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.WEB || block == Blocks.END_PORTAL) { + if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.WEB || block == Blocks.END_PORTAL || block == Blocks.COCOA) { return false; } if (block instanceof BlockDoor || block instanceof BlockFenceGate) { @@ -92,7 +92,11 @@ public interface MovementHelper extends ActionCosts, Helper { if (snow) { // the check in BlockSnow.isPassable is layers < 5 // while actually, we want < 3 because 3 or greater makes it impassable in a 2 high ceiling - return state.getValue(BlockSnow.LAYERS) < 3; + if (state.getValue(BlockSnow.LAYERS) >= 3) { + return false; + } + // ok, it's low enough we could walk through it, but is it supported? + return canWalkOn(bsi, x, y - 1, z); } if (trapdoor) { return !state.getValue(BlockTrapDoor.OPEN); // see BlockTrapDoor.isPassable @@ -139,6 +143,7 @@ public interface MovementHelper extends ActionCosts, Helper { || block == Blocks.WEB || block == Blocks.VINE || block == Blocks.LADDER + || block == Blocks.COCOA || block instanceof BlockDoor || block instanceof BlockFenceGate || block instanceof BlockSnow @@ -465,7 +470,6 @@ public interface MovementHelper extends ActionCosts, Helper { static boolean isFlowing(IBlockState state) { // Will be IFluidState in 1.13 return state.getBlock() instanceof BlockLiquid - && state.getPropertyKeys().contains(BlockLiquid.LEVEL) && state.getValue(BlockLiquid.LEVEL) != 0; } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 4a098380..afe5a976 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -25,6 +25,7 @@ import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; +import baritone.utils.BlockStateInterface; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -115,7 +116,8 @@ public class MovementDiagonal extends Movement { return COST_INF; } boolean water = false; - if (MovementHelper.isWater(context.getBlock(x, y, z)) || MovementHelper.isWater(destInto.getBlock())) { + Block startIn = context.getBlock(x, y, z); + if (MovementHelper.isWater(startIn) || MovementHelper.isWater(destInto.getBlock())) { // Ignore previous multiplier // Whatever we were walking on (possibly soul sand) doesn't matter as we're actually floating on water // Not even touching the blocks below @@ -124,6 +126,10 @@ public class MovementDiagonal extends Movement { } if (optionA != 0 || optionB != 0) { multiplier *= SQRT_2 - 0.001; // TODO tune + if (startIn == Blocks.LADDER || startIn == Blocks.VINE) { + // edging around doesn't work if doing so would climb a ladder or vine instead of moving sideways + return COST_INF; + } } if (context.canSprint() && !water) { // If we aren't edging around anything, and we aren't in water @@ -158,13 +164,13 @@ public class MovementDiagonal extends Movement { } @Override - public List toBreak() { + public List toBreak(BlockStateInterface bsi) { if (toBreakCached != null) { return toBreakCached; } List result = new ArrayList<>(); for (int i = 4; i < 6; i++) { - if (!MovementHelper.canWalkThrough(ctx, positionsToBreak[i])) { + if (!MovementHelper.canWalkThrough(bsi, positionsToBreak[i].x, positionsToBreak[i].y, positionsToBreak[i].z)) { result.add(positionsToBreak[i]); } } @@ -173,13 +179,13 @@ public class MovementDiagonal extends Movement { } @Override - public List toWalkInto() { + public List toWalkInto(BlockStateInterface bsi) { if (toWalkIntoCached == null) { toWalkIntoCached = new ArrayList<>(); } List result = new ArrayList<>(); for (int i = 0; i < 4; i++) { - if (!MovementHelper.canWalkThrough(ctx, positionsToBreak[i])) { + if (!MovementHelper.canWalkThrough(bsi, positionsToBreak[i].x, positionsToBreak[i].y, positionsToBreak[i].z)) { result.add(positionsToBreak[i]); } } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 171dd769..15948d45 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -30,6 +30,7 @@ import baritone.api.utils.input.Input; import baritone.behavior.PathingBehavior; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.CalculationContext; +import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.movements.*; import baritone.utils.BlockStateInterface; @@ -186,22 +187,23 @@ public class PathExecutor implements IPathExecutor, Helper { } }*/ //long start = System.nanoTime() / 1000000L; + BlockStateInterface bsi = new BlockStateInterface(ctx); for (int i = pathPosition - 10; i < pathPosition + 10; i++) { if (i < 0 || i >= path.movements().size()) { continue; } - IMovement m = path.movements().get(i); - HashSet prevBreak = new HashSet<>(m.toBreak()); - HashSet prevPlace = new HashSet<>(m.toPlace()); - HashSet prevWalkInto = new HashSet<>(m.toWalkInto()); + Movement m = (Movement) path.movements().get(i); + HashSet prevBreak = new HashSet<>(m.toBreak(bsi)); + HashSet prevPlace = new HashSet<>(m.toPlace(bsi)); + HashSet prevWalkInto = new HashSet<>(m.toWalkInto(bsi)); m.resetBlockCache(); - if (!prevBreak.equals(new HashSet<>(m.toBreak()))) { + if (!prevBreak.equals(new HashSet<>(m.toBreak(bsi)))) { recalcBP = true; } - if (!prevPlace.equals(new HashSet<>(m.toPlace()))) { + if (!prevPlace.equals(new HashSet<>(m.toPlace(bsi)))) { recalcBP = true; } - if (!prevWalkInto.equals(new HashSet<>(m.toWalkInto()))) { + if (!prevWalkInto.equals(new HashSet<>(m.toWalkInto(bsi)))) { recalcBP = true; } } @@ -210,9 +212,10 @@ public class PathExecutor implements IPathExecutor, Helper { HashSet newPlace = new HashSet<>(); HashSet newWalkInto = new HashSet<>(); for (int i = pathPosition; i < path.movements().size(); i++) { - newBreak.addAll(path.movements().get(i).toBreak()); - newPlace.addAll(path.movements().get(i).toPlace()); - newWalkInto.addAll(path.movements().get(i).toWalkInto()); + Movement movement = (Movement) path.movements().get(i); + newBreak.addAll(movement.toBreak(bsi)); + newPlace.addAll(movement.toPlace(bsi)); + newWalkInto.addAll(movement.toWalkInto(bsi)); } toBreak = newBreak; toPlace = newPlace; @@ -346,6 +349,9 @@ public class PathExecutor implements IPathExecutor, Helper { * Regardless of current path position, snap to the current player feet if possible */ public boolean snipsnapifpossible() { + if (!ctx.player().onGround) { + return false; + } int index = path.positions().indexOf(ctx.playerFeet()); if (index == -1) { return false; diff --git a/src/main/java/baritone/pathing/path/SplicedPath.java b/src/main/java/baritone/pathing/path/SplicedPath.java index 92610c86..f2187fe7 100644 --- a/src/main/java/baritone/pathing/path/SplicedPath.java +++ b/src/main/java/baritone/pathing/path/SplicedPath.java @@ -62,6 +62,11 @@ public class SplicedPath extends PathBase { return numNodes; } + @Override + public int length() { + return path.size(); + } + public static Optional trySplice(IPath first, IPath second, boolean allowOverlapCutoff) { if (second == null || first == null) { return Optional.empty(); @@ -77,6 +82,7 @@ public class SplicedPath extends PathBase { for (int i = 0; i < first.length() - 1; i++) { // overlap in the very last element is fine (and required) so only go up to first.length() - 1 if (secondPos.contains(first.positions().get(i))) { firstPositionInSecond = i; + break; } } if (firstPositionInSecond != -1) { @@ -94,7 +100,7 @@ public class SplicedPath extends PathBase { List movements = new ArrayList<>(); positions.addAll(first.positions().subList(0, firstPositionInSecond + 1)); movements.addAll(first.movements().subList(0, firstPositionInSecond)); - + positions.addAll(second.positions().subList(positionInSecond + 1, second.length())); movements.addAll(second.movements().subList(positionInSecond, second.length() - 1)); return Optional.of(new SplicedPath(positions, movements, first.getNumNodesConsidered() + second.getNumNodesConsidered(), first.getGoal())); diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 95f2122b..920e5743 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -77,7 +77,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain List current = new ArrayList<>(knownLocations); - CalculationContext context = new CalculationContext(baritone); + CalculationContext context = new CalculationContext(baritone, true); Baritone.getExecutor().execute(() -> rescan(current, context)); } Goal goal = new GoalComposite(knownLocations.stream().map(GoalGetToBlock::new).toArray(Goal[]::new)); diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 4ea75387..9347dba2 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -89,7 +89,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain List curr = new ArrayList<>(knownOreLocations); - CalculationContext context = new CalculationContext(baritone); + CalculationContext context = new CalculationContext(baritone, true); Baritone.getExecutor().execute(() -> rescan(curr, context)); } if (Baritone.settings().legitMine.get()) { @@ -210,7 +210,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro //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(), 1)); + locs.addAll(ctx.worldData().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 2)); } else { uninteresting.add(m); } diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index b6b264d0..be49c97c 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -23,6 +23,7 @@ import baritone.cache.CachedRegion; import baritone.cache.WorldData; import baritone.utils.accessor.IChunkProviderClient; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -48,12 +49,21 @@ public class BlockStateInterface { private static final IBlockState AIR = Blocks.AIR.getDefaultState(); public BlockStateInterface(IPlayerContext ctx) { - this(ctx.world(), (WorldData) ctx.worldData()); + this(ctx, false); } - public BlockStateInterface(World world, WorldData worldData) { + public BlockStateInterface(IPlayerContext ctx, boolean copyLoadedChunks) { + this(ctx.world(), (WorldData) ctx.worldData(), copyLoadedChunks); + } + + public BlockStateInterface(World world, WorldData worldData, boolean copyLoadedChunks) { this.worldData = worldData; - this.loadedChunks = ((IChunkProviderClient) world.getChunkProvider()).loadedChunks(); + Long2ObjectMap worldLoaded = ((IChunkProviderClient) world.getChunkProvider()).loadedChunks(); + if (copyLoadedChunks) { + this.loadedChunks = new Long2ObjectOpenHashMap<>(worldLoaded); // make a copy that we can safely access from another thread + } else { + this.loadedChunks = worldLoaded; // this will only be used on the main thread + } if (!Minecraft.getMinecraft().isCallingFromMinecraftThread()) { throw new IllegalStateException(); } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 420f48ba..4b995e82 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -34,6 +34,7 @@ import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.process.CustomGoalProcess; +import baritone.utils.pathing.SegmentedCalculator; import comms.SocketConnection; import net.minecraft.block.Block; import net.minecraft.client.multiplayer.ChunkProviderClient; @@ -208,6 +209,23 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } return true; } + if (msg.equals("fullpath")) { + if (pathingBehavior.getGoal() == null) { + logDirect("No goal."); + } else { + logDirect("Started segmented calculator"); + SegmentedCalculator.calculateSegmentsThreaded(pathingBehavior.pathStart(), pathingBehavior.getGoal(), new CalculationContext(baritone, true), ipath -> { + logDirect("Found a path"); + logDirect("Ends at " + ipath.getDest()); + logDirect("Length " + ipath.length()); + logDirect("Estimated time " + ipath.ticksRemainingFrom(0)); + pathingBehavior.secretCursedFunctionDoNotCall(ipath); // it's okay when *I* do it + }, () -> { + logDirect("Path calculation failed, no path"); + }); + } + return true; + } if (msg.equals("repack") || msg.equals("rescan")) { ChunkProviderClient cli = (ChunkProviderClient) ctx.world().getChunkProvider(); int playerChunkX = ctx.playerFeet().getX() >> 4; @@ -265,6 +283,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { }); return true; } + if (msg.equals("reset")) { + Baritone.settings().reset(); + logDirect("Baritone settings reset"); + return true; + } if (msg.startsWith("followplayers")) { baritone.getFollowProcess().follow(EntityPlayer.class::isInstance); // O P P A logDirect("Following any players"); diff --git a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java index 75dd0282..d3f6703e 100644 --- a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java +++ b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java @@ -23,9 +23,11 @@ import baritone.api.pathing.goals.Goal; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.PathCalculationResult; import baritone.behavior.PathingBehavior; +import baritone.cache.CachedWorld; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.CalculationContext; import baritone.pathing.path.SplicedPath; +import net.minecraft.util.EnumFacing; import java.util.Optional; import java.util.function.Consumer; @@ -52,8 +54,8 @@ public class SegmentedCalculator { PathCalculationResult result = segment(soFar); switch (result.getType()) { case SUCCESS_SEGMENT: + case SUCCESS_TO_GOAL: break; - case SUCCESS_TO_GOAL: // if we've gotten all the way to the goal, we're done case FAILURE: // if path calculation failed, we're done case EXCEPTION: // if path calculation threw an exception, we're done return soFar; @@ -62,13 +64,30 @@ public class SegmentedCalculator { } IPath segment = result.getPath().get(); // path calculation result type is SUCCESS_SEGMENT, so the path must be present IPath combined = soFar.map(previous -> (IPath) SplicedPath.trySplice(previous, segment, true).get()).orElse(segment); + loadAdjacent(combined.getDest().getX(), combined.getDest().getZ()); soFar = Optional.of(combined); + if (result.getType() == PathCalculationResult.Type.SUCCESS_TO_GOAL) { + return soFar; + } + } + } + + private void loadAdjacent(int blockX, int blockZ) { + BetterBlockPos bp = new BetterBlockPos(blockX, 64, blockZ); + CachedWorld cached = (CachedWorld) context.getBaritone().getPlayerContext().worldData().getCachedWorld(); + for (int i = 0; i < 4; i++) { + // pathing thread is not allowed to load new cached regions from disk + // it checks if every chunk is loaded before getting blocks from it + // so you see path segments ending at multiples of 512 (plus or minus one) on either x or z axis + // this loads every adjacent chunk to the segment end, so it can continue into the next cached region + BetterBlockPos toLoad = bp.offset(EnumFacing.byHorizontalIndex(i), 16); + cached.tryLoadFromDisk(toLoad.x >> 9, toLoad.z >> 9); } } private PathCalculationResult segment(Optional previous) { BetterBlockPos segmentStart = previous.map(IPath::getDest).orElse(start); // <-- e p i c - AbstractNodeCostSearch search = PathingBehavior.createPathfinder(segmentStart, goal, previous.orElse(null), context); + AbstractNodeCostSearch search = PathingBehavior.createPathfinder(segmentStart, goal, previous.orElse(null), context, false); return search.calculate(Baritone.settings().primaryTimeoutMS.get(), Baritone.settings().failureTimeoutMS.get()); // use normal time settings, not the plan ahead settings, so as to not overwhelm the computer }