diff --git a/PROTOCOL.md b/PROTOCOL.md new file mode 100644 index 00000000..8713120b --- /dev/null +++ b/PROTOCOL.md @@ -0,0 +1,36 @@ +# Baritone Comms Protocol + +## Data Types + +| Name | Descriptor | Java | +|------------|-----------------------------------------------------------|-----------------------------| +| coordinate | Big endian 8-byte floating point number | [readDouble], [writeDouble] | +| string | unsigned short (length) followed by UTF-8 character bytes | [readUTF], [writeUTF] | + +## Inbound + +Allows the server to execute a chat command on behalf of the client's player + +### Chat + +| Name | Type | +|---------|--------| +| Message | string | + +## Outbound + +Update the player position with the server + +### Status + +| Name | Type | +|------|------------| +| X | coordinate | +| Y | coordinate | +| Z | coordinate | + + +[readUTF]: https://docs.oracle.com/javase/7/docs/api/java/io/DataInputStream.html#readUTF() +[writeUTF]: https://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html#writeUTF(java.lang.String) +[readDouble]: https://docs.oracle.com/javase/7/docs/api/java/io/DataInputStream.html#readDouble() +[writeDouble]: https://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html#writeDouble(double) \ No newline at end of file diff --git a/README.md b/README.md index 445d34bb..9fa8a2c9 100644 --- a/README.md +++ b/README.md @@ -58,13 +58,12 @@ 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.getPathingBehavior().setGoal(new GoalXZ(10000, 20000)); -BaritoneAPI.getPathingBehavior().path(); +BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalXZ(10000, 20000)); ``` # FAQ -## Can I use Baritone as a library in my hacked client? +## Can I use Baritone as a library in my custom utility client? Sure! (As long as usage is in compliance with the LGPL 3 License) diff --git a/build.gradle b/build.gradle index 6b97128a..58c7bf9f 100755 --- a/build.gradle +++ b/build.gradle @@ -51,6 +51,10 @@ compileJava { } sourceSets { + comms {} + main { + compileClasspath += comms.compileClasspath + comms.output + } launch { compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output } @@ -103,7 +107,7 @@ mixin { } jar { - from sourceSets.launch.output, sourceSets.api.output + from sourceSets.comms.output, sourceSets.launch.output, sourceSets.api.output preserveFileTimestamps = false reproducibleFileOrder = true } diff --git a/scripts/proguard.pro b/scripts/proguard.pro index a13a0e3f..270a0631 100644 --- a/scripts/proguard.pro +++ b/scripts/proguard.pro @@ -19,7 +19,7 @@ -keep class baritone.api.IBaritoneProvider # hack --keep class baritone.utils.ExampleBaritoneControl { *; } +-keep class baritone.utils.ExampleBaritoneControl { *; } # have to include this string to remove this keep in the standalone build: # this is the keep api # setting names are reflected from field names, so keep field names -keepclassmembers class baritone.api.Settings { diff --git a/src/api/java/baritone/api/BaritoneAPI.java b/src/api/java/baritone/api/BaritoneAPI.java index b9dbcd04..c1227830 100644 --- a/src/api/java/baritone/api/BaritoneAPI.java +++ b/src/api/java/baritone/api/BaritoneAPI.java @@ -17,16 +17,6 @@ package baritone.api; -import baritone.api.behavior.ILookBehavior; -import baritone.api.behavior.IMemoryBehavior; -import baritone.api.behavior.IPathingBehavior; -import baritone.api.cache.IWorldProvider; -import baritone.api.cache.IWorldScanner; -import baritone.api.event.listener.IGameEventListener; -import baritone.api.process.ICustomGoalProcess; -import baritone.api.process.IFollowProcess; -import baritone.api.process.IGetToBlockProcess; -import baritone.api.process.IMineProcess; import baritone.api.utils.SettingsUtil; import java.util.Iterator; @@ -42,59 +32,23 @@ import java.util.ServiceLoader; */ public final class BaritoneAPI { - private static final IBaritone baritone; + private static final IBaritoneProvider provider; private static final Settings settings; static { ServiceLoader baritoneLoader = ServiceLoader.load(IBaritoneProvider.class); Iterator instances = baritoneLoader.iterator(); - baritone = instances.next().getBaritoneForPlayer(null); // PWNAGE + provider = instances.next(); settings = new Settings(); SettingsUtil.readAndApply(settings); } - public static IFollowProcess getFollowProcess() { - return baritone.getFollowProcess(); - } - - public static ILookBehavior getLookBehavior() { - return baritone.getLookBehavior(); - } - - public static IMemoryBehavior getMemoryBehavior() { - return baritone.getMemoryBehavior(); - } - - public static IMineProcess getMineProcess() { - return baritone.getMineProcess(); - } - - public static IPathingBehavior getPathingBehavior() { - return baritone.getPathingBehavior(); + public static IBaritoneProvider getProvider() { + return BaritoneAPI.provider; } public static Settings getSettings() { - return settings; - } - - public static IWorldProvider getWorldProvider() { - return baritone.getWorldProvider(); - } - - public static IWorldScanner getWorldScanner() { - return baritone.getWorldScanner(); - } - - public static ICustomGoalProcess getCustomGoalProcess() { - return baritone.getCustomGoalProcess(); - } - - public static IGetToBlockProcess getGetToBlockProcess() { - return baritone.getGetToBlockProcess(); - } - - public static void registerEventListener(IGameEventListener listener) { - baritone.registerEventListener(listener); + return BaritoneAPI.settings; } } diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index aee9dead..14805375 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -21,12 +21,14 @@ import baritone.api.behavior.ILookBehavior; import baritone.api.behavior.IMemoryBehavior; import baritone.api.behavior.IPathingBehavior; import baritone.api.cache.IWorldProvider; -import baritone.api.cache.IWorldScanner; -import baritone.api.event.listener.IGameEventListener; +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 @@ -58,6 +60,8 @@ public interface IBaritone { */ IMineProcess getMineProcess(); + IPathingControlManager getPathingControlManager(); + /** * @return The {@link IPathingBehavior} instance * @see IPathingBehavior @@ -70,20 +74,13 @@ public interface IBaritone { */ IWorldProvider getWorldProvider(); - /** - * @return The {@link IWorldScanner} instance - * @see IWorldScanner - */ - IWorldScanner getWorldScanner(); + IInputOverrideHandler getInputOverrideHandler(); ICustomGoalProcess getCustomGoalProcess(); IGetToBlockProcess getGetToBlockProcess(); - /** - * Registers a {@link IGameEventListener} with Baritone's "event bus". - * - * @param listener The listener - */ - void registerEventListener(IGameEventListener listener); + IPlayerContext getPlayerContext(); + + IEventBus getGameEventHandler(); } diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index 745842ce..d17e8e00 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -17,13 +17,34 @@ package baritone.api; +import baritone.api.cache.IWorldScanner; import net.minecraft.client.entity.EntityPlayerSP; +import java.util.List; + /** * @author Leijurv */ 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. + * + * @return The primary {@link IBaritone} instance. + */ + IBaritone getPrimaryBaritone(); + + /** + * Returns all of the active {@link IBaritone} instances. This includes the local one + * returned by {@link #getPrimaryBaritone()}. + * + * @return All active {@link IBaritone} instances. + * @see #getBaritoneForPlayer(EntityPlayerSP) + */ + List getAllBaritones(); + /** * 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. @@ -31,5 +52,20 @@ public interface IBaritoneProvider { * @param player The player * @return The {@link IBaritone} instance. */ - IBaritone getBaritoneForPlayer(EntityPlayerSP player); + 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); + } + + /** + * Returns the {@link IWorldScanner} instance. This is not a type returned by + * {@link IBaritone} implementation, because it is not linked with {@link IBaritone}. + * + * @return The {@link IWorldScanner} instance. + */ + IWorldScanner getWorldScanner(); } diff --git a/src/api/java/baritone/api/Settings.java b/src/api/java/baritone/api/Settings.java index 7fce0254..f4fd7db1 100644 --- a/src/api/java/baritone/api/Settings.java +++ b/src/api/java/baritone/api/Settings.java @@ -247,14 +247,24 @@ public class Settings { public Setting movementTimeoutTicks = new Setting<>(100); /** - * Pathing can never take longer than this + * Pathing ends after this amount of time, if a path has been found */ - public Setting pathTimeoutMS = new Setting<>(2000L); + public Setting primaryTimeoutMS = new Setting<>(500L); /** - * Planning ahead while executing a segment can never take longer than this + * Pathing can never take longer than this, even if that means failing to find any path at all */ - public Setting planAheadTimeoutMS = new Setting<>(4000L); + public Setting failureTimeoutMS = new Setting<>(2000L); + + /** + * Planning ahead while executing a segment ends after this amount of time, if a path has been found + */ + public Setting 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 planAheadFailureTimeoutMS = new Setting<>(5000L); /** * For debugging, consider nodes much much slower diff --git a/src/api/java/baritone/api/behavior/IPathingBehavior.java b/src/api/java/baritone/api/behavior/IPathingBehavior.java index e9ebe405..0f44f2ee 100644 --- a/src/api/java/baritone/api/behavior/IPathingBehavior.java +++ b/src/api/java/baritone/api/behavior/IPathingBehavior.java @@ -71,7 +71,7 @@ public interface IPathingBehavior extends IBehavior { /** * @return The current path finder being executed */ - Optional getPathFinder(); + Optional getInProgress(); /** * @return The current path executor diff --git a/src/api/java/baritone/api/cache/IBlockTypeAccess.java b/src/api/java/baritone/api/cache/IBlockTypeAccess.java index 242ff154..0804a73a 100644 --- a/src/api/java/baritone/api/cache/IBlockTypeAccess.java +++ b/src/api/java/baritone/api/cache/IBlockTypeAccess.java @@ -22,7 +22,7 @@ import net.minecraft.util.math.BlockPos; /** * @author Brady - * @since 8/4/2018 2:01 AM + * @since 8/4/2018 */ public interface IBlockTypeAccess { diff --git a/src/api/java/baritone/api/cache/ICachedWorld.java b/src/api/java/baritone/api/cache/ICachedWorld.java index 5e06a475..a435ebe0 100644 --- a/src/api/java/baritone/api/cache/ICachedWorld.java +++ b/src/api/java/baritone/api/cache/ICachedWorld.java @@ -63,10 +63,12 @@ public interface ICachedWorld { * * @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 maxRegionDistanceSq The maximum region distance, squared * @return The locations found that match the special block */ - LinkedList getLocationsOf(String block, int maximum, int maxRegionDistanceSq); + LinkedList getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq); /** * Reloads all of the cached regions in this world from disk. Anything that is not saved diff --git a/src/api/java/baritone/api/cache/IWorldScanner.java b/src/api/java/baritone/api/cache/IWorldScanner.java index 510e69ed..6d6f49ef 100644 --- a/src/api/java/baritone/api/cache/IWorldScanner.java +++ b/src/api/java/baritone/api/cache/IWorldScanner.java @@ -17,6 +17,7 @@ package baritone.api.cache; +import baritone.api.utils.IPlayerContext; import net.minecraft.block.Block; import net.minecraft.util.math.BlockPos; @@ -31,6 +32,8 @@ 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 @@ -38,5 +41,5 @@ public interface IWorldScanner { * @param maxSearchRadius The maximum chunk search radius * @return The matching block positions */ - List scanChunkRadius(List blocks, int max, int yLevelThreshold, int maxSearchRadius); + List scanChunkRadius(IPlayerContext ctx, List blocks, int max, int yLevelThreshold, int maxSearchRadius); } diff --git a/src/api/java/baritone/api/event/events/ChatEvent.java b/src/api/java/baritone/api/event/events/ChatEvent.java index ede83f24..5ab9f5bb 100644 --- a/src/api/java/baritone/api/event/events/ChatEvent.java +++ b/src/api/java/baritone/api/event/events/ChatEvent.java @@ -22,7 +22,7 @@ import net.minecraft.client.entity.EntityPlayerSP; /** * @author Brady - * @since 8/1/2018 6:39 PM + * @since 8/1/2018 */ public final class ChatEvent extends ManagedPlayerEvent.Cancellable { diff --git a/src/api/java/baritone/api/event/events/ChunkEvent.java b/src/api/java/baritone/api/event/events/ChunkEvent.java index 5c22d830..a74bed17 100644 --- a/src/api/java/baritone/api/event/events/ChunkEvent.java +++ b/src/api/java/baritone/api/event/events/ChunkEvent.java @@ -21,7 +21,7 @@ import baritone.api.event.events.type.EventState; /** * @author Brady - * @since 8/2/2018 12:32 AM + * @since 8/2/2018 */ public final class ChunkEvent { @@ -94,7 +94,16 @@ public final class ChunkEvent { /** * When the chunk is being populated with blocks, tile entities, etc. + *

+ * And it's a full chunk */ - POPULATE + POPULATE_FULL, + + /** + * When the chunk is being populated with blocks, tile entities, etc. + *

+ * And it's a partial chunk + */ + POPULATE_PARTIAL } } diff --git a/src/api/java/baritone/api/event/events/PacketEvent.java b/src/api/java/baritone/api/event/events/PacketEvent.java index 9a3d2315..9b5295ee 100644 --- a/src/api/java/baritone/api/event/events/PacketEvent.java +++ b/src/api/java/baritone/api/event/events/PacketEvent.java @@ -23,7 +23,7 @@ import net.minecraft.network.Packet; /** * @author Brady - * @since 8/6/2018 9:31 PM + * @since 8/6/2018 */ public final class PacketEvent { diff --git a/src/api/java/baritone/api/event/events/RenderEvent.java b/src/api/java/baritone/api/event/events/RenderEvent.java index b5a77276..1f879bfc 100644 --- a/src/api/java/baritone/api/event/events/RenderEvent.java +++ b/src/api/java/baritone/api/event/events/RenderEvent.java @@ -19,7 +19,7 @@ package baritone.api.event.events; /** * @author Brady - * @since 8/5/2018 12:28 AM + * @since 8/5/2018 */ public final class RenderEvent { diff --git a/src/api/java/baritone/api/event/events/WorldEvent.java b/src/api/java/baritone/api/event/events/WorldEvent.java index c7c7e102..2cb0eac5 100644 --- a/src/api/java/baritone/api/event/events/WorldEvent.java +++ b/src/api/java/baritone/api/event/events/WorldEvent.java @@ -22,7 +22,7 @@ import net.minecraft.client.multiplayer.WorldClient; /** * @author Brady - * @since 8/4/2018 3:13 AM + * @since 8/4/2018 */ public final class WorldEvent { diff --git a/src/api/java/baritone/api/event/events/type/Cancellable.java b/src/api/java/baritone/api/event/events/type/Cancellable.java index 62ff9049..ab9707e9 100644 --- a/src/api/java/baritone/api/event/events/type/Cancellable.java +++ b/src/api/java/baritone/api/event/events/type/Cancellable.java @@ -19,7 +19,7 @@ package baritone.api.event.events.type; /** * @author Brady - * @since 8/1/2018 6:41 PM + * @since 8/1/2018 */ public class Cancellable implements ICancellable { diff --git a/src/api/java/baritone/api/event/events/type/EventState.java b/src/api/java/baritone/api/event/events/type/EventState.java index 072e12c1..5f010c30 100644 --- a/src/api/java/baritone/api/event/events/type/EventState.java +++ b/src/api/java/baritone/api/event/events/type/EventState.java @@ -19,7 +19,7 @@ package baritone.api.event.events.type; /** * @author Brady - * @since 8/2/2018 12:34 AM + * @since 8/2/2018 */ public enum EventState { diff --git a/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java b/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java index 6af8e402..c11f926d 100644 --- a/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java +++ b/src/api/java/baritone/api/event/listener/AbstractGameEventListener.java @@ -26,7 +26,7 @@ import baritone.api.event.events.*; * * @author Brady * @see IGameEventListener - * @since 8/1/2018 6:29 PM + * @since 8/1/2018 */ public interface AbstractGameEventListener extends IGameEventListener { diff --git a/src/api/java/baritone/api/event/listener/IEventBus.java b/src/api/java/baritone/api/event/listener/IEventBus.java new file mode 100644 index 00000000..52240a7c --- /dev/null +++ b/src/api/java/baritone/api/event/listener/IEventBus.java @@ -0,0 +1,36 @@ +/* + * 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.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); +} diff --git a/src/api/java/baritone/api/event/listener/IGameEventListener.java b/src/api/java/baritone/api/event/listener/IGameEventListener.java index b1dda0de..c3b4e688 100644 --- a/src/api/java/baritone/api/event/listener/IGameEventListener.java +++ b/src/api/java/baritone/api/event/listener/IGameEventListener.java @@ -33,7 +33,7 @@ import net.minecraft.util.text.ITextComponent; /** * @author Brady - * @since 7/31/2018 11:05 PM + * @since 7/31/2018 */ public interface IGameEventListener { diff --git a/src/api/java/baritone/api/pathing/calc/IPath.java b/src/api/java/baritone/api/pathing/calc/IPath.java index 0844ab90..c3f7fc14 100644 --- a/src/api/java/baritone/api/pathing/calc/IPath.java +++ b/src/api/java/baritone/api/pathing/calc/IPath.java @@ -21,9 +21,9 @@ import baritone.api.Settings; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.movement.IMovement; import baritone.api.utils.BetterBlockPos; -import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import java.util.HashSet; import java.util.List; /** @@ -104,7 +104,7 @@ public interface IPath { * Returns the estimated number of ticks to complete the path from the given node index. * * @param pathPosition The index of the node we're calculating from - * @return The estimated number of ticks remaining frm the given position + * @return The estimated number of ticks remaining from the given position */ default double ticksRemainingFrom(int pathPosition) { double sum = 0; @@ -115,6 +115,15 @@ public interface IPath { return sum; } + /** + * Returns the estimated amount of time needed to complete this path from start to finish + * + * @return The estimated amount of time, in ticks + */ + default double totalTicks() { + return ticksRemainingFrom(0); + } + /** * Cuts off this path at the loaded chunk border, and returns the resulting path. Default * implementation just returns this path, without the intended functionality. @@ -153,9 +162,10 @@ public interface IPath { if (path.size() != movements.size() + 1) { throw new IllegalStateException("Size of path array is unexpected"); } + HashSet seenSoFar = new HashSet<>(); for (int i = 0; i < path.size() - 1; i++) { - BlockPos src = path.get(i); - BlockPos dest = path.get(i + 1); + 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"); @@ -163,6 +173,10 @@ public interface IPath { 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); } } } diff --git a/src/api/java/baritone/api/pathing/calc/IPathFinder.java b/src/api/java/baritone/api/pathing/calc/IPathFinder.java index f70196a6..fa83295f 100644 --- a/src/api/java/baritone/api/pathing/calc/IPathFinder.java +++ b/src/api/java/baritone/api/pathing/calc/IPathFinder.java @@ -36,7 +36,7 @@ public interface IPathFinder { * * @return The final path */ - PathCalculationResult calculate(long timeout); + PathCalculationResult calculate(long primaryTimeout, long failureTimeout); /** * Intended to be called concurrently with calculatePath from a different thread to tell if it's finished yet diff --git a/src/api/java/baritone/api/pathing/calc/IPathingControlManager.java b/src/api/java/baritone/api/pathing/calc/IPathingControlManager.java new file mode 100644 index 00000000..ffaa18b8 --- /dev/null +++ b/src/api/java/baritone/api/pathing/calc/IPathingControlManager.java @@ -0,0 +1,31 @@ +/* + * 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.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 mostRecentInControl(); + + Optional mostRecentCommand(); +} diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index bbbe1595..3f4a02de 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -20,7 +20,6 @@ package baritone.api.pathing.goals; import net.minecraft.util.math.BlockPos; import java.util.Arrays; -import java.util.Optional; /** * Useful for automated combat (retreating specifically) @@ -33,13 +32,13 @@ public class GoalRunAway implements Goal { private final double distanceSq; - private final Optional maintainY; + private final Integer maintainY; public GoalRunAway(double distance, BlockPos... from) { - this(distance, Optional.empty(), from); + this(distance, null, from); } - public GoalRunAway(double distance, Optional maintainY, BlockPos... from) { + public GoalRunAway(double distance, Integer maintainY, BlockPos... from) { if (from.length == 0) { throw new IllegalArgumentException(); } @@ -50,7 +49,7 @@ public class GoalRunAway implements Goal { @Override public boolean isInGoal(int x, int y, int z) { - if (maintainY.isPresent() && maintainY.get() != y) { + if (maintainY != null && maintainY != y) { return false; } for (BlockPos p : from) { @@ -74,16 +73,16 @@ public class GoalRunAway implements Goal { } } min = -min; - if (maintainY.isPresent()) { - min = min * 0.5 + GoalYLevel.calculate(maintainY.get(), y); + if (maintainY != null) { + min = min * 0.6 + GoalYLevel.calculate(maintainY, y) * 1.5; } return min; } @Override public String toString() { - if (maintainY.isPresent()) { - return "GoalRunAwayFromMaintainY y=" + maintainY.get() + ", " + Arrays.asList(from); + if (maintainY != null) { + return "GoalRunAwayFromMaintainY y=" + maintainY + ", " + Arrays.asList(from); } else { return "GoalRunAwayFrom" + Arrays.asList(from); } diff --git a/src/api/java/baritone/api/utils/IInputOverrideHandler.java b/src/api/java/baritone/api/utils/IInputOverrideHandler.java new file mode 100644 index 00000000..69dbbbeb --- /dev/null +++ b/src/api/java/baritone/api/utils/IInputOverrideHandler.java @@ -0,0 +1,39 @@ +/* + * 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.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 { + + default boolean isInputForcedDown(KeyBinding key) { + return isInputForcedDown(Input.getInputForBind(key)); + } + + boolean isInputForcedDown(Input input); + + void setInputForceState(Input input, boolean forced); + + void clearAllKeys(); +} diff --git a/src/api/java/baritone/api/utils/IPlayerContext.java b/src/api/java/baritone/api/utils/IPlayerContext.java new file mode 100644 index 00000000..cd80a7d9 --- /dev/null +++ b/src/api/java/baritone/api/utils/IPlayerContext.java @@ -0,0 +1,92 @@ +/* + * 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.api.utils; + +import baritone.api.cache.IWorldData; +import net.minecraft.block.BlockSlab; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.multiplayer.PlayerControllerMP; +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(); + + PlayerControllerMP 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 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 getSelectedEntity() { + if (objectMouseOver() != null && objectMouseOver().typeOfHit == RayTraceResult.Type.ENTITY) { + return Optional.of(objectMouseOver().entityHit); + } + return Optional.empty(); + } +} diff --git a/src/api/java/baritone/api/utils/PathCalculationResult.java b/src/api/java/baritone/api/utils/PathCalculationResult.java index 69d2a9b3..20aef9de 100644 --- a/src/api/java/baritone/api/utils/PathCalculationResult.java +++ b/src/api/java/baritone/api/utils/PathCalculationResult.java @@ -23,12 +23,27 @@ import java.util.Optional; public class PathCalculationResult { - public final Optional path; - public final Type type; + private final IPath path; + private final Type type; - public PathCalculationResult(Type type, Optional path) { + public PathCalculationResult(Type type) { + this(type, null); + } + + public PathCalculationResult(Type type, IPath path) { this.path = path; this.type = type; + if (type == null) { + throw new IllegalArgumentException("come on"); + } + } + + public final Optional getPath() { + return Optional.ofNullable(this.path); + } + + public final Type getType() { + return this.type; } public enum Type { diff --git a/src/api/java/baritone/api/utils/RayTraceUtils.java b/src/api/java/baritone/api/utils/RayTraceUtils.java index 8b37ef9d..61086f3d 100644 --- a/src/api/java/baritone/api/utils/RayTraceUtils.java +++ b/src/api/java/baritone/api/utils/RayTraceUtils.java @@ -17,22 +17,16 @@ 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 { - private static final Minecraft mc = Minecraft.getMinecraft(); - private RayTraceUtils() {} /** @@ -51,30 +45,6 @@ public final class RayTraceUtils { direction.y * blockReachDistance, direction.z * blockReachDistance ); - 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 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 getSelectedEntity() { - if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.ENTITY) { - return Optional.of(mc.objectMouseOver.entityHit); - } - return Optional.empty(); + return entity.world.rayTraceBlocks(start, end, false, false, true); } } diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index e1726812..20cb0dde 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -17,8 +17,11 @@ 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.entity.Entity; import net.minecraft.util.math.*; @@ -135,8 +138,9 @@ public final class RotationUtils { * @param pos The target block position * @return The optional rotation */ - public static Optional reachable(Entity entity, BlockPos pos, double blockReachDistance) { - if (pos.equals(RayTraceUtils.getSelectedBlock().orElse(null))) { + public static Optional reachable(EntityPlayerSP entity, BlockPos pos, double blockReachDistance) { + IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(entity); + if (pos.equals(baritone.getPlayerContext().getSelectedBlock().orElse(null))) { /* * why add 0.0001? * to indicate that we actually have a desired pitch @@ -203,6 +207,6 @@ public final class RotationUtils { * @return The optional rotation */ public static Optional reachableCenter(Entity entity, BlockPos pos, double blockReachDistance) { - return reachableOffset(entity, pos, VecUtils.calculateBlockCenter(pos), blockReachDistance); + return reachableOffset(entity, pos, VecUtils.calculateBlockCenter(entity.world, pos), blockReachDistance); } } diff --git a/src/api/java/baritone/api/utils/VecUtils.java b/src/api/java/baritone/api/utils/VecUtils.java index 831e0937..090cb9d7 100644 --- a/src/api/java/baritone/api/utils/VecUtils.java +++ b/src/api/java/baritone/api/utils/VecUtils.java @@ -19,21 +19,17 @@ 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() {} @@ -44,9 +40,9 @@ public final class VecUtils { * @return The center of the block's bounding box * @see #getBlockPosCenter(BlockPos) */ - public static Vec3d calculateBlockCenter(BlockPos pos) { - IBlockState b = mc.world.getBlockState(pos); - AxisAlignedBB bbox = b.getBoundingBox(mc.world, pos); + public static Vec3d calculateBlockCenter(World world, BlockPos pos) { + IBlockState b = world.getBlockState(pos); + AxisAlignedBB bbox = b.getBoundingBox(world, pos); double xDiff = (bbox.minX + bbox.maxX) / 2; double yDiff = (bbox.minY + bbox.maxY) / 2; double zDiff = (bbox.minZ + bbox.maxZ) / 2; @@ -68,7 +64,7 @@ public final class VecUtils { * * @param pos The block position * @return The assumed center of the position - * @see #calculateBlockCenter(BlockPos) + * @see #calculateBlockCenter(World, BlockPos) */ public static Vec3d getBlockPosCenter(BlockPos pos) { return new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5); diff --git a/src/api/java/baritone/api/utils/input/Input.java b/src/api/java/baritone/api/utils/input/Input.java new file mode 100644 index 00000000..1e8d44b5 --- /dev/null +++ b/src/api/java/baritone/api/utils/input/Input.java @@ -0,0 +1,119 @@ +/* + * 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.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 bindToInputMap = new HashMap<>(); + + /** + * The actual game {@link KeyBinding} being forced. + */ + private final KeyBinding keyBinding; + + Input(Function 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)); + } +} diff --git a/src/comms/java/comms/BufferedConnection.java b/src/comms/java/comms/BufferedConnection.java new file mode 100644 index 00000000..450010e7 --- /dev/null +++ b/src/comms/java/comms/BufferedConnection.java @@ -0,0 +1,86 @@ +/* + * 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 comms; + +import java.io.EOFException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * Do you not like having a blocking "receiveMessage" thingy? + *

+ * Do you prefer just being able to get a list of all messages received since the last tick? + *

+ * If so, this class is for you! + * + * @author leijurv + */ +public class BufferedConnection implements IConnection { + private final IConnection wrapped; + private final LinkedBlockingQueue queue; + private volatile transient IOException thrownOnRead; + + public BufferedConnection(IConnection wrapped) { + this(wrapped, Integer.MAX_VALUE); // LinkedBlockingQueue accepts this as "no limit" + } + + public BufferedConnection(IConnection wrapped, int maxInternalQueueSize) { + this.wrapped = wrapped; + this.queue = new LinkedBlockingQueue<>(); + this.thrownOnRead = null; + new Thread(() -> { + try { + while (thrownOnRead == null) { + queue.put(wrapped.receiveMessage()); + } + } catch (IOException e) { + thrownOnRead = e; + } catch (InterruptedException e) { + thrownOnRead = new IOException("Interrupted while enqueueing", e); + } + }).start(); + } + + @Override + public void sendMessage(iMessage message) throws IOException { + wrapped.sendMessage(message); + } + + @Override + public iMessage receiveMessage() { + throw new UnsupportedOperationException("BufferedConnection can only be read from non-blockingly"); + } + + @Override + public void close() { + wrapped.close(); + thrownOnRead = new EOFException("Closed"); + } + + public List receiveMessagesNonBlocking() throws IOException { + ArrayList msgs = new ArrayList<>(); + queue.drainTo(msgs); // preserves order -- first message received will be first in this arraylist + if (msgs.isEmpty() && thrownOnRead != null) { + IOException up = new IOException("BufferedConnection wrapped", thrownOnRead); + throw up; + } + return msgs; + } +} diff --git a/src/comms/java/comms/ConstructingDeserializer.java b/src/comms/java/comms/ConstructingDeserializer.java new file mode 100644 index 00000000..5b49ecdb --- /dev/null +++ b/src/comms/java/comms/ConstructingDeserializer.java @@ -0,0 +1,54 @@ +/* + * 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 comms; + +import java.io.DataInputStream; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +public enum ConstructingDeserializer implements MessageDeserializer { + INSTANCE; + private final List> MSGS; + + ConstructingDeserializer() { + MSGS = new ArrayList<>(); + // imagine doing something in reflect but it's actually concise and you don't need to catch 42069 different exceptions. huh. + for (Method m : IMessageListener.class.getDeclaredMethods()) { + if (m.getName().equals("handle")) { + MSGS.add((Class) m.getParameterTypes()[0]); + } + } + } + + @Override + public synchronized iMessage deserialize(DataInputStream in) throws IOException { + int type = ((int) in.readByte()) & 0xff; + try { + return MSGS.get(type).getConstructor(DataInputStream.class).newInstance(in); + } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException ex) { + throw new IOException("Unknown message type " + type, ex); + } + } + + public byte getHeader(Class klass) { + return (byte) MSGS.indexOf(klass); + } +} diff --git a/src/comms/java/comms/IConnection.java b/src/comms/java/comms/IConnection.java new file mode 100644 index 00000000..dc54beb0 --- /dev/null +++ b/src/comms/java/comms/IConnection.java @@ -0,0 +1,28 @@ +/* + * This file is part of Baritone. + * + * Baritone is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Baritone is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Baritone. If not, see . + */ + +package comms; + +import java.io.IOException; + +public interface IConnection { + void sendMessage(iMessage message) throws IOException; + + iMessage receiveMessage() throws IOException; + + void close(); +} diff --git a/src/comms/java/comms/IMessageListener.java b/src/comms/java/comms/IMessageListener.java new file mode 100644 index 00000000..94300f1f --- /dev/null +++ b/src/comms/java/comms/IMessageListener.java @@ -0,0 +1,46 @@ +/* + * 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 comms; + +import comms.downward.MessageChat; +import comms.downward.MessageComputationRequest; +import comms.upward.MessageComputationResponse; +import comms.upward.MessageStatus; + +public interface IMessageListener { + default void handle(MessageStatus message) { + unhandled(message); + } + + default void handle(MessageChat message) { + unhandled(message); + } + + default void handle(MessageComputationRequest message) { + unhandled(message); + } + + default void handle(MessageComputationResponse message) { + unhandled(message); + } + + default void unhandled(iMessage msg) { + // can override this to throw UnsupportedOperationException, if you want to make sure you're handling everything + // default is to silently ignore messages without handlers + } +} \ No newline at end of file diff --git a/src/comms/java/comms/MessageDeserializer.java b/src/comms/java/comms/MessageDeserializer.java new file mode 100644 index 00000000..aece828d --- /dev/null +++ b/src/comms/java/comms/MessageDeserializer.java @@ -0,0 +1,25 @@ +/* + * 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 comms; + +import java.io.DataInputStream; +import java.io.IOException; + +public interface MessageDeserializer { + iMessage deserialize(DataInputStream in) throws IOException; +} diff --git a/src/comms/java/comms/Pipe.java b/src/comms/java/comms/Pipe.java new file mode 100644 index 00000000..c189af60 --- /dev/null +++ b/src/comms/java/comms/Pipe.java @@ -0,0 +1,99 @@ +/* + * 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 comms; + +import java.io.EOFException; +import java.io.IOException; +import java.util.Optional; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * Do you want a socket to localhost without actually making a gross real socket to localhost? + */ +public class Pipe { + private final LinkedBlockingQueue> AtoB; + private final LinkedBlockingQueue> BtoA; + private final PipedConnection A; + private final PipedConnection B; + private volatile boolean closed; + + public Pipe() { + this.AtoB = new LinkedBlockingQueue<>(); + this.BtoA = new LinkedBlockingQueue<>(); + this.A = new PipedConnection(BtoA, AtoB); + this.B = new PipedConnection(AtoB, BtoA); + } + + public PipedConnection getA() { + return A; + } + + public PipedConnection getB() { + return B; + } + + public class PipedConnection implements IConnection { + private final LinkedBlockingQueue> in; + private final LinkedBlockingQueue> out; + + private PipedConnection(LinkedBlockingQueue> in, LinkedBlockingQueue> out) { + this.in = in; + this.out = out; + } + + @Override + public void sendMessage(iMessage message) throws IOException { + if (closed) { + throw new EOFException("Closed"); + } + try { + out.put(Optional.of(message)); + } catch (InterruptedException e) { + // this can never happen since the LinkedBlockingQueues are not constructed with a maximum capacity, see above + } + } + + @Override + public iMessage receiveMessage() throws IOException { + if (closed) { + throw new EOFException("Closed"); + } + try { + Optional t = in.take(); + if (!t.isPresent()) { + throw new EOFException("Closed"); + } + return t.get(); + } catch (InterruptedException e) { + // again, cannot happen + // but we have to throw something + throw new IllegalStateException(e); + } + } + + @Override + public void close() { + closed = true; + try { + AtoB.put(Optional.empty()); // unstick threads + BtoA.put(Optional.empty()); + } catch (InterruptedException e) { + } + } + } +} diff --git a/src/comms/java/comms/SerializedConnection.java b/src/comms/java/comms/SerializedConnection.java new file mode 100644 index 00000000..c4191194 --- /dev/null +++ b/src/comms/java/comms/SerializedConnection.java @@ -0,0 +1,59 @@ +/* + * 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 comms; + +import java.io.*; + +public class SerializedConnection implements IConnection { + private final DataInputStream in; + private final DataOutputStream out; + private final MessageDeserializer deserializer; + + public SerializedConnection(InputStream in, OutputStream out) { + this(ConstructingDeserializer.INSTANCE, in, out); + } + + public SerializedConnection(MessageDeserializer d, InputStream in, OutputStream out) { + this.in = new DataInputStream(in); + this.out = new DataOutputStream(out); + this.deserializer = d; + } + + @Override + public synchronized void sendMessage(iMessage message) throws IOException { + message.writeHeader(out); + message.write(out); + } + + @Override + public iMessage receiveMessage() throws IOException { + return deserializer.deserialize(in); + } + + @Override + public void close() { + try { + in.close(); + } catch (IOException e) { + } + try { + out.close(); + } catch (IOException e) { + } + } +} \ No newline at end of file diff --git a/src/comms/java/comms/SocketConnection.java b/src/comms/java/comms/SocketConnection.java new file mode 100644 index 00000000..e40d5a1a --- /dev/null +++ b/src/comms/java/comms/SocketConnection.java @@ -0,0 +1,27 @@ +/* + * 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 comms; + +import java.io.IOException; +import java.net.Socket; + +public class SocketConnection extends SerializedConnection { + public SocketConnection(Socket s) throws IOException { + super(s.getInputStream(), s.getOutputStream()); + } +} diff --git a/src/comms/java/comms/downward/MessageChat.java b/src/comms/java/comms/downward/MessageChat.java new file mode 100644 index 00000000..b04d2a31 --- /dev/null +++ b/src/comms/java/comms/downward/MessageChat.java @@ -0,0 +1,48 @@ +/* + * 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 comms.downward; + +import comms.IMessageListener; +import comms.iMessage; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +public class MessageChat implements iMessage { + + public final String msg; + + public MessageChat(DataInputStream in) throws IOException { + this.msg = in.readUTF(); + } + + public MessageChat(String msg) { + this.msg = msg; + } + + @Override + public void write(DataOutputStream out) throws IOException { + out.writeUTF(msg); + } + + @Override + public void handle(IMessageListener listener) { + listener.handle(this); + } +} diff --git a/src/comms/java/comms/downward/MessageComputationRequest.java b/src/comms/java/comms/downward/MessageComputationRequest.java new file mode 100644 index 00000000..065c27a2 --- /dev/null +++ b/src/comms/java/comms/downward/MessageComputationRequest.java @@ -0,0 +1,62 @@ +/* + * 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 comms.downward; + +import comms.IMessageListener; +import comms.iMessage; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +public class MessageComputationRequest implements iMessage { + public final long computationID; + public final int startX; + public final int startY; + public final int startZ; + public final String goal; // TODO find a better way to do this lol + + public MessageComputationRequest(DataInputStream in) throws IOException { + this.computationID = in.readLong(); + this.startX = in.readInt(); + this.startY = in.readInt(); + this.startZ = in.readInt(); + this.goal = in.readUTF(); + } + + public MessageComputationRequest(long computationID, int startX, int startY, int startZ, String goal) { + this.computationID = computationID; + this.startX = startX; + this.startY = startY; + this.startZ = startZ; + this.goal = goal; + } + + @Override + public void write(DataOutputStream out) throws IOException { + out.writeLong(computationID); + out.writeInt(startX); + out.writeInt(startY); + out.writeUTF(goal); + } + + @Override + public void handle(IMessageListener listener) { + listener.handle(this); + } +} diff --git a/src/comms/java/comms/iMessage.java b/src/comms/java/comms/iMessage.java new file mode 100644 index 00000000..67ec2965 --- /dev/null +++ b/src/comms/java/comms/iMessage.java @@ -0,0 +1,44 @@ +/* + * 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 comms; + +import java.io.DataOutputStream; +import java.io.IOException; + +/** + * hell yeah + *

+ *

+ * dumb android users cant read this file + *

+ * + * @author leijurv + */ +public interface iMessage { + void write(DataOutputStream out) throws IOException; + + default void writeHeader(DataOutputStream out) throws IOException { + out.writeByte(getHeader()); + } + + default byte getHeader() { + return ConstructingDeserializer.INSTANCE.getHeader(getClass()); + } + + void handle(IMessageListener listener); +} diff --git a/src/comms/java/comms/upward/MessageComputationResponse.java b/src/comms/java/comms/upward/MessageComputationResponse.java new file mode 100644 index 00000000..60118979 --- /dev/null +++ b/src/comms/java/comms/upward/MessageComputationResponse.java @@ -0,0 +1,72 @@ +/* + * 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 comms.upward; + +import comms.IMessageListener; +import comms.iMessage; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +public class MessageComputationResponse implements iMessage { + public final long computationID; + public final int pathLength; + public final double pathCost; + public final boolean endsInGoal; + public final int endX; + public final int endY; + public final int endZ; + + public MessageComputationResponse(DataInputStream in) throws IOException { + this.computationID = in.readLong(); + this.pathLength = in.readInt(); + this.pathCost = in.readDouble(); + this.endsInGoal = in.readBoolean(); + this.endX = in.readInt(); + this.endY = in.readInt(); + this.endZ = in.readInt(); + } + + public MessageComputationResponse(long computationID, int pathLength, double pathCost, boolean endsInGoal, int endX, int endY, int endZ) { + this.computationID = computationID; + this.pathLength = pathLength; + this.pathCost = pathCost; + this.endsInGoal = endsInGoal; + this.endX = endX; + this.endY = endY; + this.endZ = endZ; + } + + @Override + public void write(DataOutputStream out) throws IOException { + out.writeLong(computationID); + out.writeInt(pathLength); + out.writeDouble(pathCost); + out.writeBoolean(endsInGoal); + out.writeInt(endX); + out.writeInt(endY); + out.writeInt(endZ); + } + + @Override + public void handle(IMessageListener listener) { + listener.handle(this); + } +} + diff --git a/src/comms/java/comms/upward/MessageStatus.java b/src/comms/java/comms/upward/MessageStatus.java new file mode 100644 index 00000000..53786a01 --- /dev/null +++ b/src/comms/java/comms/upward/MessageStatus.java @@ -0,0 +1,124 @@ +/* + * 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 comms.upward; + +import comms.IMessageListener; +import comms.iMessage; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +public class MessageStatus implements iMessage { + + public final double x; + public final double y; + public final double z; + public final float yaw; + public final float pitch; + public final boolean onGround; + public final float health; + public final float saturation; + public final int foodLevel; + public final int pathStartX; + public final int pathStartY; + public final int pathStartZ; + public final boolean hasCurrentSegment; + public final boolean hasNextSegment; + public final boolean calcInProgress; + public final double ticksRemainingInCurrent; + public final boolean calcFailedLastTick; + public final boolean safeToCancel; + public final String currentGoal; + public final String currentProcess; + + public MessageStatus(DataInputStream in) throws IOException { + this.x = in.readDouble(); + this.y = in.readDouble(); + this.z = in.readDouble(); + this.yaw = in.readFloat(); + this.pitch = in.readFloat(); + this.onGround = in.readBoolean(); + this.health = in.readFloat(); + this.saturation = in.readFloat(); + this.foodLevel = in.readInt(); + this.pathStartX = in.readInt(); + this.pathStartY = in.readInt(); + this.pathStartZ = in.readInt(); + this.hasCurrentSegment = in.readBoolean(); + this.hasNextSegment = in.readBoolean(); + this.calcInProgress = in.readBoolean(); + this.ticksRemainingInCurrent = in.readDouble(); + this.calcFailedLastTick = in.readBoolean(); + this.safeToCancel = in.readBoolean(); + this.currentGoal = in.readUTF(); + this.currentProcess = in.readUTF(); + } + + public MessageStatus(double x, double y, double z, float yaw, float pitch, boolean onGround, float health, float saturation, int foodLevel, int pathStartX, int pathStartY, int pathStartZ, boolean hasCurrentSegment, boolean hasNextSegment, boolean calcInProgress, double ticksRemainingInCurrent, boolean calcFailedLastTick, boolean safeToCancel, String currentGoal, String currentProcess) { + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + this.onGround = onGround; + this.health = health; + this.saturation = saturation; + this.foodLevel = foodLevel; + this.pathStartX = pathStartX; + this.pathStartY = pathStartY; + this.pathStartZ = pathStartZ; + this.hasCurrentSegment = hasCurrentSegment; + this.hasNextSegment = hasNextSegment; + this.calcInProgress = calcInProgress; + this.ticksRemainingInCurrent = ticksRemainingInCurrent; + this.calcFailedLastTick = calcFailedLastTick; + this.safeToCancel = safeToCancel; + this.currentGoal = currentGoal; + this.currentProcess = currentProcess; + } + + @Override + public void write(DataOutputStream out) throws IOException { + out.writeDouble(x); + out.writeDouble(y); + out.writeDouble(z); + out.writeFloat(yaw); + out.writeFloat(pitch); + out.writeBoolean(onGround); + out.writeFloat(health); + out.writeFloat(saturation); + out.writeInt(foodLevel); + out.writeInt(pathStartX); + out.writeInt(pathStartY); + out.writeInt(pathStartZ); + out.writeBoolean(hasCurrentSegment); + out.writeBoolean(hasNextSegment); + out.writeBoolean(calcInProgress); + out.writeDouble(ticksRemainingInCurrent); + out.writeBoolean(calcFailedLastTick); + out.writeBoolean(safeToCancel); + out.writeUTF(currentGoal); + out.writeUTF(currentProcess); + } + + @Override + public void handle(IMessageListener listener) { + listener.handle(this); + } +} diff --git a/src/launch/java/baritone/launch/BaritoneTweaker.java b/src/launch/java/baritone/launch/BaritoneTweaker.java index e78da09f..b9db9b6a 100644 --- a/src/launch/java/baritone/launch/BaritoneTweaker.java +++ b/src/launch/java/baritone/launch/BaritoneTweaker.java @@ -29,7 +29,7 @@ import java.util.List; /** * @author Brady - * @since 7/31/2018 9:59 PM + * @since 7/31/2018 */ public class BaritoneTweaker extends SimpleTweaker { diff --git a/src/launch/java/baritone/launch/mixins/MixinChunkProviderClient.java b/src/launch/java/baritone/launch/mixins/MixinChunkProviderClient.java new file mode 100644 index 00000000..b4cada6e --- /dev/null +++ b/src/launch/java/baritone/launch/mixins/MixinChunkProviderClient.java @@ -0,0 +1,39 @@ +/* + * 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.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 loadedChunks; + + @Override + public Long2ObjectMap loadedChunks() { + return this.loadedChunks; + } +} diff --git a/src/launch/java/baritone/launch/mixins/MixinEntity.java b/src/launch/java/baritone/launch/mixins/MixinEntity.java index 8ca1743f..fe498202 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntity.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntity.java @@ -17,7 +17,7 @@ package baritone.launch.mixins; -import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.event.events.RotationMoveEvent; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.Entity; @@ -53,7 +53,7 @@ public class MixinEntity { // noinspection ConstantConditions if (EntityPlayerSP.class.isInstance(this)) { this.motionUpdateRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw); - Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(this.motionUpdateRotationEvent); + BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.motionUpdateRotationEvent); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java index 8e2eb515..1a7d298f 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -17,7 +17,7 @@ package baritone.launch.mixins; -import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.event.events.RotationMoveEvent; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.Entity; @@ -56,7 +56,7 @@ public abstract class MixinEntityLivingBase extends Entity { // noinspection ConstantConditions if (EntityPlayerSP.class.isInstance(this)) { this.jumpRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.JUMP, this.rotationYaw); - Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent); + BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index a180df5c..9c9509f0 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -17,11 +17,11 @@ package baritone.launch.mixins; -import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.behavior.IPathingBehavior; 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 5:06 PM + * @since 8/1/2018 */ @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); - Baritone.INSTANCE.getGameEventHandler().onSendChatMessage(event); + BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onSendChatMessage(event); if (event.isCancelled()) { ci.cancel(); } @@ -60,7 +60,7 @@ public class MixinEntityPlayerSP { ) ) private void onPreUpdate(CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.PRE)); + BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.PRE)); } @Inject( @@ -73,7 +73,7 @@ public class MixinEntityPlayerSP { ) ) private void onPostUpdate(CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST)); + BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST)); } @Redirect( @@ -84,7 +84,7 @@ public class MixinEntityPlayerSP { ) ) private boolean isAllowFlying(PlayerCapabilities capabilities) { - PathingBehavior pathingBehavior = Baritone.INSTANCE.getPathingBehavior(); + IPathingBehavior pathingBehavior = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getPathingBehavior(); return !pathingBehavior.isPathing() && capabilities.allowFlying; } } diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java b/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java index 174b9e3c..dfd01e46 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java @@ -17,7 +17,8 @@ package baritone.launch.mixins; -import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; import baritone.api.event.events.RenderEvent; import net.minecraft.client.renderer.EntityRenderer; import org.spongepowered.asm.mixin.Mixin; @@ -37,6 +38,8 @@ public class MixinEntityRenderer { ) ) private void renderWorldPass(int pass, float partialTicks, long finishTimeNano, CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks)); + for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { + ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks)); + } } } diff --git a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java index c776d228..5859d3c5 100644 --- a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java +++ b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java @@ -17,7 +17,7 @@ package baritone.launch.mixins; -import baritone.Baritone; +import baritone.api.BaritoneAPI; import net.minecraft.client.settings.KeyBinding; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -26,7 +26,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; /** * @author Brady - * @since 7/31/2018 11:44 PM + * @since 7/31/2018 */ @Mixin(KeyBinding.class) public class MixinKeyBinding { @@ -37,7 +37,8 @@ public class MixinKeyBinding { cancellable = true ) private void isKeyDown(CallbackInfoReturnable cir) { - if (Baritone.INSTANCE.getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this)) { + // only the primary baritone forces keys + if (BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this)) { cir.setReturnValue(true); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index 3826f0d7..12e91574 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -18,6 +18,8 @@ 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; @@ -42,7 +44,7 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture; /** * @author Brady - * @since 7/31/2018 10:51 PM + * @since 7/31/2018 */ @Mixin(Minecraft.class) public class MixinMinecraft { @@ -57,7 +59,7 @@ public class MixinMinecraft { at = @At("RETURN") ) private void postInit(CallbackInfo ci) { - Baritone.INSTANCE.init(); + ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).init(); } @Inject( @@ -83,12 +85,15 @@ public class MixinMinecraft { ) ) private void runTick(CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onTick(new TickEvent( - EventState.PRE, - (player != null && world != null) - ? TickEvent.Type.IN - : TickEvent.Type.OUT - )); + 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)); + } + } @Inject( @@ -96,7 +101,8 @@ public class MixinMinecraft { at = @At("HEAD") ) private void runTickKeyboard(CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onProcessKeyBinds(); + // keyboard input is only the primary baritone + BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onProcessKeyBinds(); } @Inject( @@ -109,7 +115,9 @@ public class MixinMinecraft { return; } - Baritone.INSTANCE.getGameEventHandler().onWorldEvent( + // mc.world changing is only the primary baritone + + BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onWorldEvent( new WorldEvent( world, EventState.PRE @@ -124,7 +132,8 @@ 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 - Baritone.INSTANCE.getGameEventHandler().onWorldEvent( + // mc.world changing is only the primary baritone + BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onWorldEvent( new WorldEvent( world, EventState.POST @@ -141,7 +150,8 @@ public class MixinMinecraft { ) ) private boolean isAllowUserInput(GuiScreen screen) { - return (Baritone.INSTANCE.getPathingBehavior().getCurrent() != null && player != null) || screen.allowUserInput; + // allow user input is only the primary baritone + return (BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().getCurrent() != null && player != null) || screen.allowUserInput; } @Inject( @@ -153,7 +163,8 @@ public class MixinMinecraft { locals = LocalCapture.CAPTURE_FAILHARD ) private void onBlockBreak(CallbackInfo ci, BlockPos pos) { - Baritone.INSTANCE.getGameEventHandler().onBlockInteract(new BlockInteractEvent(pos, BlockInteractEvent.Type.BREAK)); + // clickMouse is only for the main player + BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(pos, BlockInteractEvent.Type.BREAK)); } @Inject( @@ -165,6 +176,7 @@ 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) { - Baritone.INSTANCE.getGameEventHandler().onBlockInteract(new BlockInteractEvent(blockpos, BlockInteractEvent.Type.USE)); + // rightClickMouse is only for the main player + BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(blockpos, BlockInteractEvent.Type.USE)); } } diff --git a/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java b/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java index 498b5aff..e2cc9842 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java @@ -17,7 +17,8 @@ package baritone.launch.mixins; -import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; import baritone.api.event.events.ChunkEvent; import baritone.api.event.events.type.EventState; import net.minecraft.client.network.NetHandlerPlayClient; @@ -30,7 +31,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /** * @author Brady - * @since 8/3/2018 12:54 AM + * @since 8/3/2018 */ @Mixin(NetHandlerPlayClient.class) public class MixinNetHandlerPlayClient { @@ -43,14 +44,18 @@ public class MixinNetHandlerPlayClient { ) ) private void preRead(SPacketChunkData packetIn, CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onChunkEvent( - new ChunkEvent( - EventState.PRE, - ChunkEvent.Type.POPULATE, - packetIn.getChunkX(), - packetIn.getChunkZ() - ) - ); + 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() + ) + ); + } + } } @Inject( @@ -58,14 +63,18 @@ public class MixinNetHandlerPlayClient { at = @At("RETURN") ) private void postHandleChunkData(SPacketChunkData packetIn, CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onChunkEvent( - new ChunkEvent( - EventState.POST, - ChunkEvent.Type.POPULATE, - packetIn.getChunkX(), - packetIn.getChunkZ() - ) - ); + 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() + ) + ); + } + } } @Inject( @@ -76,6 +85,10 @@ public class MixinNetHandlerPlayClient { ) ) private void onPlayerDeath(SPacketCombatEvent packetIn, CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onPlayerDeath(); + for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { + if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) { + ibaritone.getGameEventHandler().onPlayerDeath(); + } + } } } diff --git a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java index bf15bfc3..577be96d 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java @@ -17,7 +17,8 @@ package baritone.launch.mixins; -import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; import baritone.api.event.events.PacketEvent; import baritone.api.event.events.type.EventState; import io.netty.channel.Channel; @@ -36,7 +37,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /** * @author Brady - * @since 8/6/2018 9:30 PM + * @since 8/6/2018 */ @Mixin(NetworkManager.class) public class MixinNetworkManager { @@ -53,8 +54,14 @@ public class MixinNetworkManager { at = @At("HEAD") ) private void preDispatchPacket(Packet inPacket, final GenericFutureListener>[] futureListeners, CallbackInfo ci) { - if (this.direction == EnumPacketDirection.CLIENTBOUND) { - Baritone.INSTANCE.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, inPacket)); + 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)); + } } } @@ -63,8 +70,14 @@ public class MixinNetworkManager { at = @At("RETURN") ) private void postDispatchPacket(Packet inPacket, final GenericFutureListener>[] futureListeners, CallbackInfo ci) { - if (this.direction == EnumPacketDirection.CLIENTBOUND) { - Baritone.INSTANCE.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, inPacket)); + 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)); + } } } @@ -76,8 +89,13 @@ public class MixinNetworkManager { ) ) private void preProcessPacket(ChannelHandlerContext context, Packet packet, CallbackInfo ci) { - if (this.direction == EnumPacketDirection.CLIENTBOUND) { - Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, packet)); + 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)); + } } } @@ -86,8 +104,13 @@ public class MixinNetworkManager { at = @At("RETURN") ) private void postProcessPacket(ChannelHandlerContext context, Packet packet, CallbackInfo ci) { - if (this.channel.isOpen() && this.direction == EnumPacketDirection.CLIENTBOUND) { - Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, packet)); + 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)); + } } } } diff --git a/src/launch/java/baritone/launch/mixins/MixinWorldClient.java b/src/launch/java/baritone/launch/mixins/MixinWorldClient.java index 322239b7..7c156163 100644 --- a/src/launch/java/baritone/launch/mixins/MixinWorldClient.java +++ b/src/launch/java/baritone/launch/mixins/MixinWorldClient.java @@ -17,7 +17,8 @@ package baritone.launch.mixins; -import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.IBaritone; import baritone.api.event.events.ChunkEvent; import baritone.api.event.events.type.EventState; import net.minecraft.client.multiplayer.WorldClient; @@ -28,7 +29,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /** * @author Brady - * @since 8/2/2018 12:41 AM + * @since 8/2/2018 */ @Mixin(WorldClient.class) public class MixinWorldClient { @@ -38,14 +39,19 @@ public class MixinWorldClient { at = @At("HEAD") ) private void preDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onChunkEvent( - new ChunkEvent( - EventState.PRE, - loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD, - chunkX, - chunkZ - ) - ); + 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 + ) + ); + } + } + } @Inject( @@ -53,13 +59,17 @@ public class MixinWorldClient { at = @At("RETURN") ) private void postDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onChunkEvent( - new ChunkEvent( - EventState.POST, - loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD, - chunkX, - chunkZ - ) - ); + 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 + ) + ); + } + } } } diff --git a/src/launch/resources/mixins.baritone.json b/src/launch/resources/mixins.baritone.json index 9ea70330..09ebbafd 100644 --- a/src/launch/resources/mixins.baritone.json +++ b/src/launch/resources/mixins.baritone.json @@ -10,6 +10,7 @@ "client": [ "MixinAnvilChunkLoader", "MixinBlockPos", + "MixinChunkProviderClient", "MixinChunkProviderServer", "MixinEntity", "MixinEntityLivingBase", diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index f4546012..7ee40e55 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -20,13 +20,10 @@ package baritone; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; -import baritone.api.event.listener.IGameEventListener; -import baritone.behavior.Behavior; -import baritone.behavior.LookBehavior; -import baritone.behavior.MemoryBehavior; -import baritone.behavior.PathingBehavior; +import baritone.api.event.listener.IEventBus; +import baritone.api.utils.IPlayerContext; +import baritone.behavior.*; import baritone.cache.WorldProvider; -import baritone.cache.WorldScanner; import baritone.event.GameEventHandler; import baritone.process.CustomGoalProcess; import baritone.process.FollowProcess; @@ -36,6 +33,7 @@ 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; @@ -50,14 +48,9 @@ import java.util.concurrent.TimeUnit; /** * @author Brady - * @since 7/31/2018 10:50 PM + * @since 7/31/2018 */ -public enum Baritone implements IBaritone { - - /** - * Singleton instance of this class - */ - INSTANCE; +public class Baritone implements IBaritone { private static ThreadPoolExecutor threadPool; private static File dir; @@ -81,6 +74,7 @@ public enum Baritone implements IBaritone { private GameEventHandler gameEventHandler; private List behaviors; + private ControllerBehavior controllerBehavior; private PathingBehavior pathingBehavior; private LookBehavior lookBehavior; private MemoryBehavior memoryBehavior; @@ -93,6 +87,7 @@ public enum Baritone implements IBaritone { private PathingControlManager pathingControlManager; + private IPlayerContext playerContext; private WorldProvider worldProvider; Baritone() { @@ -104,9 +99,13 @@ public enum Baritone implements IBaritone { return; } + // Define this before behaviors try and get it, or else it will be null and the builds will fail! + this.playerContext = PrimaryPlayerContext.INSTANCE; + this.behaviors = new ArrayList<>(); { // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist + controllerBehavior = new ControllerBehavior(this); pathingBehavior = new PathingBehavior(this); lookBehavior = new LookBehavior(this); memoryBehavior = new MemoryBehavior(this); @@ -125,81 +124,87 @@ public enum Baritone implements IBaritone { this.worldProvider = new WorldProvider(); if (BaritoneAutoTest.ENABLE_AUTO_TEST) { - registerEventListener(BaritoneAutoTest.INSTANCE); + this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE); } this.initialized = true; } - public PathingControlManager getPathingControlManager() { - return pathingControlManager; - } - - public IGameEventListener getGameEventHandler() { - return this.gameEventHandler; - } - - public InputOverrideHandler getInputOverrideHandler() { - return this.inputOverrideHandler; - } - public List getBehaviors() { return this.behaviors; } public void registerBehavior(Behavior behavior) { this.behaviors.add(behavior); - this.registerEventListener(behavior); + this.gameEventHandler.registerEventListener(behavior); + } + + @Override + public PathingControlManager getPathingControlManager() { + return this.pathingControlManager; + } + + @Override + public InputOverrideHandler getInputOverrideHandler() { + return this.inputOverrideHandler; + } + + public ControllerBehavior getControllerBehavior() { + return this.controllerBehavior; } @Override public CustomGoalProcess getCustomGoalProcess() { // Iffy - return customGoalProcess; + return this.customGoalProcess; } @Override public GetToBlockProcess getGetToBlockProcess() { // Iffy - return getToBlockProcess; - } - - @Override - public FollowProcess getFollowProcess() { - return followProcess; - } - - @Override - public LookBehavior getLookBehavior() { - return lookBehavior; - } - - @Override - public MemoryBehavior getMemoryBehavior() { - return memoryBehavior; - } - - @Override - public MineProcess getMineProcess() { - return mineProcess; + return this.getToBlockProcess; } @Override public PathingBehavior getPathingBehavior() { - return pathingBehavior; + return this.pathingBehavior; + } + + @Override + public MemoryBehavior getMemoryBehavior() { + return this.memoryBehavior; + } + + @Override + public IPlayerContext getPlayerContext() { + return this.playerContext; + } + + @Override + public FollowProcess getFollowProcess() { + return this.followProcess; } @Override public WorldProvider getWorldProvider() { - return worldProvider; + return this.worldProvider; } @Override - public WorldScanner getWorldScanner() { - return WorldScanner.INSTANCE; + public IEventBus getGameEventHandler() { + return this.gameEventHandler; } @Override - public void registerEventListener(IGameEventListener listener) { - this.gameEventHandler.registerEventListener(listener); + public LookBehavior getLookBehavior() { + return this.lookBehavior; + } + + @Override + public MineProcess getMineProcess() { + return this.mineProcess; + } + + public static Executor getExecutor() { + return threadPool; } public static Settings settings() { @@ -209,8 +214,4 @@ public enum Baritone implements IBaritone { public static File getDir() { return dir; } - - public static Executor getExecutor() { - return threadPool; - } } diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index a80dfe5e..73e5e6e5 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -19,15 +19,33 @@ package baritone; import baritone.api.IBaritone; import baritone.api.IBaritoneProvider; -import net.minecraft.client.entity.EntityPlayerSP; +import baritone.api.cache.IWorldScanner; +import baritone.cache.WorldScanner; + +import java.util.Collections; +import java.util.List; /** * @author Brady * @since 9/29/2018 */ public final class BaritoneProvider implements IBaritoneProvider { + + private final Baritone primary = new Baritone(); + @Override - public IBaritone getBaritoneForPlayer(EntityPlayerSP player) { - return Baritone.INSTANCE; // pwnage + public IBaritone getPrimaryBaritone() { + return primary; + } + + @Override + public List getAllBaritones() { + // TODO return a CopyOnWriteArrayList + return Collections.singletonList(primary); + } + + @Override + public IWorldScanner getWorldScanner() { + return WorldScanner.INSTANCE; } } diff --git a/src/main/java/baritone/behavior/Behavior.java b/src/main/java/baritone/behavior/Behavior.java index 66434d7a..36273c02 100644 --- a/src/main/java/baritone/behavior/Behavior.java +++ b/src/main/java/baritone/behavior/Behavior.java @@ -19,19 +19,22 @@ 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. * * @author Brady - * @since 8/1/2018 6:29 PM + * @since 8/1/2018 */ public class Behavior implements IBehavior { public final Baritone baritone; + public final IPlayerContext ctx; protected Behavior(Baritone baritone) { this.baritone = baritone; + this.ctx = baritone.getPlayerContext(); baritone.registerBehavior(this); } } diff --git a/src/main/java/baritone/behavior/ControllerBehavior.java b/src/main/java/baritone/behavior/ControllerBehavior.java new file mode 100644 index 00000000..405ccc4d --- /dev/null +++ b/src/main/java/baritone/behavior/ControllerBehavior.java @@ -0,0 +1,173 @@ +/* + * 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.behavior; + +import baritone.Baritone; +import baritone.api.event.events.ChatEvent; +import baritone.api.event.events.TickEvent; +import baritone.api.pathing.calc.IPath; +import baritone.api.pathing.goals.Goal; +import baritone.api.pathing.goals.GoalYLevel; +import baritone.api.process.IBaritoneProcess; +import baritone.api.utils.BetterBlockPos; +import baritone.pathing.movement.CalculationContext; +import baritone.utils.Helper; +import baritone.utils.pathing.SegmentedCalculator; +import comms.BufferedConnection; +import comms.IConnection; +import comms.IMessageListener; +import comms.downward.MessageChat; +import comms.downward.MessageComputationRequest; +import comms.iMessage; +import comms.upward.MessageComputationResponse; +import comms.upward.MessageStatus; +import net.minecraft.util.math.BlockPos; + +import java.io.IOException; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +public class ControllerBehavior extends Behavior implements IMessageListener { + + public ControllerBehavior(Baritone baritone) { + super(baritone); + } + + private BufferedConnection conn; + + @Override + public void onTick(TickEvent event) { + if (event.getType() == TickEvent.Type.OUT) { + return; + } + trySend(buildStatus()); + readAndHandle(); + } + + public MessageStatus buildStatus() { + // TODO report inventory and echest contents + // TODO figure out who should remember echest contents when it isn't open, baritone or tenor? + BlockPos pathStart = baritone.getPathingBehavior().pathStart(); + return new MessageStatus( + ctx.player().posX, + ctx.player().posY, + ctx.player().posZ, + ctx.player().rotationYaw, + ctx.player().rotationPitch, + ctx.player().onGround, + ctx.player().getHealth(), + ctx.player().getFoodStats().getSaturationLevel(), + ctx.player().getFoodStats().getFoodLevel(), + pathStart.getX(), + pathStart.getY(), + pathStart.getZ(), + baritone.getPathingBehavior().getCurrent() != null, + baritone.getPathingBehavior().getNext() != null, + baritone.getPathingBehavior().getInProgress().isPresent(), + baritone.getPathingBehavior().ticksRemainingInSegment().orElse(0D), + baritone.getPathingBehavior().calcFailedLastTick(), + baritone.getPathingBehavior().isSafeToCancel(), + baritone.getPathingBehavior().getGoal() + "", + baritone.getPathingControlManager().mostRecentInControl().map(IBaritoneProcess::displayName).orElse("") + ); + } + + private void readAndHandle() { + if (conn == null) { + return; + } + try { + List msgs = conn.receiveMessagesNonBlocking(); + msgs.forEach(msg -> msg.handle(this)); + } catch (IOException e) { + e.printStackTrace(); + disconnect(); + } + } + + public boolean trySend(iMessage msg) { + if (conn == null) { + return false; + } + try { + conn.sendMessage(msg); + return true; + } catch (IOException e) { + e.printStackTrace(); + disconnect(); + return false; + } + } + + public void connectTo(IConnection conn) { + disconnect(); + if (conn instanceof BufferedConnection) { + this.conn = (BufferedConnection) conn; + } else { + this.conn = new BufferedConnection(conn); + } + } + + public void disconnect() { + if (conn != null) { + conn.close(); + } + conn = null; + } + + @Override + public void handle(MessageChat msg) { // big brain + ChatEvent event = new ChatEvent(ctx.player(), msg.msg); + baritone.getGameEventHandler().onSendChatMessage(event); + } + + @Override + public void handle(MessageComputationRequest msg) { + BetterBlockPos start = new BetterBlockPos(msg.startX, msg.startY, msg.startZ); + // TODO this may require scanning the world for blocks of a certain type, idk how to manage that + Goal goal = new GoalYLevel(Integer.parseInt(msg.goal)); // im already winston + SegmentedCalculator.calculateSegmentsThreaded(start, goal, new CalculationContext(baritone), path -> { + if (path.isPresent() && !Objects.equals(path.get().getGoal(), goal)) { + throw new IllegalStateException(); // sanity check + } + try { + conn.sendMessage(buildResponse(path, msg)); + } catch (IOException e) { + // nothing we can do about this, we just completed a computation but our tenor connection was closed in the meantime + // just discard the path we made for them =(( + e.printStackTrace(); // and complain =) + } + }); + } + + private static MessageComputationResponse buildResponse(Optional optPath, MessageComputationRequest req) { + if (optPath.isPresent()) { + IPath path = optPath.get(); + BetterBlockPos dest = path.getDest(); + return new MessageComputationResponse(req.computationID, path.length(), path.totalTicks(), path.getGoal().isInGoal(dest), dest.x, dest.y, dest.z); + } else { + return new MessageComputationResponse(req.computationID, 0, 0, false, 0, 0, 0); + } + } + + @Override + public void unhandled(iMessage msg) { + Helper.HELPER.logDebug("Unhandled message received by ControllerBehavior " + msg); + } +} diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index ee8548a2..31e76913 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -23,9 +23,8 @@ 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, Helper { +public final class LookBehavior extends Behavior implements ILookBehavior { /** * Target's values are as follows: @@ -69,24 +68,24 @@ public final class LookBehavior extends Behavior implements ILookBehavior, Helpe switch (event.getState()) { case PRE: { if (this.force) { - player().rotationYaw = this.target.getYaw(); - float oldPitch = player().rotationPitch; + ctx.player().rotationYaw = this.target.getYaw(); + float oldPitch = ctx.player().rotationPitch; float desiredPitch = this.target.getPitch(); - player().rotationPitch = desiredPitch; + ctx.player().rotationPitch = desiredPitch; if (desiredPitch == oldPitch) { nudgeToLevel(); } this.target = null; } if (silent) { - this.lastYaw = player().rotationYaw; - player().rotationYaw = this.target.getYaw(); + this.lastYaw = ctx.player().rotationYaw; + ctx.player().rotationYaw = this.target.getYaw(); } break; } case POST: { if (silent) { - player().rotationYaw = this.lastYaw; + ctx.player().rotationYaw = this.lastYaw; this.target = null; } break; @@ -114,10 +113,10 @@ public final class LookBehavior extends Behavior implements ILookBehavior, Helpe * Nudges the player's pitch to a regular level. (Between {@code -20} and {@code 10}, increments are by {@code 1}) */ private void nudgeToLevel() { - if (player().rotationPitch < -20) { - player().rotationPitch++; - } else if (player().rotationPitch > 10) { - player().rotationPitch--; + if (ctx.player().rotationPitch < -20) { + ctx.player().rotationPitch++; + } else if (ctx.player().rotationPitch > 10) { + ctx.player().rotationPitch--; } } } diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 1e8e069a..84507367 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -27,7 +27,6 @@ import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.type.EventState; import baritone.cache.Waypoint; import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; import net.minecraft.block.BlockBed; import net.minecraft.item.ItemStack; import net.minecraft.network.Packet; @@ -43,9 +42,9 @@ import java.util.*; /** * @author Brady - * @since 8/6/2018 9:47 PM + * @since 8/6/2018 */ -public final class MemoryBehavior extends Behavior implements IMemoryBehavior, Helper { +public final class MemoryBehavior extends Behavior implements IMemoryBehavior { private final Map worldDataContainers = new HashMap<>(); @@ -68,7 +67,7 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H if (p instanceof CPacketPlayerTryUseItemOnBlock) { CPacketPlayerTryUseItemOnBlock packet = event.cast(); - TileEntity tileEntity = world().getTileEntity(packet.getPos()); + TileEntity tileEntity = ctx.world().getTileEntity(packet.getPos()); // Ensure the TileEntity is a container of some sort if (tileEntity instanceof TileEntityLockable) { @@ -120,14 +119,14 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H @Override public void onBlockInteract(BlockInteractEvent event) { - if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(event.getPos()) instanceof BlockBed) { + 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())); } } @Override public void onPlayerDeath() { - baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, playerFeet())); + baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, ctx.playerFeet())); } private Optional getInventoryFromWindow(int windowId) { @@ -135,9 +134,9 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H } private void updateInventory() { - getInventoryFromWindow(player().openContainer.windowId).ifPresent(inventory -> { + getInventoryFromWindow(ctx.player().openContainer.windowId).ifPresent(inventory -> { inventory.items.clear(); - inventory.items.addAll(player().openContainer.getInventory().subList(0, inventory.size)); + inventory.items.addAll(ctx.player().openContainer.getInventory().subList(0, inventory.size)); }); } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index b1d2fc56..de973a5f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -24,7 +24,6 @@ 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; @@ -36,7 +35,6 @@ 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 net.minecraft.util.math.BlockPos; @@ -58,7 +56,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private boolean cancelRequested; private boolean calcFailedLastTick; - private volatile boolean isPathCalcInProgress; + private volatile AbstractNodeCostSearch inProgress; private final Object pathCalcLock = new Object(); private final Object pathPlanLock = new Object(); @@ -101,7 +99,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, if (pauseRequestedLastTick && safeToCancel) { pauseRequestedLastTick = false; baritone.getInputOverrideHandler().clearAllKeys(); - BlockBreakHelper.stopBreakingBlock(); + baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); return; } if (cancelRequested) { @@ -115,13 +113,13 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, synchronized (pathPlanLock) { if (current.failed() || current.finished()) { current = null; - if (goal == null || goal.isInGoal(playerFeet())) { + if (goal == null || goal.isInGoal(ctx.playerFeet())) { logDebug("All done. At " + goal); queuePathEvent(PathEvent.AT_GOAL); next = null; return; } - if (next != null && !next.getPath().positions().contains(playerFeet())) { + if (next != null && !next.getPath().positions().contains(ctx.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 @@ -142,13 +140,13 @@ 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 (isPathCalcInProgress) { + if (inProgress != null) { queuePathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING); // if we aren't calculating right now return; } queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true, Optional.empty()); + findPathInNewThread(pathStart(), true); } return; } @@ -167,7 +165,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, next = null; } synchronized (pathCalcLock) { - if (isPathCalcInProgress) { + if (inProgress != null) { // if we aren't calculating right now return; } @@ -183,7 +181,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, Optional.of(current.getPath())); + findPathInNewThread(current.getPath().getDest(), false); } } } @@ -239,8 +237,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } @Override - public Optional getPathFinder() { - return Optional.ofNullable(AbstractNodeCostSearch.currentlyRunning()); + public Optional getInProgress() { + return Optional.ofNullable(inProgress); } @Override @@ -285,7 +283,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, current = null; next = null; cancelRequested = true; - AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(AbstractNodeCostSearch::cancel); + getInProgress().ifPresent(AbstractNodeCostSearch::cancel); // only cancel ours // do everything BUT clear keys } @@ -295,14 +293,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, current = null; next = null; baritone.getInputOverrideHandler().clearAllKeys(); - AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(AbstractNodeCostSearch::cancel); - BlockBreakHelper.stopBreakingBlock(); + getInProgress().ifPresent(AbstractNodeCostSearch::cancel); + baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); } public void forceCancel() { // NOT exposed on public api cancelEverything(); secretInternalSegmentCancel(); - isPathCalcInProgress = false; + inProgress = null; } /** @@ -314,7 +312,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, if (goal == null) { return false; } - if (goal.isInGoal(playerFeet())) { + if (goal.isInGoal(ctx.playerFeet())) { return false; } synchronized (pathPlanLock) { @@ -322,11 +320,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return false; } synchronized (pathCalcLock) { - if (isPathCalcInProgress) { + if (inProgress != null) { return false; } queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true, Optional.empty()); + findPathInNewThread(pathStart(), true); return true; } } @@ -337,12 +335,12 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * * @return The starting {@link BlockPos} for a new path */ - public BlockPos pathStart() { - BetterBlockPos feet = playerFeet(); - if (!MovementHelper.canWalkOn(feet.down())) { - if (player().onGround) { - double playerX = player().posX; - double playerZ = player().posZ; + public BlockPos 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; ArrayList closest = new ArrayList<>(); for (int dx = -1; dx <= 1; dx++) { for (int dz = -1; dz <= 1; dz++) { @@ -358,9 +356,9 @@ 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(possibleSupport.down()) && MovementHelper.canWalkThrough(possibleSupport) && MovementHelper.canWalkThrough(possibleSupport.up())) { + if (MovementHelper.canWalkOn(ctx, possibleSupport.down()) && MovementHelper.canWalkThrough(ctx, possibleSupport) && MovementHelper.canWalkThrough(ctx, possibleSupport.up())) { // this is plausible - logDebug("Faking path start assuming player is standing off the edge of a block"); + //logDebug("Faking path start assuming player is standing off the edge of a block"); return possibleSupport; } } @@ -368,8 +366,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } else { // !onGround // we're in the middle of a jump - if (MovementHelper.canWalkOn(feet.down().down())) { - logDebug("Faking path start assuming player is midair and falling"); + if (MovementHelper.canWalkOn(ctx, feet.down().down())) { + //logDebug("Faking path start assuming player is midair and falling"); return feet.down(); } } @@ -383,21 +381,43 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * @param start * @param talkAboutIt */ - private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt, final Optional previous) { - synchronized (pathCalcLock) { - if (isPathCalcInProgress) { - throw new IllegalStateException("Already doing it"); - } - isPathCalcInProgress = true; + 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 } - CalculationContext context = new CalculationContext(); // not safe to create on the other thread, it looks up a lot of stuff in minecraft + 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); // 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)) { + logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance"); + } + inProgress = pathfinder; Baritone.getExecutor().execute(() -> { if (talkAboutIt) { logDebug("Starting to search for path from " + start + " to " + goal); } - PathCalculationResult calcResult = findPath(start, previous, context); - Optional path = calcResult.path; + PathCalculationResult calcResult = pathfinder.calculate(primaryTimeout, failureTimeout); + Optional path = calcResult.getPath(); if (Baritone.settings().cutoffAtLoadBoundary.get()) { path = path.map(p -> { IPath result = p.cutoffAtLoadedChunks(context.world()); @@ -421,7 +441,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } return result; - }).map(PathExecutor::new); + }).map(p -> new PathExecutor(this, p)); synchronized (pathPlanLock) { if (current == null) { @@ -429,7 +449,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, queuePathEvent(PathEvent.CALC_FINISHED_NOW_EXECUTING); current = executor.get(); } else { - if (calcResult.type != PathCalculationResult.Type.CANCELLATION && calcResult.type != PathCalculationResult.Type.EXCEPTION) { + if (calcResult.getType() != PathCalculationResult.Type.CANCELLATION && calcResult.getType() != PathCalculationResult.Type.EXCEPTION) { // don't dispatch CALC_FAILED on cancellation queuePathEvent(PathEvent.CALC_FAILED); } @@ -454,51 +474,25 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } } synchronized (pathCalcLock) { - isPathCalcInProgress = false; + inProgress = null; } } }); } - /** - * Actually do the pathing - * - * @param start - * @return - */ - private PathCalculationResult findPath(BlockPos start, Optional previous, CalculationContext context) { - Goal goal = this.goal; - if (goal == null) { - logDebug("no goal"); - return new PathCalculationResult(PathCalculationResult.Type.CANCELLATION, Optional.empty()); - } + public static AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, IPath previous, CalculationContext context) { + Goal transformed = goal; if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) { BlockPos pos = ((IGoalRenderPos) goal).getGoalPos(); if (context.world().getChunk(pos) instanceof EmptyChunk) { - logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance"); - goal = new GoalXZ(pos.getX(), pos.getZ()); + transformed = new GoalXZ(pos.getX(), pos.getZ()); } } - long timeout; - if (current == null) { - timeout = Baritone.settings().pathTimeoutMS.get(); - } else { - timeout = Baritone.settings().planAheadTimeoutMS.get(); - } - Optional> favoredPositions; - if (Baritone.settings().backtrackCostFavoringCoefficient.get() == 1D) { - favoredPositions = Optional.empty(); - } else { - favoredPositions = previous.map(IPath::positions).map(Collection::stream).map(x -> x.map(BetterBlockPos::longHash)).map(x -> x.collect(Collectors.toList())).map(HashSet::new); // <-- okay this is EPIC - } - 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 new PathCalculationResult(PathCalculationResult.Type.EXCEPTION, Optional.empty()); + HashSet favoredPositions = null; + if (Baritone.settings().backtrackCostFavoringCoefficient.get() != 1D && previous != null) { + favoredPositions = previous.positions().stream().map(BetterBlockPos::longHash).collect(Collectors.toCollection(HashSet::new)); } + return new AStarPathFinder(start.getX(), start.getY(), start.getZ(), transformed, favoredPositions, context); } @Override diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index abc741a5..1e55cb64 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -17,7 +17,6 @@ package baritone.cache; -import baritone.utils.Helper; import baritone.utils.pathing.PathingBlockType; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -28,9 +27,9 @@ import java.util.*; /** * @author Brady - * @since 8/3/2018 1:04 AM + * @since 8/3/2018 */ -public final class CachedChunk implements Helper { +public final class CachedChunk { public static final Set BLOCKS_TO_KEEP_TRACK_OF; diff --git a/src/main/java/baritone/cache/CachedRegion.java b/src/main/java/baritone/cache/CachedRegion.java index 95c20f37..d8426197 100644 --- a/src/main/java/baritone/cache/CachedRegion.java +++ b/src/main/java/baritone/cache/CachedRegion.java @@ -32,7 +32,7 @@ import java.util.zip.GZIPOutputStream; /** * @author Brady - * @since 8/3/2018 9:35 PM + * @since 8/3/2018 */ public final class CachedRegion implements ICachedRegion { diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index b775902e..31bcceab 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -18,7 +18,10 @@ 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; @@ -35,7 +38,7 @@ import java.util.concurrent.LinkedBlockingQueue; /** * @author Brady - * @since 8/4/2018 12:02 AM + * @since 8/4/2018 */ public final class CachedWorld implements ICachedWorld, Helper { @@ -106,10 +109,10 @@ public final class CachedWorld implements ICachedWorld, Helper { } @Override - public final LinkedList getLocationsOf(String block, int maximum, int maxRegionDistanceSq) { + public final LinkedList getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq) { LinkedList res = new LinkedList<>(); - int playerRegionX = playerFeet().getX() >> 9; - int playerRegionZ = playerFeet().getZ() >> 9; + int centerRegionX = centerX >> 9; + int centerRegionZ = centerZ >> 9; int searchRadius = 0; while (searchRadius <= maxRegionDistanceSq) { @@ -119,8 +122,8 @@ public final class CachedWorld implements ICachedWorld, Helper { if (distance != searchRadius) { continue; } - int regionX = xoff + playerRegionX; - int regionZ = zoff + playerRegionZ; + int regionX = xoff + centerRegionX; + int regionZ = zoff + centerRegionZ; CachedRegion region = getOrCreateRegion(regionX, regionZ); if (region != null) { // TODO: 100% verify if this or addAll is faster. @@ -190,9 +193,11 @@ 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() { - WorldData data = Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); - if (data != null && data.getCachedWorld() == this) { - return playerFeet(); + for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { + IWorldData data = ibaritone.getWorldProvider().getCurrentWorld(); + if (data != null && data.getCachedWorld() == this) { + return ibaritone.getPlayerContext().playerFeet(); + } } CachedChunk mostRecentlyModified = null; for (CachedRegion region : allRegions()) { diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index d73cdb03..0627ebb4 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -18,7 +18,6 @@ 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; @@ -36,9 +35,9 @@ import java.util.*; /** * @author Brady - * @since 8/3/2018 1:09 AM + * @since 8/3/2018 */ -public final class ChunkPacker implements Helper { +public final class ChunkPacker { private ChunkPacker() {} @@ -125,7 +124,7 @@ public final class ChunkPacker implements Helper { private static PathingBlockType getPathingBlockType(IBlockState state) { Block block = state.getBlock(); - if (block.equals(Blocks.WATER)) { + if (block.equals(Blocks.WATER) && !MovementHelper.isFlowing(state)) { // only water source blocks are plausibly usable, flowing water should be avoid return PathingBlockType.WATER; } diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index dd6e3561..fe33a4d1 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -36,7 +36,7 @@ import java.util.function.Consumer; /** * @author Brady - * @since 8/4/2018 11:06 AM + * @since 8/4/2018 */ public class WorldProvider implements IWorldProvider, Helper { @@ -55,8 +55,8 @@ public class WorldProvider implements IWorldProvider, Helper { * @param dimension The ID of the world's dimension */ public final void initWorld(int dimension) { - // Fight me @leijurv - File directory, readme; + File directory; + File readme; IntegratedServer integratedServer = mc.getIntegratedServer(); diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index 6366b157..1d220188 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -18,7 +18,7 @@ package baritone.cache; import baritone.api.cache.IWorldScanner; -import baritone.utils.Helper; +import baritone.api.utils.IPlayerContext; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.multiplayer.ChunkProviderClient; @@ -30,12 +30,12 @@ import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import java.util.LinkedList; import java.util.List; -public enum WorldScanner implements IWorldScanner, Helper { +public enum WorldScanner implements IWorldScanner { INSTANCE; @Override - public List scanChunkRadius(List blocks, int max, int yLevelThreshold, int maxSearchRadius) { + public List scanChunkRadius(IPlayerContext ctx, List blocks, int max, int yLevelThreshold, int maxSearchRadius) { if (blocks.contains(null)) { throw new IllegalStateException("Invalid block name should have been caught earlier: " + blocks.toString()); } @@ -43,12 +43,12 @@ public enum WorldScanner implements IWorldScanner, Helper { if (blocks.isEmpty()) { return res; } - ChunkProviderClient chunkProvider = world().getChunkProvider(); + ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider(); int maxSearchRadiusSq = maxSearchRadius * maxSearchRadius; - int playerChunkX = playerFeet().getX() >> 4; - int playerChunkZ = playerFeet().getZ() >> 4; - int playerY = playerFeet().getY(); + int playerChunkX = ctx.playerFeet().getX() >> 4; + int playerChunkZ = ctx.playerFeet().getZ() >> 4; + int playerY = ctx.playerFeet().getY(); int searchRadiusSq = 0; boolean foundWithinY = false; diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 084b5562..9f16283e 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -20,23 +20,25 @@ 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.cache.WorldProvider; import baritone.utils.Helper; +import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; -import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; /** * @author Brady - * @since 7/31/2018 11:04 PM + * @since 7/31/2018 */ -public final class GameEventHandler implements IGameEventListener, Helper { +public final class GameEventHandler implements IEventBus, Helper { private final Baritone baritone; - private final List listeners = new ArrayList<>(); + private final List listeners = new CopyOnWriteArrayList<>(); public GameEventHandler(Baritone baritone) { this.baritone = baritone; @@ -68,19 +70,21 @@ public final class GameEventHandler implements IGameEventListener, Helper { ChunkEvent.Type type = event.getType(); boolean isPostPopulate = state == EventState.POST - && type == ChunkEvent.Type.POPULATE; + && (type == ChunkEvent.Type.POPULATE_FULL || type == ChunkEvent.Type.POPULATE_PARTIAL); + + World world = baritone.getPlayerContext().world(); // 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 - && mc.world.getChunkProvider().isChunkGeneratedAt(event.getX(), event.getZ()); + && world.getChunkProvider().isChunkGeneratedAt(event.getX(), event.getZ()); if (isPostPopulate || isPreUnload) { - baritone.getWorldProvider().ifWorldLoaded(world -> { - Chunk chunk = mc.world.getChunk(event.getX(), event.getZ()); - world.getCachedWorld().queueForPacking(chunk); + baritone.getWorldProvider().ifWorldLoaded(worldData -> { + Chunk chunk = world.getChunk(event.getX(), event.getZ()); + worldData.getCachedWorld().queueForPacking(chunk); }); } @@ -137,8 +141,8 @@ public final class GameEventHandler implements IGameEventListener, Helper { listeners.forEach(l -> l.onPathEvent(event)); } + @Override public final void registerEventListener(IGameEventListener listener) { this.listeners.add(listener); } - } diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index b9babdda..d0061921 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -39,17 +39,17 @@ import java.util.Optional; */ public final class AStarPathFinder extends AbstractNodeCostSearch implements Helper { - private final Optional> favoredPositions; + private final HashSet favoredPositions; private final CalculationContext calcContext; - public AStarPathFinder(int startX, int startY, int startZ, Goal goal, Optional> favoredPositions, CalculationContext context) { + public AStarPathFinder(int startX, int startY, int startZ, Goal goal, HashSet favoredPositions, CalculationContext context) { super(startX, startY, startZ, goal, context); this.favoredPositions = favoredPositions; this.calcContext = context; } @Override - protected Optional calculate0(long timeout) { + protected Optional calculate0(long primaryTimeout, long failureTimeout) { startNode = getNodeAtPosition(startX, startY, startZ, BetterBlockPos.longHash(startX, startY, startZ)); startNode.cost = 0; startNode.combinedCost = startNode.estimatedCostToGoal; @@ -63,24 +63,28 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel bestSoFar[i] = startNode; } MutableMoveResult res = new MutableMoveResult(); - HashSet favored = favoredPositions.orElse(null); + HashSet favored = favoredPositions; BetterWorldBorder worldBorder = new BetterWorldBorder(calcContext.world().getWorldBorder()); long startTime = System.nanoTime() / 1000000L; boolean slowPath = Baritone.settings().slowPath.get(); if (slowPath) { - logDebug("slowPath is on, path timeout will be " + Baritone.settings().slowPathTimeoutMS.get() + "ms instead of " + timeout + "ms"); + logDebug("slowPath is on, path timeout will be " + Baritone.settings().slowPathTimeoutMS.get() + "ms instead of " + primaryTimeout + "ms"); } - long timeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.get() : timeout); - //long lastPrintout = 0; + long primaryTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.get() : primaryTimeout); + long failureTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.get() : failureTimeout); + boolean failing = true; int numNodes = 0; int numMovementsConsidered = 0; int numEmptyChunk = 0; - boolean favoring = favoredPositions.isPresent(); + boolean favoring = favored != null; 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(); - loopBegin(); - while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && System.nanoTime() / 1000000L - timeoutTime < 0 && !cancelRequested) { + while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && !cancelRequested) { + long now = System.nanoTime() / 1000000L; + if (now - failureTimeoutTime >= 0 || (!failing && now - primaryTimeoutTime >= 0)) { + break; + } if (slowPath) { try { Thread.sleep(Baritone.settings().slowPathTimeDelayMS.get()); @@ -167,6 +171,9 @@ 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; + } } } } diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 79a56037..6d9ad67e 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -23,6 +23,7 @@ import baritone.api.pathing.calc.IPathFinder; import baritone.api.pathing.goals.Goal; 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; @@ -34,11 +35,6 @@ 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; @@ -87,42 +83,37 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { cancelRequested = true; } - public synchronized PathCalculationResult calculate(long timeout) { + @Override + public synchronized PathCalculationResult calculate(long primaryTimeout, long failureTimeout) { if (isFinished) { throw new IllegalStateException("Path Finder is currently in use, and cannot be reused!"); } this.cancelRequested = false; try { - Optional path = calculate0(timeout); - path = path.map(IPath::postProcess); + IPath path = calculate0(primaryTimeout, failureTimeout).map(IPath::postProcess).orElse(null); isFinished = true; if (cancelRequested) { return new PathCalculationResult(PathCalculationResult.Type.CANCELLATION, path); } - if (!path.isPresent()) { - return new PathCalculationResult(PathCalculationResult.Type.FAILURE, path); + if (path == null) { + return new PathCalculationResult(PathCalculationResult.Type.FAILURE); } - if (goal.isInGoal(path.get().getDest())) { + 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); } finally { // this is run regardless of what exception may or may not be raised by calculate0 - currentlyRunning = null; isFinished = true; } } - /** - * 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 calculate0(long timeout); + protected abstract Optional calculate0(long primaryTimeout, long failureTimeout); /** * Determines the distance squared from the specified node to the start @@ -156,30 +147,9 @@ 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 pathToMostRecentNodeConsidered() { - try { - return Optional.ofNullable(mostRecentConsidered).map(node -> new Path(startNode, node, 0, goal, context)); - } catch (IllegalStateException ex) { - System.out.println("Unable to construct path to render"); - return Optional.empty(); - } + return Optional.ofNullable(mostRecentConsidered).map(node -> new Path(startNode, node, 0, goal, context)); } protected int mapSize() { @@ -188,7 +158,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { @Override public Optional bestPathSoFar() { - if (startNode == null || bestSoFar[0] == null) { + if (startNode == null || bestSoFar == null) { return Optional.empty(); } for (int i = 0; i < bestSoFar.length; i++) { @@ -196,12 +166,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { continue; } if (getDistFromStartSq(bestSoFar[i]) > MIN_DIST_PATH * MIN_DIST_PATH) { // square the comparison since distFromStartSq is squared - try { - return Optional.of(new Path(startNode, bestSoFar[i], 0, goal, context)); - } catch (IllegalStateException ex) { - System.out.println("Unable to construct path to render"); - return Optional.empty(); - } + return Optional.of(new Path(startNode, bestSoFar[i], 0, goal, context)); } } // instead of returning bestSoFar[0], be less misleading @@ -218,12 +183,4 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { public final Goal getGoal() { return goal; } - - public static Optional getCurrentlyRunning() { - return Optional.ofNullable(currentlyRunning); - } - - public static AbstractNodeCostSearch currentlyRunning() { - return currentlyRunning; - } } diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index e419bb72..cb4727cc 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -18,10 +18,10 @@ package baritone.pathing.movement; import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.pathing.movement.ActionCosts; import baritone.cache.WorldData; import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; import baritone.utils.ToolSet; import baritone.utils.pathing.BetterWorldBorder; import net.minecraft.block.Block; @@ -36,12 +36,13 @@ import net.minecraft.world.World; /** * @author Brady - * @since 8/7/2018 4:30 PM + * @since 8/7/2018 */ public class CalculationContext { private static final ItemStack STACK_BUCKET_WATER = new ItemStack(Items.WATER_BUCKET); + private final IBaritone baritone; private final EntityPlayerSP player; private final World world; private final WorldData worldData; @@ -58,14 +59,15 @@ public class CalculationContext { private final double breakBlockAdditionalCost; private final BetterWorldBorder worldBorder; - public CalculationContext() { - this.player = Helper.HELPER.player(); - this.world = Helper.HELPER.world(); - this.worldData = Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); + public CalculationContext(IBaritone baritone) { + 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 // 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(false); + this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(baritone.getPlayerContext(), false); this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether(); this.canSprint = Baritone.settings().allowSprint.get() && player.getFoodStats().getFoodLevel() > 6; this.placeBlockCost = Baritone.settings().blockPlacementPenalty.get(); @@ -85,6 +87,10 @@ public class CalculationContext { this.worldBorder = new BetterWorldBorder(world.getWorldBorder()); } + public final IBaritone getBaritone() { + return baritone; + } + public IBlockState get(int x, int y, int z) { return bsi.get0(x, y, z); // laughs maniacally } diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index e492a795..a3e841c6 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -17,13 +17,12 @@ package baritone.pathing.movement; -import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.*; +import baritone.api.utils.input.Input; import baritone.utils.BlockStateInterface; -import baritone.utils.Helper; -import baritone.utils.InputOverrideHandler; import net.minecraft.block.BlockLiquid; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -34,12 +33,13 @@ import java.util.List; import java.util.Objects; import java.util.Optional; -import static baritone.utils.InputOverrideHandler.Input; - -public abstract class Movement implements IMovement, Helper, MovementHelper { +public abstract class Movement implements IMovement, MovementHelper { protected static final EnumFacing[] HORIZONTALS = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST}; + protected final IBaritone baritone; + protected final IPlayerContext ctx; + private MovementState currentState = new MovementState().setStatus(MovementStatus.PREPPING); protected final BetterBlockPos src; @@ -64,21 +64,23 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { private Boolean calculatedWhileLoaded; - protected Movement(BetterBlockPos src, BetterBlockPos dest, BetterBlockPos[] toBreak, BetterBlockPos toPlace) { + protected Movement(IBaritone baritone, BetterBlockPos src, BetterBlockPos dest, BetterBlockPos[] toBreak, BetterBlockPos toPlace) { + this.baritone = baritone; + this.ctx = baritone.getPlayerContext(); this.src = src; this.dest = dest; this.positionsToBreak = toBreak; this.positionToPlace = toPlace; } - protected Movement(BetterBlockPos src, BetterBlockPos dest, BetterBlockPos[] toBreak) { - this(src, dest, toBreak, null); + protected Movement(IBaritone baritone, BetterBlockPos src, BetterBlockPos dest, BetterBlockPos[] toBreak) { + this(baritone, src, dest, toBreak, null); } @Override public double getCost() { if (cost == null) { - cost = calculateCost(new CalculationContext()); + cost = calculateCost(new CalculationContext(baritone)); } return cost; } @@ -97,7 +99,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { @Override public double calculateCostWithoutCaching() { - return calculateCost(new CalculationContext()); + return calculateCost(new CalculationContext(baritone)); } /** @@ -108,18 +110,18 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { */ @Override public MovementStatus update() { - player().capabilities.isFlying = false; + ctx.player().capabilities.isFlying = false; currentState = updateState(currentState); - if (MovementHelper.isLiquid(playerFeet())) { + if (MovementHelper.isLiquid(ctx, ctx.playerFeet())) { currentState.setInput(Input.JUMP, true); } - if (player().isEntityInsideOpaqueBlock()) { + if (ctx.player().isEntityInsideOpaqueBlock()) { currentState.setInput(Input.CLICK_LEFT, true); } // If the movement target has to force the new rotations, or we aren't using silent move, then force the rotations currentState.getTarget().getRotation().ifPresent(rotation -> - Baritone.INSTANCE.getLookBehavior().updateTarget( + baritone.getLookBehavior().updateTarget( rotation, currentState.getTarget().hasToForceRotations())); @@ -127,13 +129,13 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { // latestState.getTarget().position.ifPresent(null); NULL CONSUMER REALLY SHOULDN'T BE THE FINAL THING YOU SHOULD REALLY REPLACE THIS WITH ALMOST ACTUALLY ANYTHING ELSE JUST PLEASE DON'T LEAVE IT AS IT IS THANK YOU KANYE currentState.getInputStates().forEach((input, forced) -> { - Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(input, forced); + baritone.getInputOverrideHandler().setInputForceState(input, forced); }); currentState.getInputStates().replaceAll((input, forced) -> false); // If the current status indicates a completed movement if (currentState.getStatus().isComplete()) { - Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys(); + baritone.getInputOverrideHandler().clearAllKeys(); } return currentState.getStatus(); @@ -145,13 +147,13 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { } boolean somethingInTheWay = false; for (BetterBlockPos blockPos : positionsToBreak) { - if (!MovementHelper.canWalkThrough(blockPos) && !(BlockStateInterface.getBlock(blockPos) instanceof BlockLiquid)) { // can't break liquid, so don't try + if (!MovementHelper.canWalkThrough(ctx, blockPos) && !(BlockStateInterface.getBlock(ctx, blockPos) instanceof BlockLiquid)) { // can't break liquid, so don't try somethingInTheWay = true; - Optional reachable = RotationUtils.reachable(player(), blockPos, playerController().getBlockReachDistance()); + Optional reachable = RotationUtils.reachable(ctx.player(), blockPos, ctx.playerController().getBlockReachDistance()); if (reachable.isPresent()) { - MovementHelper.switchToBestToolFor(BlockStateInterface.get(blockPos)); + MovementHelper.switchToBestToolFor(ctx, BlockStateInterface.get(ctx, blockPos)); state.setTarget(new MovementState.MovementTarget(reachable.get(), true)); - if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), blockPos)) { + if (Objects.equals(ctx.getSelectedBlock().orElse(null), blockPos)) { state.setInput(Input.CLICK_LEFT, true); } return false; @@ -160,11 +162,11 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { //i'm doing it anyway //i dont care if theres snow in the way!!!!!!! //you dont own me!!!! - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(player().getPositionEyes(1.0F), + state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.player().getPositionEyes(1.0F), VecUtils.getBlockPosCenter(blockPos)), true) ); // don't check selectedblock on this one, this is a fallback when we can't see any face directly, it's intended to be breaking the "incorrect" block - state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); + state.setInput(Input.CLICK_LEFT, true); return false; } } @@ -249,7 +251,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { } List result = new ArrayList<>(); for (BetterBlockPos positionToBreak : positionsToBreak) { - if (!MovementHelper.canWalkThrough(positionToBreak)) { + if (!MovementHelper.canWalkThrough(ctx, positionToBreak)) { result.add(positionToBreak); } } @@ -263,7 +265,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { return toPlaceCached; } List result = new ArrayList<>(); - if (positionToPlace != null && !MovementHelper.canWalkOn(positionToPlace)) { + if (positionToPlace != null && !MovementHelper.canWalkOn(ctx, positionToPlace)) { result.add(positionToPlace); } toPlaceCached = result; diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index a7e9c378..917adc7c 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -20,10 +20,10 @@ package baritone.pathing.movement; import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; import baritone.api.utils.*; +import baritone.api.utils.input.Input; import baritone.pathing.movement.MovementState.MovementTarget; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; -import baritone.utils.InputOverrideHandler; import baritone.utils.ToolSet; import net.minecraft.block.*; import net.minecraft.block.properties.PropertyBool; @@ -35,6 +35,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; import net.minecraft.world.chunk.EmptyChunk; /** @@ -44,33 +45,27 @@ import net.minecraft.world.chunk.EmptyChunk; */ public interface MovementHelper extends ActionCosts, Helper { - static boolean avoidBreaking(CalculationContext context, int x, int y, int z, IBlockState state) { + static boolean avoidBreaking(BlockStateInterface bsi, int x, int y, int z, IBlockState state) { Block b = state.getBlock(); return b == Blocks.ICE // ice becomes water, and water can mess up the path || b instanceof BlockSilverfish // obvious reasons // call context.get directly with x,y,z. no need to make 5 new BlockPos for no reason - || context.get(x, y + 1, z).getBlock() instanceof BlockLiquid//don't break anything touching liquid on any side - || context.get(x + 1, y, z).getBlock() instanceof BlockLiquid - || context.get(x - 1, y, z).getBlock() instanceof BlockLiquid - || context.get(x, y, z + 1).getBlock() instanceof BlockLiquid - || context.get(x, y, z - 1).getBlock() instanceof BlockLiquid; + || bsi.get0(x, y + 1, z).getBlock() instanceof BlockLiquid//don't break anything touching liquid on any side + || bsi.get0(x + 1, y, z).getBlock() instanceof BlockLiquid + || bsi.get0(x - 1, y, z).getBlock() instanceof BlockLiquid + || bsi.get0(x, y, z + 1).getBlock() instanceof BlockLiquid + || bsi.get0(x, y, z - 1).getBlock() instanceof BlockLiquid; } - /** - * Can I walk through this block? e.g. air, saplings, torches, etc - * - * @param pos - * @return - */ - static boolean canWalkThrough(BetterBlockPos pos) { - return canWalkThrough(new CalculationContext(), pos.x, pos.y, pos.z, BlockStateInterface.get(pos)); + static boolean canWalkThrough(IPlayerContext ctx, BetterBlockPos pos) { + return canWalkThrough(new BlockStateInterface(ctx), pos.x, pos.y, pos.z); } - static boolean canWalkThrough(CalculationContext context, int x, int y, int z) { - return canWalkThrough(context, x, y, z, context.get(x, y, z)); + static boolean canWalkThrough(BlockStateInterface bsi, int x, int y, int z) { + return canWalkThrough(bsi, x, y, z, bsi.get0(x, y, z)); } - static boolean canWalkThrough(CalculationContext context, int x, int y, int z, IBlockState state) { + static boolean canWalkThrough(BlockStateInterface bsi, int x, int y, int z, IBlockState state) { Block block = state.getBlock(); if (block == Blocks.AIR) { // early return for most common case return true; @@ -91,7 +86,7 @@ public interface MovementHelper extends ActionCosts, Helper { // so the only remaining dynamic isPassables are snow and trapdoor // if they're cached as a top block, we don't know their metadata // default to true (mostly because it would otherwise make long distance pathing through snowy biomes impossible) - if (mc.world.getChunk(x >> 4, z >> 4) instanceof EmptyChunk) { + if (!bsi.worldContainsLoadedChunk(x, z)) { return true; } if (snow) { @@ -111,7 +106,7 @@ public interface MovementHelper extends ActionCosts, Helper { if (Baritone.settings().assumeWalkOnWater.get()) { return false; } - IBlockState up = context.get(x, y + 1, z); + IBlockState up = bsi.get0(x, y + 1, z); if (up.getBlock() instanceof BlockLiquid || up.getBlock() instanceof BlockLilyPad) { return false; } @@ -156,7 +151,7 @@ public interface MovementHelper extends ActionCosts, Helper { return block.isPassable(null, null); } - static boolean isReplacable(int x, int y, int z, IBlockState state) { + static boolean isReplacable(int x, int y, int z, IBlockState state, World world) { // for MovementTraverse and MovementAscend // block double plant defaults to true when the block doesn't match, so don't need to check that case // all other overrides just return true or false @@ -170,7 +165,7 @@ public interface MovementHelper extends ActionCosts, Helper { Block block = state.getBlock(); if (block instanceof BlockSnow) { // as before, default to true (mostly because it would otherwise make long distance pathing through snowy biomes impossible) - if (mc.world.getChunk(x >> 4, z >> 4) instanceof EmptyChunk) { + if (world.getChunk(x >> 4, z >> 4) instanceof EmptyChunk) { return true; } return state.getValue(BlockSnow.LAYERS) == 1; @@ -182,12 +177,12 @@ public interface MovementHelper extends ActionCosts, Helper { return state.getMaterial().isReplaceable(); } - static boolean isDoorPassable(BlockPos doorPos, BlockPos playerPos) { + static boolean isDoorPassable(IPlayerContext ctx, BlockPos doorPos, BlockPos playerPos) { if (playerPos.equals(doorPos)) { return false; } - IBlockState state = BlockStateInterface.get(doorPos); + IBlockState state = BlockStateInterface.get(ctx, doorPos); if (!(state.getBlock() instanceof BlockDoor)) { return true; } @@ -195,17 +190,17 @@ public interface MovementHelper extends ActionCosts, Helper { return isHorizontalBlockPassable(doorPos, state, playerPos, BlockDoor.OPEN); } - static boolean isGatePassable(BlockPos gatePos, BlockPos playerPos) { + static boolean isGatePassable(IPlayerContext ctx, BlockPos gatePos, BlockPos playerPos) { if (playerPos.equals(gatePos)) { return false; } - IBlockState state = BlockStateInterface.get(gatePos); + IBlockState state = BlockStateInterface.get(ctx, gatePos); if (!(state.getBlock() instanceof BlockFenceGate)) { return true; } - return isHorizontalBlockPassable(gatePos, state, playerPos, BlockFenceGate.OPEN); + return state.getValue(BlockFenceGate.OPEN); } static boolean isHorizontalBlockPassable(BlockPos blockPos, IBlockState blockState, BlockPos playerPos, PropertyBool propertyOpen) { @@ -245,7 +240,7 @@ public interface MovementHelper extends ActionCosts, Helper { * * @return */ - static boolean canWalkOn(CalculationContext context, int x, int y, int z, IBlockState state) { + static boolean canWalkOn(BlockStateInterface bsi, int x, int y, int z, IBlockState state) { Block block = state.getBlock(); if (block == Blocks.AIR || block == Blocks.MAGMA) { // early return for most common case (air) @@ -267,7 +262,7 @@ public interface MovementHelper extends ActionCosts, Helper { if (isWater(block)) { // since this is called literally millions of times per second, the benefit of not allocating millions of useless "pos.up()" // BlockPos s that we'd just garbage collect immediately is actually noticeable. I don't even think its a decrease in readability - Block up = context.get(x, y + 1, z).getBlock(); + Block up = bsi.get0(x, y + 1, z).getBlock(); if (up == Blocks.WATERLILY) { return true; } @@ -279,7 +274,7 @@ public interface MovementHelper extends ActionCosts, Helper { // if assumeWalkOnWater is off, we can only walk on water if there is water above it return isWater(up) ^ Baritone.settings().assumeWalkOnWater.get(); } - if (block instanceof BlockGlass || block instanceof BlockStainedGlass) { + if (block == Blocks.GLASS || block == Blocks.STAINED_GLASS) { return true; } if (block instanceof BlockSlab) { @@ -294,24 +289,28 @@ public interface MovementHelper extends ActionCosts, Helper { return block instanceof BlockStairs; } - static boolean canWalkOn(BetterBlockPos pos, IBlockState state) { - return canWalkOn(new CalculationContext(), pos.x, pos.y, pos.z, state); + static boolean canWalkOn(IPlayerContext ctx, BetterBlockPos pos, IBlockState state) { + return canWalkOn(new BlockStateInterface(ctx), pos.x, pos.y, pos.z, state); } - static boolean canWalkOn(BetterBlockPos pos) { - return canWalkOn(new CalculationContext(), pos.x, pos.y, pos.z, BlockStateInterface.get(pos)); + static boolean canWalkOn(IPlayerContext ctx, BetterBlockPos pos) { + return canWalkOn(new BlockStateInterface(ctx), pos.x, pos.y, pos.z); } - static boolean canWalkOn(CalculationContext context, int x, int y, int z) { - return canWalkOn(context, x, y, z, context.get(x, y, z)); + static boolean canWalkOn(BlockStateInterface bsi, int x, int y, int z) { + return canWalkOn(bsi, x, y, z, bsi.get0(x, y, z)); } - static boolean canPlaceAgainst(CalculationContext context, int x, int y, int z) { - return canPlaceAgainst(context.get(x, y, z)); + static boolean canPlaceAgainst(BlockStateInterface bsi, int x, int y, int z) { + return canPlaceAgainst(bsi.get0(x, y, z)); } - static boolean canPlaceAgainst(BlockPos pos) { - return canPlaceAgainst(BlockStateInterface.get(pos)); + static boolean canPlaceAgainst(BlockStateInterface bsi, BlockPos pos) { + return canPlaceAgainst(bsi.get0(pos.getX(), pos.getY(), pos.getZ())); + } + + static boolean canPlaceAgainst(IPlayerContext ctx, BlockPos pos) { + return canPlaceAgainst(new BlockStateInterface(ctx), pos); } static boolean canPlaceAgainst(IBlockState state) { @@ -325,11 +324,11 @@ public interface MovementHelper extends ActionCosts, Helper { static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, IBlockState state, boolean includeFalling) { Block block = state.getBlock(); - if (!canWalkThrough(context, x, y, z, state)) { + if (!canWalkThrough(context.bsi(), x, y, z, state)) { if (!context.canBreakAt(x, y, z)) { return COST_INF; } - if (avoidBreaking(context, x, y, z, state)) { + if (avoidBreaking(context.bsi(), x, y, z, state)) { return COST_INF; } if (block instanceof BlockLiquid) { @@ -360,26 +359,13 @@ public interface MovementHelper extends ActionCosts, Helper { && state.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.BOTTOM; } - /** - * AutoTool - */ - static void switchToBestTool() { - RayTraceUtils.getSelectedBlock().ifPresent(pos -> { - IBlockState state = BlockStateInterface.get(pos); - if (state.getBlock().equals(Blocks.AIR)) { - return; - } - switchToBestToolFor(state); - }); - } - /** * AutoTool for a specific block * * @param b the blockstate to mine */ - static void switchToBestToolFor(IBlockState b) { - switchToBestToolFor(b, new ToolSet(Helper.HELPER.player())); + static void switchToBestToolFor(IPlayerContext ctx, IBlockState b) { + switchToBestToolFor(ctx, b, new ToolSet(ctx.player())); } /** @@ -388,12 +374,12 @@ public interface MovementHelper extends ActionCosts, Helper { * @param b the blockstate to mine * @param ts previously calculated ToolSet */ - static void switchToBestToolFor(IBlockState b, ToolSet ts) { - Helper.HELPER.player().inventory.currentItem = ts.getBestSlot(b.getBlock()); + static void switchToBestToolFor(IPlayerContext ctx, IBlockState b, ToolSet ts) { + ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock()); } - static boolean throwaway(boolean select) { - EntityPlayerSP p = Helper.HELPER.player(); + static boolean throwaway(IPlayerContext ctx, boolean select) { + EntityPlayerSP p = ctx.player(); NonNullList inv = p.inventory.mainInventory; for (byte i = 0; i < 9; i++) { ItemStack item = inv.get(i); @@ -428,14 +414,14 @@ public interface MovementHelper extends ActionCosts, Helper { return false; } - static void moveTowards(MovementState state, BlockPos pos) { - EntityPlayerSP player = Helper.HELPER.player(); + static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) { + EntityPlayerSP player = ctx.player(); state.setTarget(new MovementTarget( new Rotation(RotationUtils.calcRotationFromVec3d(player.getPositionEyes(1.0F), VecUtils.getBlockPosCenter(pos), new Rotation(player.rotationYaw, player.rotationPitch)).getYaw(), player.rotationPitch), false - )).setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); + )).setInput(Input.MOVE_FORWARD, true); } /** @@ -453,11 +439,12 @@ public interface MovementHelper extends ActionCosts, Helper { * Returns whether or not the block at the specified pos is * water, regardless of whether or not it is flowing. * - * @param bp The block pos + * @param ctx The player context + * @param bp The block pos * @return Whether or not the block is water */ - static boolean isWater(BlockPos bp) { - return isWater(BlockStateInterface.getBlock(bp)); + static boolean isWater(IPlayerContext ctx, BlockPos bp) { + return isWater(BlockStateInterface.getBlock(ctx, bp)); } static boolean isLava(Block b) { @@ -467,11 +454,12 @@ public interface MovementHelper extends ActionCosts, Helper { /** * Returns whether or not the specified pos has a liquid * - * @param p The pos + * @param ctx The player context + * @param p The pos * @return Whether or not the block is a liquid */ - static boolean isLiquid(BlockPos p) { - return BlockStateInterface.getBlock(p) instanceof BlockLiquid; + static boolean isLiquid(IPlayerContext ctx, BlockPos p) { + return BlockStateInterface.getBlock(ctx, p) instanceof BlockLiquid; } static boolean isFlowing(IBlockState state) { diff --git a/src/main/java/baritone/pathing/movement/MovementState.java b/src/main/java/baritone/pathing/movement/MovementState.java index 8b1b0e0d..4432c503 100644 --- a/src/main/java/baritone/pathing/movement/MovementState.java +++ b/src/main/java/baritone/pathing/movement/MovementState.java @@ -19,7 +19,7 @@ package baritone.pathing.movement; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.Rotation; -import baritone.utils.InputOverrideHandler.Input; +import baritone.api.utils.input.Input; import net.minecraft.util.math.Vec3d; import java.util.HashMap; diff --git a/src/main/java/baritone/pathing/movement/Moves.java b/src/main/java/baritone/pathing/movement/Moves.java index 340122b3..c5a6ceb6 100644 --- a/src/main/java/baritone/pathing/movement/Moves.java +++ b/src/main/java/baritone/pathing/movement/Moves.java @@ -31,7 +31,7 @@ public enum Moves { DOWNWARD(0, -1, 0) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementDownward(src, src.down()); + return new MovementDownward(context.getBaritone(), src, src.down()); } @Override @@ -43,7 +43,7 @@ public enum Moves { PILLAR(0, +1, 0) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementPillar(src, src.up()); + return new MovementPillar(context.getBaritone(), src, src.up()); } @Override @@ -55,7 +55,7 @@ public enum Moves { TRAVERSE_NORTH(0, 0, -1) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementTraverse(src, src.north()); + return new MovementTraverse(context.getBaritone(), src, src.north()); } @Override @@ -67,7 +67,7 @@ public enum Moves { TRAVERSE_SOUTH(0, 0, +1) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementTraverse(src, src.south()); + return new MovementTraverse(context.getBaritone(), src, src.south()); } @Override @@ -79,7 +79,7 @@ public enum Moves { TRAVERSE_EAST(+1, 0, 0) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementTraverse(src, src.east()); + return new MovementTraverse(context.getBaritone(), src, src.east()); } @Override @@ -91,7 +91,7 @@ public enum Moves { TRAVERSE_WEST(-1, 0, 0) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementTraverse(src, src.west()); + return new MovementTraverse(context.getBaritone(), src, src.west()); } @Override @@ -103,7 +103,7 @@ public enum Moves { ASCEND_NORTH(0, +1, -1) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementAscend(src, new BetterBlockPos(src.x, src.y + 1, src.z - 1)); + return new MovementAscend(context.getBaritone(), src, new BetterBlockPos(src.x, src.y + 1, src.z - 1)); } @Override @@ -115,7 +115,7 @@ public enum Moves { ASCEND_SOUTH(0, +1, +1) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementAscend(src, new BetterBlockPos(src.x, src.y + 1, src.z + 1)); + return new MovementAscend(context.getBaritone(), src, new BetterBlockPos(src.x, src.y + 1, src.z + 1)); } @Override @@ -127,7 +127,7 @@ public enum Moves { ASCEND_EAST(+1, +1, 0) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementAscend(src, new BetterBlockPos(src.x + 1, src.y + 1, src.z)); + return new MovementAscend(context.getBaritone(), src, new BetterBlockPos(src.x + 1, src.y + 1, src.z)); } @Override @@ -139,7 +139,7 @@ public enum Moves { ASCEND_WEST(-1, +1, 0) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementAscend(src, new BetterBlockPos(src.x - 1, src.y + 1, src.z)); + return new MovementAscend(context.getBaritone(), src, new BetterBlockPos(src.x - 1, src.y + 1, src.z)); } @Override @@ -154,9 +154,9 @@ public enum Moves { MutableMoveResult res = new MutableMoveResult(); apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { - return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementDescend(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } else { - return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementFall(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -172,9 +172,9 @@ public enum Moves { MutableMoveResult res = new MutableMoveResult(); apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { - return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementDescend(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } else { - return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementFall(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -190,9 +190,9 @@ public enum Moves { MutableMoveResult res = new MutableMoveResult(); apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { - return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementDescend(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } else { - return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementFall(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -208,9 +208,9 @@ public enum Moves { MutableMoveResult res = new MutableMoveResult(); apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { - return new MovementDescend(src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementDescend(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } else { - return new MovementFall(src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementFall(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -223,7 +223,7 @@ public enum Moves { DIAGONAL_NORTHEAST(+1, 0, -1) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementDiagonal(src, EnumFacing.NORTH, EnumFacing.EAST); + return new MovementDiagonal(context.getBaritone(), src, EnumFacing.NORTH, EnumFacing.EAST); } @Override @@ -235,7 +235,7 @@ public enum Moves { DIAGONAL_NORTHWEST(-1, 0, -1) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementDiagonal(src, EnumFacing.NORTH, EnumFacing.WEST); + return new MovementDiagonal(context.getBaritone(), src, EnumFacing.NORTH, EnumFacing.WEST); } @Override @@ -247,7 +247,7 @@ public enum Moves { DIAGONAL_SOUTHEAST(+1, 0, +1) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementDiagonal(src, EnumFacing.SOUTH, EnumFacing.EAST); + return new MovementDiagonal(context.getBaritone(), src, EnumFacing.SOUTH, EnumFacing.EAST); } @Override @@ -259,7 +259,7 @@ public enum Moves { DIAGONAL_SOUTHWEST(-1, 0, +1) { @Override public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementDiagonal(src, EnumFacing.SOUTH, EnumFacing.WEST); + return new MovementDiagonal(context.getBaritone(), src, EnumFacing.SOUTH, EnumFacing.WEST); } @Override diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 1d161554..0baef881 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -18,19 +18,18 @@ package baritone.pathing.movement.movements; import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.RayTraceUtils; import baritone.api.utils.RotationUtils; +import baritone.api.utils.input.Input; 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 baritone.utils.InputOverrideHandler; import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -42,8 +41,8 @@ public class MovementAscend extends Movement { private int ticksWithoutPlacement = 0; - public MovementAscend(BetterBlockPos src, BetterBlockPos dest) { - super(src, dest, new BetterBlockPos[]{dest, src.up(2), dest.up()}, dest.down()); + public MovementAscend(IBaritone baritone, BetterBlockPos src, BetterBlockPos dest) { + super(baritone, src, dest, new BetterBlockPos[]{dest, src.up(2), dest.up()}, dest.down()); } @Override @@ -71,11 +70,11 @@ public class MovementAscend extends Movement { return COST_INF;// the only thing we can ascend onto from a bottom slab is another bottom slab } boolean hasToPlace = false; - if (!MovementHelper.canWalkOn(context, destX, y, destZ, toPlace)) { + if (!MovementHelper.canWalkOn(context.bsi(), destX, y, destZ, toPlace)) { if (!context.canPlaceThrowawayAt(destX, y, destZ)) { return COST_INF; } - if (toPlace.getBlock() != Blocks.AIR && !MovementHelper.isWater(toPlace.getBlock()) && !MovementHelper.isReplacable(destX, y, destZ, toPlace)) { + if (toPlace.getBlock() != Blocks.AIR && !MovementHelper.isWater(toPlace.getBlock()) && !MovementHelper.isReplacable(destX, y, destZ, toPlace, context.world())) { return COST_INF; } // TODO: add ability to place against .down() as well as the cardinal directions @@ -87,7 +86,7 @@ public class MovementAscend extends Movement { if (againstX == x && againstZ == z) { continue; } - if (MovementHelper.canPlaceAgainst(context, againstX, y, againstZ)) { + if (MovementHelper.canPlaceAgainst(context.bsi(), againstX, y, againstZ)) { hasToPlace = true; break; } @@ -97,7 +96,7 @@ public class MovementAscend extends Movement { } } IBlockState srcUp2 = null; - if (context.get(x, y + 3, z).getBlock() instanceof BlockFalling && (MovementHelper.canWalkThrough(context, x, y + 1, z) || !((srcUp2 = context.get(x, y + 2, z)).getBlock() instanceof BlockFalling))) {//it would fall on us and possibly suffocate us + if (context.get(x, y + 3, z).getBlock() instanceof BlockFalling && (MovementHelper.canWalkThrough(context.bsi(), x, y + 1, z) || !((srcUp2 = context.get(x, y + 2, z)).getBlock() instanceof BlockFalling))) {//it would fall on us and possibly suffocate us // HOWEVER, we assume that we're standing in the start position // that means that src and src.up(1) are both air // maybe they aren't now, but they will be by the time this starts @@ -161,40 +160,40 @@ public class MovementAscend extends Movement { return state; } - if (playerFeet().equals(dest)) { + if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } - IBlockState jumpingOnto = BlockStateInterface.get(positionToPlace); - if (!MovementHelper.canWalkOn(positionToPlace, jumpingOnto)) { + IBlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace); + if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) { for (int i = 0; i < 4; i++) { BlockPos anAgainst = positionToPlace.offset(HORIZONTALS[i]); if (anAgainst.equals(src)) { continue; } - if (MovementHelper.canPlaceAgainst(anAgainst)) { - if (!MovementHelper.throwaway(true)) {//get ready to place a throwaway block + if (MovementHelper.canPlaceAgainst(ctx, anAgainst)) { + if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block return state.setStatus(MovementStatus.UNREACHABLE); } double faceX = (dest.getX() + anAgainst.getX() + 1.0D) * 0.5D; double faceY = (dest.getY() + anAgainst.getY()) * 0.5D; double faceZ = (dest.getZ() + anAgainst.getZ() + 1.0D) * 0.5D; - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true)); - EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; + state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true)); + EnumFacing side = ctx.objectMouseOver().sideHit; - RayTraceUtils.getSelectedBlock().ifPresent(selectedBlock -> { + ctx.getSelectedBlock().ifPresent(selectedBlock -> { if (Objects.equals(selectedBlock, anAgainst) && selectedBlock.offset(side).equals(positionToPlace)) { ticksWithoutPlacement++; - state.setInput(InputOverrideHandler.Input.SNEAK, true); - if (player().isSneaking()) { - state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); + state.setInput(Input.SNEAK, true); + if (ctx.player().isSneaking()) { + state.setInput(Input.CLICK_RIGHT, true); } if (ticksWithoutPlacement > 10) { // After 10 ticks without placement, we might be standing in the way, move back - state.setInput(InputOverrideHandler.Input.MOVE_BACK, true); + state.setInput(Input.MOVE_BACK, true); } } else { - state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); // break whatever replaceable block is in the way + state.setInput(Input.CLICK_LEFT, true); // break whatever replaceable block is in the way } //System.out.println("Trying to look at " + anAgainst + ", actually looking at" + selectedBlock); }); @@ -203,8 +202,8 @@ public class MovementAscend extends Movement { } return state.setStatus(MovementStatus.UNREACHABLE); } - MovementHelper.moveTowards(state, dest); - if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(BlockStateInterface.get(src.down()))) { + MovementHelper.moveTowards(ctx, state, dest); + if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(BlockStateInterface.get(ctx, src.down()))) { return state; // don't jump while walking from a non double slab into a bottom slab } @@ -212,14 +211,18 @@ public class MovementAscend extends Movement { return state; } + if (ctx.playerFeet().equals(src.up())) { + return state; // no need to hit space if we're already jumping + } + if (headBonkClear()) { - return state.setInput(InputOverrideHandler.Input.JUMP, true); + return state.setInput(Input.JUMP, true); } int xAxis = Math.abs(src.getX() - dest.getX()); // either 0 or 1 int zAxis = Math.abs(src.getZ() - dest.getZ()); // either 0 or 1 - double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - player().posZ); - double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - player().posZ); + double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ); + double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ); // System.out.println(flatDistToNext + " " + sideDist); if (flatDistToNext > 1.2 || sideDist > 0.2) { return state; @@ -228,14 +231,14 @@ public class MovementAscend extends Movement { // Once we are pointing the right way and moving, start jumping // This is slightly more efficient because otherwise we might start jumping before moving, and fall down without moving onto the block we want to jump onto // Also wait until we are close enough, because we might jump and hit our head on an adjacent block - return state.setInput(InputOverrideHandler.Input.JUMP, true); + return state.setInput(Input.JUMP, true); } private boolean headBonkClear() { BetterBlockPos startUp = src.up(2); for (int i = 0; i < 4; i++) { BetterBlockPos check = startUp.offset(EnumFacing.byHorizontalIndex(i)); - if (!MovementHelper.canWalkThrough(check)) { + if (!MovementHelper.canWalkThrough(ctx, check)) { // We might bonk our head return false; } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index 84f0d781..d868c5fc 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -18,26 +18,32 @@ package baritone.pathing.movement.movements; import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.Rotation; +import baritone.api.utils.RotationUtils; +import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; -import baritone.utils.InputOverrideHandler; +import baritone.utils.BlockStateInterface; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; public class MovementDescend extends Movement { private int numTicks = 0; - public MovementDescend(BetterBlockPos start, BetterBlockPos end) { - super(start, end, new BetterBlockPos[]{end.up(2), end.up(), end}, end.down()); + public MovementDescend(IBaritone baritone, BetterBlockPos start, BetterBlockPos end) { + super(baritone, start, end, new BetterBlockPos[]{end.up(2), end.up(), end}, end.down()); } @Override @@ -88,7 +94,7 @@ public class MovementDescend extends Movement { //C, D, etc determine the length of the fall IBlockState below = context.get(destX, y - 2, destZ); - if (!MovementHelper.canWalkOn(context, destX, y - 2, destZ, below)) { + if (!MovementHelper.canWalkOn(context.bsi(), destX, y - 2, destZ, below)) { dynamicFallCost(context, x, y, z, destX, destZ, totalCost, below, res); return; } @@ -117,7 +123,7 @@ public class MovementDescend extends Movement { // and potentially replace the water we're going to fall into return; } - if (!MovementHelper.canWalkThrough(context, destX, y - 2, destZ, below) && below.getBlock() != Blocks.WATER) { + if (!MovementHelper.canWalkThrough(context.bsi(), destX, y - 2, destZ, below) && below.getBlock() != Blocks.WATER) { return; } for (int fallHeight = 3; true; fallHeight++) { @@ -145,10 +151,10 @@ public class MovementDescend extends Movement { if (ontoBlock.getBlock() == Blocks.FLOWING_WATER) { return; } - if (MovementHelper.canWalkThrough(context, destX, newY, destZ, ontoBlock)) { + if (MovementHelper.canWalkThrough(context.bsi(), destX, newY, destZ, ontoBlock)) { continue; } - if (!MovementHelper.canWalkOn(context, destX, newY, destZ, ontoBlock)) { + if (!MovementHelper.canWalkOn(context.bsi(), destX, newY, destZ, ontoBlock)) { return; } if (MovementHelper.isBottomSlab(ontoBlock)) { @@ -181,32 +187,56 @@ public class MovementDescend extends Movement { return state; } - BlockPos playerFeet = playerFeet(); - if (playerFeet.equals(dest) && (MovementHelper.isLiquid(dest) || player().posY - playerFeet.getY() < 0.094)) { // lilypads + BlockPos playerFeet = ctx.playerFeet(); + if (playerFeet.equals(dest) && (MovementHelper.isLiquid(ctx, dest) || ctx.player().posY - playerFeet.getY() < 0.094)) { // lilypads // Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately return state.setStatus(MovementStatus.SUCCESS); /* else { // System.out.println(player().posY + " " + playerFeet.getY() + " " + (player().posY - playerFeet.getY())); }*/ } - double diffX = player().posX - (dest.getX() + 0.5); - double diffZ = player().posZ - (dest.getZ() + 0.5); + if (safeMode()) { + double destX = (src.getX() + 0.5) * 0.19 + (dest.getX() + 0.5) * 0.81; + double destZ = (src.getZ() + 0.5) * 0.19 + (dest.getZ() + 0.5) * 0.81; + EntityPlayerSP player = ctx.player(); + state.setTarget(new MovementState.MovementTarget( + new Rotation(RotationUtils.calcRotationFromVec3d(player.getPositionEyes(1.0F), + new Vec3d(destX, dest.getY(), destZ), + new Rotation(player.rotationYaw, player.rotationPitch)).getYaw(), player.rotationPitch), + false + )).setInput(Input.MOVE_FORWARD, true); + return state; + } + double diffX = ctx.player().posX - (dest.getX() + 0.5); + double diffZ = ctx.player().posZ - (dest.getZ() + 0.5); double ab = Math.sqrt(diffX * diffX + diffZ * diffZ); - double x = player().posX - (src.getX() + 0.5); - double z = player().posZ - (src.getZ() + 0.5); + double x = ctx.player().posX - (src.getX() + 0.5); + double z = ctx.player().posZ - (src.getZ() + 0.5); double fromStart = Math.sqrt(x * x + z * z); if (!playerFeet.equals(dest) || ab > 0.25) { BlockPos fakeDest = new BlockPos(dest.getX() * 2 - src.getX(), dest.getY(), dest.getZ() * 2 - src.getZ()); if (numTicks++ < 20) { - MovementHelper.moveTowards(state, fakeDest); + MovementHelper.moveTowards(ctx, state, fakeDest); if (fromStart > 1.25) { - state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, false); - state.setInput(InputOverrideHandler.Input.MOVE_BACK, true); + state.setInput(Input.MOVE_FORWARD, false); + state.setInput(Input.MOVE_BACK, true); } } else { - MovementHelper.moveTowards(state, dest); + MovementHelper.moveTowards(ctx, state, dest); } } return state; } + + public boolean safeMode() { + // (dest - src) + dest is offset 1 more in the same direction + // so it's the block we'd need to worry about running into if we decide to sprint straight through this descend + BlockPos into = dest.subtract(src.down()).add(dest); + for (int y = 0; y <= 2; y++) { // we could hit any of the three blocks + if (MovementHelper.avoidWalkingInto(BlockStateInterface.getBlock(ctx, into.up(y)))) { + return true; + } + } + return false; + } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 8e5dd910..4a098380 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -17,13 +17,14 @@ package baritone.pathing.movement.movements; +import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; -import baritone.utils.InputOverrideHandler; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -37,17 +38,17 @@ public class MovementDiagonal extends Movement { private static final double SQRT_2 = Math.sqrt(2); - public MovementDiagonal(BetterBlockPos start, EnumFacing dir1, EnumFacing dir2) { - this(start, start.offset(dir1), start.offset(dir2), dir2); + public MovementDiagonal(IBaritone baritone, BetterBlockPos start, EnumFacing dir1, EnumFacing dir2) { + this(baritone, start, start.offset(dir1), start.offset(dir2), dir2); // super(start, start.offset(dir1).offset(dir2), new BlockPos[]{start.offset(dir1), start.offset(dir1).up(), start.offset(dir2), start.offset(dir2).up(), start.offset(dir1).offset(dir2), start.offset(dir1).offset(dir2).up()}, new BlockPos[]{start.offset(dir1).offset(dir2).down()}); } - private MovementDiagonal(BetterBlockPos start, BetterBlockPos dir1, BetterBlockPos dir2, EnumFacing drr2) { - this(start, dir1.offset(drr2), dir1, dir2); + private MovementDiagonal(IBaritone baritone, BetterBlockPos start, BetterBlockPos dir1, BetterBlockPos dir2, EnumFacing drr2) { + this(baritone, start, dir1.offset(drr2), dir1, dir2); } - private MovementDiagonal(BetterBlockPos start, BetterBlockPos end, BetterBlockPos dir1, BetterBlockPos dir2) { - super(start, end, new BetterBlockPos[]{dir1, dir1.up(), dir2, dir2.up(), end, end.up()}); + private MovementDiagonal(IBaritone baritone, BetterBlockPos start, BetterBlockPos end, BetterBlockPos dir1, BetterBlockPos dir2) { + super(baritone, start, end, new BetterBlockPos[]{dir1, dir1.up(), dir2, dir2.up(), end, end.up()}); } @Override @@ -61,11 +62,11 @@ public class MovementDiagonal extends Movement { return COST_INF; } IBlockState destInto = context.get(destX, y, destZ); - if (!MovementHelper.canWalkThrough(context, destX, y, destZ, destInto) || !MovementHelper.canWalkThrough(context, destX, y + 1, destZ)) { + if (!MovementHelper.canWalkThrough(context.bsi(), destX, y, destZ, destInto) || !MovementHelper.canWalkThrough(context.bsi(), destX, y + 1, destZ)) { return COST_INF; } IBlockState destWalkOn = context.get(destX, y - 1, destZ); - if (!MovementHelper.canWalkOn(context, destX, y - 1, destZ, destWalkOn)) { + if (!MovementHelper.canWalkOn(context.bsi(), destX, y - 1, destZ, destWalkOn)) { return COST_INF; } double multiplier = WALK_ONE_BLOCK_COST; @@ -140,14 +141,14 @@ public class MovementDiagonal extends Movement { return state; } - if (playerFeet().equals(dest)) { + if (ctx.playerFeet().equals(dest)) { state.setStatus(MovementStatus.SUCCESS); return state; } - if (!MovementHelper.isLiquid(playerFeet())) { - state.setInput(InputOverrideHandler.Input.SPRINT, true); + if (!MovementHelper.isLiquid(ctx, ctx.playerFeet())) { + state.setInput(Input.SPRINT, true); } - MovementHelper.moveTowards(state, dest); + MovementHelper.moveTowards(ctx, state, dest); return state; } @@ -163,7 +164,7 @@ public class MovementDiagonal extends Movement { } List result = new ArrayList<>(); for (int i = 4; i < 6; i++) { - if (!MovementHelper.canWalkThrough(positionsToBreak[i])) { + if (!MovementHelper.canWalkThrough(ctx, positionsToBreak[i])) { result.add(positionsToBreak[i]); } } @@ -178,7 +179,7 @@ public class MovementDiagonal extends Movement { } List result = new ArrayList<>(); for (int i = 0; i < 4; i++) { - if (!MovementHelper.canWalkThrough(positionsToBreak[i])) { + if (!MovementHelper.canWalkThrough(ctx, positionsToBreak[i])) { result.add(positionsToBreak[i]); } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java index 07c101e6..f18fc538 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java @@ -17,6 +17,7 @@ package baritone.pathing.movement.movements; +import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; import baritone.pathing.movement.CalculationContext; @@ -31,8 +32,8 @@ public class MovementDownward extends Movement { private int numTicks = 0; - public MovementDownward(BetterBlockPos start, BetterBlockPos end) { - super(start, end, new BetterBlockPos[]{end}); + public MovementDownward(IBaritone baritone, BetterBlockPos start, BetterBlockPos end) { + super(baritone, start, end, new BetterBlockPos[]{end}); } @Override @@ -47,7 +48,7 @@ public class MovementDownward extends Movement { } public static double cost(CalculationContext context, int x, int y, int z) { - if (!MovementHelper.canWalkOn(context, x, y - 2, z)) { + if (!MovementHelper.canWalkOn(context.bsi(), x, y - 2, z)) { return COST_INF; } IBlockState d = context.get(x, y - 1, z); @@ -68,17 +69,17 @@ public class MovementDownward extends Movement { return state; } - if (playerFeet().equals(dest)) { + if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } - double diffX = player().posX - (dest.getX() + 0.5); - double diffZ = player().posZ - (dest.getZ() + 0.5); + double diffX = ctx.player().posX - (dest.getX() + 0.5); + double diffZ = ctx.player().posZ - (dest.getZ() + 0.5); double ab = Math.sqrt(diffX * diffX + diffZ * diffZ); if (numTicks++ < 10 && ab < 0.2) { return state; } - MovementHelper.moveTowards(state, positionsToBreak[0]); + MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); return state; } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index ba57eeac..ef89919b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -18,17 +18,18 @@ package baritone.pathing.movement.movements; import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.VecUtils; +import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementState; import baritone.pathing.movement.MovementState.MovementTarget; -import baritone.utils.InputOverrideHandler; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; @@ -42,8 +43,8 @@ public class MovementFall extends Movement { private static final ItemStack STACK_BUCKET_WATER = new ItemStack(Items.WATER_BUCKET); private static final ItemStack STACK_BUCKET_EMPTY = new ItemStack(Items.BUCKET); - public MovementFall(BetterBlockPos src, BetterBlockPos dest) { - super(src, dest, MovementFall.buildPositionsToBreak(src, dest)); + public MovementFall(IBaritone baritone, BetterBlockPos src, BetterBlockPos dest) { + super(baritone, src, dest, MovementFall.buildPositionsToBreak(src, dest)); } @Override @@ -63,40 +64,41 @@ public class MovementFall extends Movement { return state; } - BlockPos playerFeet = playerFeet(); + BlockPos playerFeet = ctx.playerFeet(); + Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)); Rotation targetRotation = null; - if (!MovementHelper.isWater(dest) && src.getY() - dest.getY() > Baritone.settings().maxFallHeightNoWater.get() && !playerFeet.equals(dest)) { - if (!InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_WATER)) || world().provider.isNether()) { + if (!MovementHelper.isWater(ctx, dest) && src.getY() - dest.getY() > Baritone.settings().maxFallHeightNoWater.get() && !playerFeet.equals(dest)) { + if (!InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER)) || ctx.world().provider.isNether()) { return state.setStatus(MovementStatus.UNREACHABLE); } - if (player().posY - dest.getY() < playerController().getBlockReachDistance()) { - player().inventory.currentItem = player().inventory.getSlotFor(STACK_BUCKET_WATER); + if (ctx.player().posY - dest.getY() < ctx.playerController().getBlockReachDistance() && !ctx.player().onGround) { + ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER); - targetRotation = new Rotation(player().rotationYaw, 90.0F); + targetRotation = new Rotation(toDest.getYaw(), 90.0F); - RayTraceResult trace = mc.objectMouseOver; - if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK && player().rotationPitch > 89.0F) { - state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); + RayTraceResult trace = ctx.objectMouseOver(); + if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK && ctx.player().rotationPitch > 89.0F) { + state.setInput(Input.CLICK_RIGHT, true); } } } if (targetRotation != null) { state.setTarget(new MovementTarget(targetRotation, true)); } else { - state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.getBlockPosCenter(dest)), false)); + state.setTarget(new MovementTarget(toDest, false)); } - if (playerFeet.equals(dest) && (player().posY - playerFeet.getY() < 0.094 || MovementHelper.isWater(dest))) { // 0.094 because lilypads - if (MovementHelper.isWater(dest)) { - if (InventoryPlayer.isHotbar(player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) { - player().inventory.currentItem = player().inventory.getSlotFor(STACK_BUCKET_EMPTY); - if (player().motionY >= 0) { - return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); + if (playerFeet.equals(dest) && (ctx.player().posY - playerFeet.getY() < 0.094 || MovementHelper.isWater(ctx, dest))) { // 0.094 because lilypads + if (MovementHelper.isWater(ctx, dest)) { + if (InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) { + ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY); + if (ctx.player().motionY >= 0) { + return state.setInput(Input.CLICK_RIGHT, true); } else { return state; } } else { - if (player().motionY >= 0) { + if (ctx.player().motionY >= 0) { return state.setStatus(MovementStatus.SUCCESS); } // don't else return state; we need to stay centered because this water might be flowing under the surface } @@ -105,8 +107,8 @@ public class MovementFall extends Movement { } } Vec3d destCenter = VecUtils.getBlockPosCenter(dest); // we are moving to the 0.5 center not the edge (like if we were falling on a ladder) - if (Math.abs(player().posX - destCenter.x) > 0.15 || Math.abs(player().posZ - destCenter.z) > 0.15) { - state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); + if (Math.abs(ctx.player().posX - destCenter.x) > 0.15 || Math.abs(ctx.player().posZ - destCenter.z) > 0.15) { + state.setInput(Input.MOVE_FORWARD, true); } return state; } @@ -115,7 +117,7 @@ public class MovementFall extends Movement { public boolean safeToCancel(MovementState state) { // if we haven't started walking off the edge yet, or if we're in the process of breaking blocks before doing the fall // then it's safe to cancel this - return playerFeet().equals(src) || state.getStatus() != MovementStatus.RUNNING; + return ctx.playerFeet().equals(src) || state.getStatus() != MovementStatus.RUNNING; } private static BetterBlockPos[] buildPositionsToBreak(BetterBlockPos src, BetterBlockPos dest) { @@ -138,7 +140,7 @@ public class MovementFall extends Movement { // only break if one of the first three needs to be broken // specifically ignore the last one which might be water for (int i = 0; i < 4 && i < positionsToBreak.length; i++) { - if (!MovementHelper.canWalkThrough(positionsToBreak[i])) { + if (!MovementHelper.canWalkThrough(ctx, positionsToBreak[i])) { return super.prepared(state); } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 2b255d62..80d6feb4 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -18,22 +18,23 @@ package baritone.pathing.movement.movements; import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.RayTraceUtils; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; +import baritone.api.utils.input.Input; 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 baritone.utils.Helper; -import baritone.utils.InputOverrideHandler; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; +import net.minecraft.block.BlockStairs; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -50,8 +51,8 @@ public class MovementParkour extends Movement { private final EnumFacing direction; private final int dist; - private MovementParkour(BetterBlockPos src, int dist, EnumFacing dir) { - super(src, src.offset(dir, dist), EMPTY, src.offset(dir, dist).down()); + private MovementParkour(IBaritone baritone, BetterBlockPos src, int dist, EnumFacing dir) { + super(baritone, src, src.offset(dir, dist), EMPTY, src.offset(dir, dist).down()); this.direction = dir; this.dist = dist; } @@ -60,7 +61,7 @@ public class MovementParkour extends Movement { MutableMoveResult res = new MutableMoveResult(); cost(context, src.x, src.y, src.z, direction, res); int dist = Math.abs(res.x - src.x) + Math.abs(res.z - src.z); - return new MovementParkour(src, dist, direction); + return new MovementParkour(context.getBaritone(), src, dist, direction); } public static void cost(CalculationContext context, int x, int y, int z, EnumFacing dir, MutableMoveResult res) { @@ -68,7 +69,7 @@ public class MovementParkour extends Movement { return; } IBlockState standingOn = context.get(x, y - 1, z); - if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || MovementHelper.isBottomSlab(standingOn)) { + if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || standingOn.getBlock() instanceof BlockStairs || MovementHelper.isBottomSlab(standingOn)) { return; } int xDiff = dir.getXOffset(); @@ -77,20 +78,20 @@ public class MovementParkour extends Movement { if (MovementHelper.avoidWalkingInto(adj.getBlock()) && adj.getBlock() != Blocks.WATER && adj.getBlock() != Blocks.FLOWING_WATER) { // magma sucks return; } - if (MovementHelper.canWalkOn(context,x + xDiff, y - 1, z + zDiff, adj)) { // don't parkour if we could just traverse (for now) + if (MovementHelper.canWalkOn(context.bsi(), x + xDiff, y - 1, z + zDiff, adj)) { // don't parkour if we could just traverse (for now) return; } - if (!MovementHelper.fullyPassable(context,x + xDiff, y, z + zDiff)) { + if (!MovementHelper.fullyPassable(context, x + xDiff, y, z + zDiff)) { return; } - if (!MovementHelper.fullyPassable(context,x + xDiff, y + 1, z + zDiff)) { + if (!MovementHelper.fullyPassable(context, x + xDiff, y + 1, z + zDiff)) { return; } - if (!MovementHelper.fullyPassable(context,x + xDiff, y + 2, z + zDiff)) { + if (!MovementHelper.fullyPassable(context, x + xDiff, y + 2, z + zDiff)) { return; } - if (!MovementHelper.fullyPassable(context,x, y + 2, z)) { + if (!MovementHelper.fullyPassable(context, x, y + 2, z)) { return; } int maxJump; @@ -106,11 +107,11 @@ public class MovementParkour extends Movement { for (int i = 2; i <= maxJump; i++) { // TODO perhaps dest.up(3) doesn't need to be fullyPassable, just canWalkThrough, possibly? for (int y2 = 0; y2 < 4; y2++) { - if (!MovementHelper.fullyPassable(context,x + xDiff * i, y + y2, z + zDiff * i)) { + if (!MovementHelper.fullyPassable(context, x + xDiff * i, y + y2, z + zDiff * i)) { return; } } - if (MovementHelper.canWalkOn(context,x + xDiff * i, y - 1, z + zDiff * i)) { + if (MovementHelper.canWalkOn(context.bsi(), x + xDiff * i, y - 1, z + zDiff * i)) { res.x = x + xDiff * i; res.y = y; res.z = z + zDiff * i; @@ -134,7 +135,7 @@ public class MovementParkour extends Movement { if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) { return; } - if (toPlace.getBlock() != Blocks.AIR && !MovementHelper.isWater(toPlace.getBlock()) && !MovementHelper.isReplacable(destX, y - 1, destZ, toPlace)) { + if (toPlace.getBlock() != Blocks.AIR && !MovementHelper.isWater(toPlace.getBlock()) && !MovementHelper.isReplacable(destX, y - 1, destZ, toPlace, context.world())) { return; } for (int i = 0; i < 5; i++) { @@ -143,7 +144,7 @@ public class MovementParkour extends Movement { if (againstX == x + xDiff * 3 && againstZ == z + zDiff * 3) { // we can't turn around that fast continue; } - if (MovementHelper.canPlaceAgainst(context,againstX, y - 1, againstZ)) { + if (MovementHelper.canPlaceAgainst(context.bsi(), againstX, y - 1, againstZ)) { res.x = destX; res.y = y; res.z = destZ; @@ -191,71 +192,71 @@ public class MovementParkour extends Movement { if (state.getStatus() != MovementStatus.RUNNING) { return state; } - if (player().isHandActive()) { + if (ctx.player().isHandActive()) { logDebug("Pausing parkour since hand is active"); return state; } if (dist >= 4) { - state.setInput(InputOverrideHandler.Input.SPRINT, true); + state.setInput(Input.SPRINT, true); } - MovementHelper.moveTowards(state, dest); - if (playerFeet().equals(dest)) { - Block d = BlockStateInterface.getBlock(dest); + MovementHelper.moveTowards(ctx, state, dest); + if (ctx.playerFeet().equals(dest)) { + Block d = BlockStateInterface.getBlock(ctx, dest); if (d == Blocks.VINE || d == Blocks.LADDER) { // it physically hurt me to add support for parkour jumping onto a vine // but i did it anyway return state.setStatus(MovementStatus.SUCCESS); } - if (player().posY - playerFeet().getY() < 0.094) { // lilypads + if (ctx.player().posY - ctx.playerFeet().getY() < 0.094) { // lilypads state.setStatus(MovementStatus.SUCCESS); } - } else if (!playerFeet().equals(src)) { - if (playerFeet().equals(src.offset(direction)) || player().posY - playerFeet().getY() > 0.0001) { + } else if (!ctx.playerFeet().equals(src)) { + if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().posY - ctx.playerFeet().getY() > 0.0001) { - if (!MovementHelper.canWalkOn(dest.down()) && !player().onGround) { + if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround) { BlockPos positionToPlace = dest.down(); for (int i = 0; i < 5; i++) { BlockPos against1 = positionToPlace.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); if (against1.up().equals(src.offset(direction, 3))) { // we can't turn around that fast continue; } - if (MovementHelper.canPlaceAgainst(against1)) { - if (!MovementHelper.throwaway(true)) {//get ready to place a throwaway block + if (MovementHelper.canPlaceAgainst(ctx, against1)) { + if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block return state.setStatus(MovementStatus.UNREACHABLE); } double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; double faceY = (dest.getY() + against1.getY()) * 0.5D; double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; - Rotation place = RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()); - RayTraceResult res = RayTraceUtils.rayTraceTowards(player(), place, playerController().getBlockReachDistance()); + Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); + RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance()); if (res != null && res.typeOfHit == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(dest.down())) { state.setTarget(new MovementState.MovementTarget(place, true)); } - RayTraceUtils.getSelectedBlock().ifPresent(selectedBlock -> { - EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; + ctx.getSelectedBlock().ifPresent(selectedBlock -> { + EnumFacing side = ctx.objectMouseOver().sideHit; if (Objects.equals(selectedBlock, against1) && selectedBlock.offset(side).equals(dest.down())) { - state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); + state.setInput(Input.CLICK_RIGHT, true); } }); } } } if (dist == 3) { // this is a 2 block gap, dest = src + direction * 3 - double xDiff = (src.x + 0.5) - player().posX; - double zDiff = (src.z + 0.5) - player().posZ; + double xDiff = (src.x + 0.5) - ctx.player().posX; + double zDiff = (src.z + 0.5) - ctx.player().posZ; double distFromStart = Math.max(Math.abs(xDiff), Math.abs(zDiff)); if (distFromStart < 0.7) { return state; } } - state.setInput(InputOverrideHandler.Input.JUMP, true); - } else if (!playerFeet().equals(dest.offset(direction, -1))) { - state.setInput(InputOverrideHandler.Input.SPRINT, false); - if (playerFeet().equals(src.offset(direction, -1))) { - MovementHelper.moveTowards(state, src); + state.setInput(Input.JUMP, true); + } else if (!ctx.playerFeet().equals(dest.offset(direction, -1))) { + state.setInput(Input.SPRINT, false); + if (ctx.playerFeet().equals(src.offset(direction, -1))) { + MovementHelper.moveTowards(ctx, state, src); } else { - MovementHelper.moveTowards(state, src.offset(direction, -1)); + MovementHelper.moveTowards(ctx, state, src.offset(direction, -1)); } } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 846e4018..78a62628 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -17,17 +17,18 @@ package baritone.pathing.movement.movements; +import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.VecUtils; +import baritone.api.utils.input.Input; 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 baritone.utils.InputOverrideHandler; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -36,8 +37,8 @@ import net.minecraft.util.math.Vec3d; public class MovementPillar extends Movement { - public MovementPillar(BetterBlockPos start, BetterBlockPos end) { - super(start, end, new BetterBlockPos[]{start.up(2)}, start); + public MovementPillar(IBaritone baritone, BetterBlockPos start, BetterBlockPos end) { + super(baritone, start, end, new BetterBlockPos[]{start.up(2)}, start); } @Override @@ -142,41 +143,41 @@ public class MovementPillar extends Movement { return state; } - IBlockState fromDown = BlockStateInterface.get(src); - if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(dest)) { + IBlockState fromDown = BlockStateInterface.get(ctx, src); + if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(ctx, dest)) { // stay centered while swimming up a water column - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.getBlockPosCenter(dest)), false)); + state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)), false)); Vec3d destCenter = VecUtils.getBlockPosCenter(dest); - if (Math.abs(player().posX - destCenter.x) > 0.2 || Math.abs(player().posZ - destCenter.z) > 0.2) { - state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); + if (Math.abs(ctx.player().posX - destCenter.x) > 0.2 || Math.abs(ctx.player().posZ - destCenter.z) > 0.2) { + state.setInput(Input.MOVE_FORWARD, true); } - if (playerFeet().equals(dest)) { + if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } return state; } boolean ladder = fromDown.getBlock() instanceof BlockLadder || fromDown.getBlock() instanceof BlockVine; boolean vine = fromDown.getBlock() instanceof BlockVine; - Rotation rotation = RotationUtils.calcRotationFromVec3d(player().getPositionEyes(1.0F), + Rotation rotation = RotationUtils.calcRotationFromVec3d(ctx.player().getPositionEyes(1.0F), VecUtils.getBlockPosCenter(positionToPlace), - new Rotation(player().rotationYaw, player().rotationPitch)); + new Rotation(ctx.player().rotationYaw, ctx.player().rotationPitch)); if (!ladder) { - state.setTarget(new MovementState.MovementTarget(new Rotation(player().rotationYaw, rotation.getPitch()), true)); + state.setTarget(new MovementState.MovementTarget(new Rotation(ctx.player().rotationYaw, rotation.getPitch()), true)); } - boolean blockIsThere = MovementHelper.canWalkOn(src) || ladder; + boolean blockIsThere = MovementHelper.canWalkOn(ctx, src) || ladder; if (ladder) { - BlockPos against = vine ? getAgainst(new CalculationContext(), src) : src.offset(fromDown.getValue(BlockLadder.FACING).getOpposite()); + BlockPos against = vine ? getAgainst(new CalculationContext(baritone), src) : src.offset(fromDown.getValue(BlockLadder.FACING).getOpposite()); if (against == null) { logDebug("Unable to climb vines"); return state.setStatus(MovementStatus.UNREACHABLE); } - if (playerFeet().equals(against.up()) || playerFeet().equals(dest)) { + if (ctx.playerFeet().equals(against.up()) || ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } - if (MovementHelper.isBottomSlab(BlockStateInterface.get(src.down()))) { - state.setInput(InputOverrideHandler.Input.JUMP, true); + if (MovementHelper.isBottomSlab(BlockStateInterface.get(ctx, src.down()))) { + state.setInput(Input.JUMP, true); } /* if (thePlayer.getPosition0().getX() != from.getX() || thePlayer.getPosition0().getZ() != from.getZ()) { @@ -184,47 +185,50 @@ public class MovementPillar extends Movement { } */ - MovementHelper.moveTowards(state, against); + MovementHelper.moveTowards(ctx, state, against); return state; } else { // Get ready to place a throwaway block - if (!MovementHelper.throwaway(true)) { + if (!MovementHelper.throwaway(ctx, true)) { return state.setStatus(MovementStatus.UNREACHABLE); } - // If our Y coordinate is above our goal, stop jumping - state.setInput(InputOverrideHandler.Input.JUMP, player().posY < dest.getY()); - state.setInput(InputOverrideHandler.Input.SNEAK, player().posY > dest.getY()); // delay placement by 1 tick for ncp compatibility + + state.setInput(Input.SNEAK, ctx.player().posY > dest.getY() || ctx.player().posY < src.getY() + 0.2D); // delay placement by 1 tick for ncp compatibility // since (lower down) we only right click once player.isSneaking, and that happens the tick after we request to sneak - double diffX = player().posX - (dest.getX() + 0.5); - double diffZ = player().posZ - (dest.getZ() + 0.5); + double diffX = ctx.player().posX - (dest.getX() + 0.5); + double diffZ = ctx.player().posZ - (dest.getZ() + 0.5); double dist = Math.sqrt(diffX * diffX + diffZ * diffZ); + double flatMotion = Math.sqrt(ctx.player().motionX * ctx.player().motionX + ctx.player().motionZ * ctx.player().motionZ); if (dist > 0.17) {//why 0.17? because it seemed like a good number, that's why //[explanation added after baritone port lol] also because it needs to be less than 0.2 because of the 0.3 sneak limit //and 0.17 is reasonably less than 0.2 // If it's been more than forty ticks of trying to jump and we aren't done yet, go forward, maybe we are stuck - state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); + state.setInput(Input.MOVE_FORWARD, true); // revise our target to both yaw and pitch if we're going to be moving forward state.setTarget(new MovementState.MovementTarget(rotation, true)); + } else if (flatMotion < 0.05) { + // If our Y coordinate is above our goal, stop jumping + state.setInput(Input.JUMP, ctx.player().posY < dest.getY()); } if (!blockIsThere) { - Block fr = BlockStateInterface.get(src).getBlock(); - if (!(fr instanceof BlockAir || fr.isReplaceable(world(), src))) { - state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); + Block fr = BlockStateInterface.get(ctx, src).getBlock(); + if (!(fr instanceof BlockAir || fr.isReplaceable(ctx.world(), src))) { + state.setInput(Input.CLICK_LEFT, true); blockIsThere = false; - } else if (player().isSneaking()) { // 1 tick after we're able to place - state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); + } else if (ctx.player().isSneaking()) { // 1 tick after we're able to place + state.setInput(Input.CLICK_RIGHT, true); } } } // If we are at our goal and the block below us is placed - if (playerFeet().equals(dest) && blockIsThere) { + if (ctx.playerFeet().equals(dest) && blockIsThere) { return state.setStatus(MovementStatus.SUCCESS); } @@ -233,13 +237,13 @@ public class MovementPillar extends Movement { @Override protected boolean prepared(MovementState state) { - if (playerFeet().equals(src) || playerFeet().equals(src.down())) { - Block block = BlockStateInterface.getBlock(src.down()); + if (ctx.playerFeet().equals(src) || ctx.playerFeet().equals(src.down())) { + Block block = BlockStateInterface.getBlock(ctx, src.down()); if (block == Blocks.LADDER || block == Blocks.VINE) { - state.setInput(InputOverrideHandler.Input.SNEAK, true); + state.setInput(Input.SNEAK, true); } } - if (MovementHelper.isWater(dest.up())) { + if (MovementHelper.isWater(ctx, dest.up())) { return true; } return super.prepared(state); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index a4f32855..aa25b5b6 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -18,17 +18,20 @@ package baritone.pathing.movement.movements; import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; -import baritone.api.utils.*; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.Rotation; +import baritone.api.utils.RotationUtils; +import baritone.api.utils.VecUtils; +import baritone.api.utils.input.Input; 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 baritone.utils.InputOverrideHandler; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -43,8 +46,8 @@ public class MovementTraverse extends Movement { */ private boolean wasTheBridgeBlockAlwaysThere = true; - public MovementTraverse(BetterBlockPos from, BetterBlockPos to) { - super(from, to, new BetterBlockPos[]{to.up(), to}, to.down()); + public MovementTraverse(IBaritone baritone, BetterBlockPos from, BetterBlockPos to) { + super(baritone, from, to, new BetterBlockPos[]{to.up(), to}, to.down()); } @Override @@ -63,7 +66,7 @@ public class MovementTraverse extends Movement { IBlockState pb1 = context.get(destX, y, destZ); IBlockState destOn = context.get(destX, y - 1, destZ); Block srcDown = context.getBlock(x, y - 1, z); - if (MovementHelper.canWalkOn(context, destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge + if (MovementHelper.canWalkOn(context.bsi(), destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge double WC = WALK_ONE_BLOCK_COST; boolean water = false; if (MovementHelper.isWater(pb0.getBlock()) || MovementHelper.isWater(pb1.getBlock())) { @@ -100,7 +103,7 @@ public class MovementTraverse extends Movement { if (srcDown == Blocks.LADDER || srcDown == Blocks.VINE) { return COST_INF; } - if (destOn.getBlock().equals(Blocks.AIR) || MovementHelper.isReplacable(destX, y - 1, destZ, destOn)) { + if (destOn.getBlock().equals(Blocks.AIR) || MovementHelper.isReplacable(destX, y - 1, destZ, destOn, context.world())) { boolean throughWater = MovementHelper.isWater(pb0.getBlock()) || MovementHelper.isWater(pb1.getBlock()); if (MovementHelper.isWater(destOn.getBlock()) && throughWater) { return COST_INF; @@ -121,7 +124,7 @@ public class MovementTraverse extends Movement { if (againstX == x && againstZ == z) { continue; } - if (MovementHelper.canPlaceAgainst(context, againstX, y - 1, againstZ)) { + if (MovementHelper.canPlaceAgainst(context.bsi(), againstX, y - 1, againstZ)) { return WC + context.placeBlockCost() + hardness1 + hardness2; } } @@ -152,86 +155,89 @@ public class MovementTraverse extends Movement { return state; } // and if it's fine to walk into the blocks in front - if (MovementHelper.avoidWalkingInto(BlockStateInterface.get(positionsToBreak[0]).getBlock())) { + if (MovementHelper.avoidWalkingInto(BlockStateInterface.get(ctx, positionsToBreak[0]).getBlock())) { return state; } - if (MovementHelper.avoidWalkingInto(BlockStateInterface.get(positionsToBreak[1]).getBlock())) { + if (MovementHelper.avoidWalkingInto(BlockStateInterface.get(ctx, positionsToBreak[1]).getBlock())) { return state; } // and we aren't already pressed up against the block - double dist = Math.max(Math.abs(player().posX - (dest.getX() + 0.5D)), Math.abs(player().posZ - (dest.getZ() + 0.5D))); + double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); if (dist < 0.83) { return state; } // combine the yaw to the center of the destination, and the pitch to the specific block we're trying to break // it's safe to do this since the two blocks we break (in a traverse) are right on top of each other and so will have the same yaw - float yawToDest = RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(dest)).getYaw(); + float yawToDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), dest)).getYaw(); float pitchToBreak = state.getTarget().getRotation().get().getPitch(); state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true)); - return state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, true); + return state.setInput(Input.MOVE_FORWARD, true); } //sneak may have been set to true in the PREPPING state while mining an adjacent block - state.setInput(InputOverrideHandler.Input.SNEAK, false); + state.setInput(Input.SNEAK, false); - Block fd = BlockStateInterface.get(src.down()).getBlock(); + Block fd = BlockStateInterface.get(ctx, src.down()).getBlock(); boolean ladder = fd instanceof BlockLadder || fd instanceof BlockVine; - IBlockState pb0 = BlockStateInterface.get(positionsToBreak[0]); - IBlockState pb1 = BlockStateInterface.get(positionsToBreak[1]); + IBlockState pb0 = BlockStateInterface.get(ctx, positionsToBreak[0]); + IBlockState pb1 = BlockStateInterface.get(ctx, positionsToBreak[1]); boolean door = pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor; if (door) { boolean isDoorActuallyBlockingUs = false; - if (pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(src, dest)) { + if (pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, src, dest)) { isDoorActuallyBlockingUs = true; - } else if (pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(dest, src)) { + } else if (pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, dest, src)) { isDoorActuallyBlockingUs = true; } if (isDoorActuallyBlockingUs && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { - return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(positionsToBreak[0])), true)) - .setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); + return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0])), true)) + .setInput(Input.CLICK_RIGHT, true); } } if (pb0.getBlock() instanceof BlockFenceGate || pb1.getBlock() instanceof BlockFenceGate) { BlockPos blocked = null; - if (!MovementHelper.isGatePassable(positionsToBreak[0], src.up())) { + if (!MovementHelper.isGatePassable(ctx, positionsToBreak[0], src.up())) { blocked = positionsToBreak[0]; - } else if (!MovementHelper.isGatePassable(positionsToBreak[1], src)) { + } else if (!MovementHelper.isGatePassable(ctx, positionsToBreak[1], src)) { blocked = positionsToBreak[1]; } if (blocked != null) { - return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), VecUtils.calculateBlockCenter(blocked)), true)) - .setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); + return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), blocked)), true)) + .setInput(Input.CLICK_RIGHT, true); } } - boolean isTheBridgeBlockThere = MovementHelper.canWalkOn(positionToPlace) || ladder; - BlockPos whereAmI = playerFeet(); + boolean isTheBridgeBlockThere = MovementHelper.canWalkOn(ctx, positionToPlace) || ladder; + BlockPos whereAmI = ctx.playerFeet(); if (whereAmI.getY() != dest.getY() && !ladder) { logDebug("Wrong Y coordinate"); if (whereAmI.getY() < dest.getY()) { - state.setInput(InputOverrideHandler.Input.JUMP, true); + state.setInput(Input.JUMP, true); } return state; } if (isTheBridgeBlockThere) { - if (playerFeet().equals(dest)) { + if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } - if (wasTheBridgeBlockAlwaysThere && !MovementHelper.isLiquid(playerFeet())) { - state.setInput(InputOverrideHandler.Input.SPRINT, true); + BlockPos into = dest.subtract(src).add(dest); + Block intoBelow = BlockStateInterface.get(ctx, into).getBlock(); + Block intoAbove = BlockStateInterface.get(ctx, into.up()).getBlock(); + if (wasTheBridgeBlockAlwaysThere && !MovementHelper.isLiquid(ctx, ctx.playerFeet()) && !MovementHelper.avoidWalkingInto(intoBelow) && !MovementHelper.avoidWalkingInto(intoAbove)) { + state.setInput(Input.SPRINT, true); } - Block destDown = BlockStateInterface.get(dest.down()).getBlock(); + Block destDown = BlockStateInterface.get(ctx, dest.down()).getBlock(); if (whereAmI.getY() != dest.getY() && ladder && (destDown instanceof BlockVine || destDown instanceof BlockLadder)) { - new MovementPillar(dest.down(), dest).updateState(state); // i'm sorry + new MovementPillar(baritone, dest.down(), dest).updateState(state); // i'm sorry return state; } - MovementHelper.moveTowards(state, positionsToBreak[0]); + MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); return state; } else { wasTheBridgeBlockAlwaysThere = false; @@ -241,44 +247,44 @@ public class MovementTraverse extends Movement { continue; } against1 = against1.down(); - if (MovementHelper.canPlaceAgainst(against1)) { - if (!MovementHelper.throwaway(true)) { // get ready to place a throwaway block + if (MovementHelper.canPlaceAgainst(ctx, against1)) { + if (!MovementHelper.throwaway(ctx, true)) { // get ready to place a throwaway block logDebug("bb pls get me some blocks. dirt or cobble"); return state.setStatus(MovementStatus.UNREACHABLE); } if (!Baritone.settings().assumeSafeWalk.get()) { - state.setInput(InputOverrideHandler.Input.SNEAK, true); + state.setInput(Input.SNEAK, true); } - Block standingOn = BlockStateInterface.get(playerFeet().down()).getBlock(); + Block standingOn = BlockStateInterface.get(ctx, ctx.playerFeet().down()).getBlock(); if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 - double dist = Math.max(Math.abs(dest.getX() + 0.5 - player().posX), Math.abs(dest.getZ() + 0.5 - player().posZ)); + double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); if (dist < 0.85) { // 0.5 + 0.3 + epsilon - MovementHelper.moveTowards(state, dest); - return state.setInput(InputOverrideHandler.Input.MOVE_FORWARD, false) - .setInput(InputOverrideHandler.Input.MOVE_BACK, true); + MovementHelper.moveTowards(ctx, state, dest); + return state.setInput(Input.MOVE_FORWARD, false) + .setInput(Input.MOVE_BACK, true); } } - state.setInput(InputOverrideHandler.Input.MOVE_BACK, false); + state.setInput(Input.MOVE_BACK, false); double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; double faceY = (dest.getY() + against1.getY()) * 0.5D; double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()), true)); + state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true)); - EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; - if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) { - return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); + EnumFacing side = ctx.objectMouseOver().sideHit; + if (Objects.equals(ctx.getSelectedBlock().orElse(null), against1) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && ctx.getSelectedBlock().get().offset(side).equals(positionToPlace)) { + return state.setInput(Input.CLICK_RIGHT, true); } //System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); - return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); + return state.setInput(Input.CLICK_LEFT, true); } } if (!Baritone.settings().assumeSafeWalk.get()) { - state.setInput(InputOverrideHandler.Input.SNEAK, true); + state.setInput(Input.SNEAK, true); } if (whereAmI.equals(dest)) { // If we are in the block that we are trying to get to, we are sneaking over air and we need to place a block beneath us against the one we just walked off of // Out.log(from + " " + to + " " + faceX + "," + faceY + "," + faceZ + " " + whereAmI); - if (!MovementHelper.throwaway(true)) {// get ready to place a throwaway block + if (!MovementHelper.throwaway(ctx, true)) {// get ready to place a throwaway block logDebug("bb pls get me some blocks. dirt or cobble"); return state.setStatus(MovementStatus.UNREACHABLE); } @@ -288,24 +294,24 @@ public class MovementTraverse extends Movement { // faceX, faceY, faceZ is the middle of the face between from and to BlockPos goalLook = src.down(); // this is the block we were just standing on, and the one we want to place against - Rotation backToFace = RotationUtils.calcRotationFromVec3d(playerHead(), new Vec3d(faceX, faceY, faceZ), playerRotations()); + Rotation backToFace = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); float pitch = backToFace.getPitch(); - double dist = Math.max(Math.abs(player().posX - faceX), Math.abs(player().posZ - faceZ)); + double dist = Math.max(Math.abs(ctx.player().posX - faceX), Math.abs(ctx.player().posZ - faceZ)); if (dist < 0.29) { - float yaw = RotationUtils.calcRotationFromVec3d(VecUtils.getBlockPosCenter(dest), playerHead(), playerRotations()).getYaw(); + float yaw = RotationUtils.calcRotationFromVec3d(VecUtils.getBlockPosCenter(dest), ctx.playerHead(), ctx.playerRotations()).getYaw(); state.setTarget(new MovementState.MovementTarget(new Rotation(yaw, pitch), true)); - state.setInput(InputOverrideHandler.Input.MOVE_BACK, true); + state.setInput(Input.MOVE_BACK, true); } else { state.setTarget(new MovementState.MovementTarget(backToFace, true)); } - state.setInput(InputOverrideHandler.Input.SNEAK, true); - if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), goalLook)) { - return state.setInput(InputOverrideHandler.Input.CLICK_RIGHT, true); // wait to right click until we are able to place + state.setInput(Input.SNEAK, true); + if (Objects.equals(ctx.getSelectedBlock().orElse(null), goalLook)) { + return state.setInput(Input.CLICK_RIGHT, true); // wait to right click until we are able to place } // Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt()); - return state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); + return state.setInput(Input.CLICK_LEFT, true); } else { - MovementHelper.moveTowards(state, positionsToBreak[0]); + MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); return state; // TODO MovementManager.moveTowardsBlock(to); // move towards not look at because if we are bridging for a couple blocks in a row, it is faster if we dont spin around and walk forwards then spin around and place backwards for every block } @@ -317,15 +323,15 @@ public class MovementTraverse extends Movement { // if we're in the process of breaking blocks before walking forwards // or if this isn't a sneak place (the block is already there) // then it's safe to cancel this - return state.getStatus() != MovementStatus.RUNNING || MovementHelper.canWalkOn(dest.down()); + return state.getStatus() != MovementStatus.RUNNING || MovementHelper.canWalkOn(ctx, dest.down()); } @Override protected boolean prepared(MovementState state) { - if (playerFeet().equals(src) || playerFeet().equals(src.down())) { - Block block = BlockStateInterface.getBlock(src.down()); + if (ctx.playerFeet().equals(src) || ctx.playerFeet().equals(src.down())) { + Block block = BlockStateInterface.getBlock(ctx, src.down()); if (block == Blocks.LADDER || block == Blocks.VINE) { - state.setInput(InputOverrideHandler.Input.SNEAK, true); + state.setInput(Input.SNEAK, true); } } return super.prepared(state); diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 5cc472e6..171dd769 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -24,15 +24,16 @@ import baritone.api.pathing.movement.IMovement; import baritone.api.pathing.movement.MovementStatus; import baritone.api.pathing.path.IPathExecutor; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.IPlayerContext; import baritone.api.utils.VecUtils; +import baritone.api.utils.input.Input; +import baritone.behavior.PathingBehavior; import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.movements.*; -import baritone.utils.BlockBreakHelper; import baritone.utils.BlockStateInterface; import baritone.utils.Helper; -import baritone.utils.InputOverrideHandler; import net.minecraft.init.Blocks; import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; @@ -48,6 +49,7 @@ import static baritone.api.pathing.movement.MovementStatus.*; * @author leijurv */ public class PathExecutor implements IPathExecutor, Helper { + private static final double MAX_MAX_DIST_FROM_PATH = 3; private static final double MAX_DIST_FROM_PATH = 2; @@ -72,7 +74,12 @@ public class PathExecutor implements IPathExecutor, Helper { private HashSet toPlace = new HashSet<>(); private HashSet toWalkInto = new HashSet<>(); - public PathExecutor(IPath path) { + private PathingBehavior behavior; + private IPlayerContext ctx; + + public PathExecutor(PathingBehavior behavior, IPath path) { + this.behavior = behavior; + this.ctx = behavior.ctx; this.path = path; this.pathPosition = 0; } @@ -91,18 +98,18 @@ public class PathExecutor implements IPathExecutor, Helper { return true; // stop bugging me, I'm done } BetterBlockPos whereShouldIBe = path.positions().get(pathPosition); - BetterBlockPos whereAmI = playerFeet(); + BetterBlockPos whereAmI = ctx.playerFeet(); if (!whereShouldIBe.equals(whereAmI)) { - if (pathPosition == 0 && whereAmI.equals(whereShouldIBe.up()) && Math.abs(player().motionY) < 0.1 && !(path.movements().get(0) instanceof MovementAscend) && !(path.movements().get(0) instanceof MovementPillar)) { + if (pathPosition == 0 && whereAmI.equals(whereShouldIBe.up()) && Math.abs(ctx.player().motionY) < 0.1 && !(path.movements().get(0) instanceof MovementAscend) && !(path.movements().get(0) instanceof MovementPillar)) { // avoid the Wrong Y coordinate bug // TODO add a timer here - new MovementDownward(whereAmI, whereShouldIBe).update(); + new MovementDownward(behavior.baritone, whereAmI, whereShouldIBe).update(); return false; } //System.out.println("Should be at " + whereShouldIBe + " actually am at " + whereAmI); - if (!Blocks.AIR.equals(BlockStateInterface.getBlock(whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip + if (!Blocks.AIR.equals(BlockStateInterface.getBlock(ctx, whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip for (int i = 0; i < pathPosition - 1 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks if (whereAmI.equals(path.positions().get(i))) { logDebug("Skipping back " + (pathPosition - i) + " steps, to " + i); @@ -278,7 +285,7 @@ public class PathExecutor implements IPathExecutor, Helper { double best = -1; BlockPos bestPos = null; for (BlockPos pos : path.positions()) { - double dist = VecUtils.entityDistanceToCenter(player(), pos); + double dist = VecUtils.entityDistanceToCenter(ctx.player(), pos); if (dist < best || best == -1) { best = dist; bestPos = pos; @@ -288,18 +295,18 @@ public class PathExecutor implements IPathExecutor, Helper { } private boolean shouldPause() { - Optional current = AbstractNodeCostSearch.getCurrentlyRunning(); + Optional current = behavior.getInProgress(); if (!current.isPresent()) { return false; } - if (!player().onGround) { + if (!ctx.player().onGround) { return false; } - if (!MovementHelper.canWalkOn(playerFeet().down())) { + if (!MovementHelper.canWalkOn(ctx, ctx.playerFeet().down())) { // we're in some kind of sketchy situation, maybe parkouring return false; } - if (!MovementHelper.canWalkThrough(playerFeet()) || !MovementHelper.canWalkThrough(playerFeet().up())) { + if (!MovementHelper.canWalkThrough(ctx, ctx.playerFeet()) || !MovementHelper.canWalkThrough(ctx, ctx.playerFeet().up())) { // suffocating? return false; } @@ -317,7 +324,7 @@ public class PathExecutor implements IPathExecutor, Helper { // the first block of the next path will always overlap // no need to pause our very last movement when it would have otherwise cleanly exited with MovementStatus SUCCESS positions = positions.subList(1, positions.size()); - return positions.contains(playerFeet()); + return positions.contains(ctx.playerFeet()); } private boolean possiblyOffPath(Tuple status, double leniency) { @@ -326,7 +333,7 @@ public class PathExecutor implements IPathExecutor, Helper { // when we're midair in the middle of a fall, we're very far from both the beginning and the end, but we aren't actually off path if (path.movements().get(pathPosition) instanceof MovementFall) { BlockPos fallDest = path.positions().get(pathPosition + 1); // .get(pathPosition) is the block we fell off of - return VecUtils.entityFlatDistanceToCenter(player(), fallDest) >= leniency; // ignore Y by using flat distance + return VecUtils.entityFlatDistanceToCenter(ctx.player(), fallDest) >= leniency; // ignore Y by using flat distance } else { return true; } @@ -339,7 +346,7 @@ public class PathExecutor implements IPathExecutor, Helper { * Regardless of current path position, snap to the current player feet if possible */ public boolean snipsnapifpossible() { - int index = path.positions().indexOf(playerFeet()); + int index = path.positions().indexOf(ctx.playerFeet()); if (index == -1) { return false; } @@ -349,59 +356,52 @@ public class PathExecutor implements IPathExecutor, Helper { } private void sprintIfRequested() { - // first and foremost, if allowSprint is off, or if we don't have enough hunger, don't try and sprint - if (!new CalculationContext().canSprint()) { - Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.SPRINT, false); - player().setSprinting(false); + if (!new CalculationContext(behavior.baritone).canSprint()) { + behavior.baritone.getInputOverrideHandler().setInputForceState(Input.SPRINT, false); + ctx.player().setSprinting(false); return; } // if the movement requested sprinting, then we're done - if (Baritone.INSTANCE.getInputOverrideHandler().isInputForcedDown(mc.gameSettings.keyBindSprint)) { - if (!player().isSprinting()) { - player().setSprinting(true); + if (behavior.baritone.getInputOverrideHandler().isInputForcedDown(mc.gameSettings.keyBindSprint)) { + if (!ctx.player().isSprinting()) { + ctx.player().setSprinting(true); } return; } // we'll take it from here, no need for minecraft to see we're holding down control and sprint for us - Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.SPRINT, false); + behavior.baritone.getInputOverrideHandler().setInputForceState(Input.SPRINT, false); // however, descend doesn't request sprinting, beceause it doesn't know the context of what movement comes after it IMovement current = path.movements().get(pathPosition); if (current instanceof MovementDescend && pathPosition < path.length() - 2) { - // (dest - src) + dest is offset 1 more in the same direction - // so it's the block we'd need to worry about running into if we decide to sprint straight through this descend - - BlockPos into = current.getDest().subtract(current.getSrc().down()).add(current.getDest()); - for (int y = 0; y <= 2; y++) { // we could hit any of the three blocks - if (MovementHelper.avoidWalkingInto(BlockStateInterface.getBlock(into.up(y)))) { - logDebug("Sprinting would be unsafe"); - player().setSprinting(false); - return; - } + if (((MovementDescend) current).safeMode()) { + logDebug("Sprinting would be unsafe"); + ctx.player().setSprinting(false); + return; } IMovement next = path.movements().get(pathPosition + 1); if (next instanceof MovementAscend && current.getDirection().up().equals(next.getDirection().down())) { // a descend then an ascend in the same direction - if (!player().isSprinting()) { - player().setSprinting(true); + if (!ctx.player().isSprinting()) { + ctx.player().setSprinting(true); } pathPosition++; // okay to skip clearKeys and / or onChangeInPathPosition here since this isn't possible to repeat, since it's asymmetric logDebug("Skipping descend to straight ascend"); return; } - if (canSprintInto(current, next)) { - if (playerFeet().equals(current.getDest())) { + if (canSprintInto(ctx, current, next)) { + if (ctx.playerFeet().equals(current.getDest())) { pathPosition++; onChangeInPathPosition(); } - if (!player().isSprinting()) { - player().setSprinting(true); + if (!ctx.player().isSprinting()) { + ctx.player().setSprinting(true); } return; } @@ -411,23 +411,23 @@ public class PathExecutor implements IPathExecutor, Helper { IMovement prev = path.movements().get(pathPosition - 1); if (prev instanceof MovementDescend && prev.getDirection().up().equals(current.getDirection().down())) { BlockPos center = current.getSrc().up(); - if (player().posY >= center.getY()) { // playerFeet adds 0.1251 to account for soul sand - Baritone.INSTANCE.getInputOverrideHandler().setInputForceState(InputOverrideHandler.Input.JUMP, false); - if (!player().isSprinting()) { - player().setSprinting(true); + if (ctx.player().posY >= center.getY()) { // playerFeet adds 0.1251 to account for soul sand + behavior.baritone.getInputOverrideHandler().setInputForceState(Input.JUMP, false); + if (!ctx.player().isSprinting()) { + ctx.player().setSprinting(true); } return; } } } - player().setSprinting(false); + ctx.player().setSprinting(false); } - private static boolean canSprintInto(IMovement current, IMovement next) { + private static boolean canSprintInto(IPlayerContext ctx, IMovement current, IMovement next) { if (next instanceof MovementDescend && next.getDirection().equals(current.getDirection())) { return true; } - if (next instanceof MovementTraverse && next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(next.getDest().down())) { + if (next instanceof MovementTraverse && next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(ctx, next.getDest().down())) { return true; } return next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.get(); @@ -438,14 +438,14 @@ public class PathExecutor implements IPathExecutor, Helper { ticksOnCurrent = 0; } - private static void clearKeys() { + private void clearKeys() { // i'm just sick and tired of this snippet being everywhere lol - Baritone.INSTANCE.getInputOverrideHandler().clearAllKeys(); + behavior.baritone.getInputOverrideHandler().clearAllKeys(); } private void cancel() { clearKeys(); - BlockBreakHelper.stopBreakingBlock(); + behavior.baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); pathPosition = path.length() + 3; failed = true; } @@ -458,11 +458,11 @@ public class PathExecutor implements IPathExecutor, Helper { if (next == null) { return cutIfTooLong(); } - return SplicedPath.trySplice(path, next.path).map(path -> { + return SplicedPath.trySplice(path, next.path, false).map(path -> { if (!path.getDest().equals(next.getPath().getDest())) { throw new IllegalStateException(); } - PathExecutor ret = new PathExecutor(path); + PathExecutor ret = new PathExecutor(behavior, path); ret.pathPosition = pathPosition; ret.currentMovementOriginalCostEstimate = currentMovementOriginalCostEstimate; ret.costEstimateIndex = costEstimateIndex; @@ -479,7 +479,7 @@ public class PathExecutor implements IPathExecutor, Helper { throw new IllegalStateException(); } logDebug("Discarding earliest segment movements, length cut from " + path.length() + " to " + newPath.length()); - PathExecutor ret = new PathExecutor(newPath); + PathExecutor ret = new PathExecutor(behavior, newPath); ret.pathPosition = pathPosition - cutoffAmt; ret.currentMovementOriginalCostEstimate = currentMovementOriginalCostEstimate; if (costEstimateIndex != null) { diff --git a/src/main/java/baritone/pathing/path/SplicedPath.java b/src/main/java/baritone/pathing/path/SplicedPath.java index 5048a84a..92610c86 100644 --- a/src/main/java/baritone/pathing/path/SplicedPath.java +++ b/src/main/java/baritone/pathing/path/SplicedPath.java @@ -62,7 +62,7 @@ public class SplicedPath extends PathBase { return numNodes; } - public static Optional trySplice(IPath first, IPath second) { + public static Optional trySplice(IPath first, IPath second, boolean allowOverlapCutoff) { if (second == null || first == null) { return Optional.empty(); } @@ -72,18 +72,31 @@ public class SplicedPath extends PathBase { if (!first.getDest().equals(second.getSrc())) { return Optional.empty(); } - HashSet a = new HashSet<>(first.positions()); - for (int i = 1; i < second.length(); i++) { - if (a.contains(second.positions().get(i))) { + HashSet secondPos = new HashSet<>(second.positions()); + int firstPositionInSecond = -1; + 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; + } + } + if (firstPositionInSecond != -1) { + if (!allowOverlapCutoff) { return Optional.empty(); } + } else { + firstPositionInSecond = first.length() - 1; + } + int positionInSecond = second.positions().indexOf(first.positions().get(firstPositionInSecond)); + if (!allowOverlapCutoff && positionInSecond != 0) { + throw new IllegalStateException(); } List positions = new ArrayList<>(); List movements = new ArrayList<>(); - positions.addAll(first.positions()); - positions.addAll(second.positions().subList(1, second.length())); - movements.addAll(first.movements()); - movements.addAll(second.movements()); + 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/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index 98c700e3..65f0ba7a 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -86,7 +86,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG if (calcFailed) { onLostControl(); } - if (this.goal == null || this.goal.isInGoal(playerFeet())) { + if (this.goal == null || this.goal.isInGoal(ctx.playerFeet())) { onLostControl(); // we're there xd } return new PathingCommand(this.goal, PathingCommandType.SET_GOAL_AND_PATH); diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index 41a59808..84ab0748 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -76,17 +76,14 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo if (entity.isDead) { return false; } - if (entity.equals(player())) { + if (entity.equals(ctx.player())) { return false; } - if (!world().loadedEntityList.contains(entity) && !world().playerEntities.contains(entity)) { - return false; - } - return true; + return ctx.world().loadedEntityList.contains(entity) || ctx.world().playerEntities.contains(entity); } private void scanWorld() { - cache = Stream.of(world().loadedEntityList, world().playerEntities).flatMap(List::stream).filter(this::followable).filter(this.filter).distinct().collect(Collectors.toCollection(ArrayList::new)); + cache = Stream.of(ctx.world().loadedEntityList, ctx.world().playerEntities).flatMap(List::stream).filter(this::followable).filter(this.filter).distinct().collect(Collectors.toCollection(ArrayList::new)); } @Override diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 0fb2abc0..95f2122b 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -24,6 +24,7 @@ import baritone.api.pathing.goals.GoalGetToBlock; import baritone.api.process.IGetToBlockProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; +import baritone.pathing.movement.CalculationContext; import baritone.utils.BaritoneProcessHelper; import net.minecraft.block.Block; import net.minecraft.util.math.BlockPos; @@ -46,7 +47,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl public void getToBlock(Block block) { gettingTo = block; knownLocations = null; - rescan(new ArrayList<>()); + rescan(new ArrayList<>(), new CalculationContext(baritone)); } @Override @@ -57,7 +58,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { if (knownLocations == null) { - rescan(new ArrayList<>()); + rescan(new ArrayList<>(), new CalculationContext(baritone)); } if (knownLocations.isEmpty()) { logDirect("No known locations of " + gettingTo + ", canceling GetToBlock"); @@ -76,10 +77,11 @@ 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); - Baritone.getExecutor().execute(() -> rescan(current)); + CalculationContext context = new CalculationContext(baritone); + Baritone.getExecutor().execute(() -> rescan(current, context)); } Goal goal = new GoalComposite(knownLocations.stream().map(GoalGetToBlock::new).toArray(Goal[]::new)); - if (goal.isInGoal(playerFeet())) { + if (goal.isInGoal(ctx.playerFeet())) { onLostControl(); } return new PathingCommand(goal, PathingCommandType.REVALIDATE_GOAL_AND_PATH); @@ -96,7 +98,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl return "Get To Block " + gettingTo; } - private void rescan(List known) { - knownLocations = MineProcess.searchWorld(Collections.singletonList(gettingTo), 64, baritone.getWorldProvider(), world(), known); + private void rescan(List known, CalculationContext context) { + knownLocations = MineProcess.searchWorld(context, Collections.singletonList(gettingTo), 64, known); } } \ No newline at end of file diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index c3a61426..4ea75387 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -22,16 +22,15 @@ 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; @@ -74,7 +73,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { if (desiredQuantity > 0) { Item item = mining.get(0).getItemDropped(mining.get(0).getDefaultState(), new Random(), 0); - int curr = player().inventory.mainInventory.stream().filter(stack -> item.equals(stack.getItem())).mapToInt(ItemStack::getCount).sum(); + int curr = ctx.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))); @@ -90,7 +89,8 @@ 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); - baritone.getExecutor().execute(() -> rescan(curr)); + CalculationContext context = new CalculationContext(baritone); + Baritone.getExecutor().execute(() -> rescan(curr, context)); } if (Baritone.settings().legitMine.get()) { addNearby(); @@ -118,9 +118,9 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro private Goal updateGoal() { List locs = knownOreLocations; if (!locs.isEmpty()) { - List locs2 = prune(new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT, world()); + List locs2 = prune(new CalculationContext(baritone), new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT); // can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final - Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(loc, locs2)).toArray(Goal[]::new)); + Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(ctx, loc, locs2)).toArray(Goal[]::new)); knownOreLocations = locs2; return goal; } @@ -138,12 +138,12 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } else { return new GoalYLevel(y); }*/ - branchPoint = playerFeet(); + branchPoint = ctx.playerFeet(); } // 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, Optional.of(y), branchPoint) { + branchPointRunaway = new GoalRunAway(1, y, branchPoint) { @Override public boolean isInGoal(int x, int y, int z) { return false; @@ -153,15 +153,15 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return branchPointRunaway; } - private void rescan(List already) { + private void rescan(List already, CalculationContext context) { if (mining == null) { return; } if (Baritone.settings().legitMine.get()) { return; } - List locs = searchWorld(mining, ORE_LOCATIONS_COUNT, baritone.getWorldProvider(), world(), already); - locs.addAll(droppedItemsScan(mining, world())); + List locs = searchWorld(context, mining, ORE_LOCATIONS_COUNT, already); + locs.addAll(droppedItemsScan(mining, ctx.world())); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); cancel(); @@ -170,26 +170,15 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro knownOreLocations = locs; } - private static Goal coalesce(BlockPos loc, List locs) { + private static Goal coalesce(IPlayerContext ctx, BlockPos loc, List locs) { if (!Baritone.settings().forceInternalMining.get()) { return new GoalTwoBlocks(loc); } - 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); - } - } + // 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()); } public static List droppedItemsScan(List mining, World world) { @@ -215,16 +204,13 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return ret; } - /*public static List searchWorld(List mining, int max, World world) { - - }*/ - public static List searchWorld(List mining, int max, WorldProvider provider, World world, List alreadyKnown) { + public static List searchWorld(CalculationContext ctx, List mining, int max, List alreadyKnown) { List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); //long b = System.currentTimeMillis(); for (Block m : mining) { if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(m)) { - locs.addAll(provider.getCurrentWorld().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, 1)); + locs.addAll(ctx.worldData().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 1)); } else { uninteresting.add(m); } @@ -235,43 +221,46 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } if (!uninteresting.isEmpty()) { //long before = System.currentTimeMillis(); - locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(uninteresting, max, 10, 26)); + locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), uninteresting, max, 10, 26)); //System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms"); } locs.addAll(alreadyKnown); - return prune(locs, mining, max, world); + return prune(ctx, locs, mining, max); } public void addNearby() { - knownOreLocations.addAll(droppedItemsScan(mining, world())); - BlockPos playerFeet = playerFeet(); - int searchDist = 4;//why four? idk + 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 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++) { - BlockPos pos = new BlockPos(x, y, z); - if (mining.contains(BlockStateInterface.getBlock(pos)) && RotationUtils.reachable(player(), pos, playerController().getBlockReachDistance()).isPresent()) {//crucial to only add blocks we can see because otherwise this is an x-ray and it'll get caught - knownOreLocations.add(pos); + // 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)); } } } } - knownOreLocations = prune(knownOreLocations, mining, ORE_LOCATIONS_COUNT, world()); + knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, mining, ORE_LOCATIONS_COUNT); } - public static List prune(List locs2, List mining, int max, World world) { - List dropped = droppedItemsScan(mining, world); + public static List prune(CalculationContext ctx, List locs2, List mining, int max) { + List dropped = droppedItemsScan(mining, ctx.world()); List locs = locs2 .stream() .distinct() // remove any that are within loaded chunks that aren't actually what we want - .filter(pos -> world.getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock()) || dropped.contains(pos)) + .filter(pos -> ctx.world().getChunk(pos) instanceof EmptyChunk || mining.contains(ctx.getBlock(pos.getX(), pos.getY(), pos.getZ())) || dropped.contains(pos)) // remove any that are implausible to mine (encased in bedrock, or touching lava) - .filter(MineProcess::plausibleToBreak) + .filter(pos -> MineProcess.plausibleToBreak(ctx.bsi(), pos)) - .sorted(Comparator.comparingDouble(Helper.HELPER.playerFeet()::distanceSq)) + .sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().playerFeet()::distanceSq)) .collect(Collectors.toList()); if (locs.size() > max) { @@ -280,12 +269,13 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return locs; } - public static boolean plausibleToBreak(BlockPos pos) { - if (MovementHelper.avoidBreaking(new CalculationContext(), pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(pos))) { + public static boolean plausibleToBreak(BlockStateInterface bsi, BlockPos pos) { + if (MovementHelper.avoidBreaking(bsi, pos.getX(), pos.getY(), pos.getZ(), bsi.get0(pos))) { return false; } + // bedrock above and below makes it implausible, otherwise we're good - return !(BlockStateInterface.getBlock(pos.up()) == Blocks.BEDROCK && BlockStateInterface.getBlock(pos.down()) == Blocks.BEDROCK); + return !(bsi.get0(pos.up()).getBlock() == Blocks.BEDROCK && bsi.get0(pos.down()).getBlock() == Blocks.BEDROCK); } @Override @@ -300,6 +290,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro this.knownOreLocations = new ArrayList<>(); this.branchPoint = null; this.branchPointRunaway = null; - rescan(new ArrayList<>()); + if (mining != null) { + rescan(new ArrayList<>(), new CalculationContext(baritone)); + } } } diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index 4aee4bd4..d86a36c4 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -17,11 +17,12 @@ package baritone.utils; -import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.event.events.TickEvent; import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; +import baritone.api.utils.IPlayerContext; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.settings.GameSettings; @@ -69,7 +70,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { @Override public void onTick(TickEvent event) { - + IPlayerContext ctx = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext(); // If we're on the main menu then create the test world and launch the integrated server if (mc.currentScreen instanceof GuiMainMenu) { System.out.println("Beginning Baritone automatic test routine"); @@ -101,15 +102,15 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { // Print out an update of our position every 5 seconds if (event.getCount() % 100 == 0) { - System.out.println(playerFeet() + " " + event.getCount()); + System.out.println(ctx.playerFeet() + " " + event.getCount()); } // Setup Baritone's pathing goal and (if needed) begin pathing - Baritone.INSTANCE.getCustomGoalProcess().setGoalAndPath(GOAL); + BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(GOAL); // If we have reached our goal, print a message and safely close the game - if (GOAL.isInGoal(playerFeet())) { - System.out.println("Successfully pathed to " + playerFeet() + " in " + event.getCount() + " ticks"); + if (GOAL.isInGoal(ctx.playerFeet())) { + System.out.println("Successfully pathed to " + ctx.playerFeet() + " in " + event.getCount() + " ticks"); mc.shutdown(); } diff --git a/src/main/java/baritone/utils/BaritoneProcessHelper.java b/src/main/java/baritone/utils/BaritoneProcessHelper.java index d01e815d..4f3870c5 100644 --- a/src/main/java/baritone/utils/BaritoneProcessHelper.java +++ b/src/main/java/baritone/utils/BaritoneProcessHelper.java @@ -19,11 +19,14 @@ package baritone.utils; import baritone.Baritone; import baritone.api.process.IBaritoneProcess; +import baritone.api.utils.IPlayerContext; public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper { + public static final double DEFAULT_PRIORITY = 0; protected final Baritone baritone; + protected final IPlayerContext ctx; private final double priority; public BaritoneProcessHelper(Baritone baritone) { @@ -32,6 +35,7 @@ public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper public BaritoneProcessHelper(Baritone baritone, double priority) { this.baritone = baritone; + this.ctx = baritone.getPlayerContext(); this.priority = priority; baritone.getPathingControlManager().registerProcess(this); } diff --git a/src/main/java/baritone/utils/BlockBreakHelper.java b/src/main/java/baritone/utils/BlockBreakHelper.java index b1e9ae53..d4d03f67 100644 --- a/src/main/java/baritone/utils/BlockBreakHelper.java +++ b/src/main/java/baritone/utils/BlockBreakHelper.java @@ -17,6 +17,9 @@ package baritone.utils; +import baritone.Baritone; +import baritone.api.BaritoneAPI; +import baritone.api.utils.IPlayerContext; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; @@ -32,41 +35,62 @@ public final class BlockBreakHelper implements Helper { * The last block that we tried to break, if this value changes * between attempts, then we re-initialize the breaking process. */ - private static BlockPos lastBlock; - private static boolean didBreakLastTick; + private BlockPos lastBlock; + private boolean didBreakLastTick; - private BlockBreakHelper() {} + private IPlayerContext playerContext; - public static void tryBreakBlock(BlockPos pos, EnumFacing side) { + public BlockBreakHelper(IPlayerContext playerContext) { + this.playerContext = playerContext; + } + + public void tryBreakBlock(BlockPos pos, EnumFacing side) { if (!pos.equals(lastBlock)) { - mc.playerController.clickBlock(pos, side); + playerContext.playerController().clickBlock(pos, side); } - if (mc.playerController.onPlayerDamageBlock(pos, side)) { - mc.player.swingArm(EnumHand.MAIN_HAND); + if (playerContext.playerController().onPlayerDamageBlock(pos, side)) { + playerContext.player().swingArm(EnumHand.MAIN_HAND); } lastBlock = pos; } - public static void stopBreakingBlock() { - if (mc.playerController != null) { - mc.playerController.resetBlockRemoving(); + public void stopBreakingBlock() { + if (playerContext.playerController() != null) { + playerContext.playerController().resetBlockRemoving(); } lastBlock = null; } - public static boolean tick(boolean isLeftClick) { - RayTraceResult trace = mc.objectMouseOver; + private boolean fakeBreak() { + if (playerContext != BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext()) { + // for a non primary player, we need to fake break always, CLICK_LEFT has no effect + return true; + } + if (!Baritone.settings().leftClickWorkaround.get()) { + // if this setting is false, we CLICK_LEFT regardless of gui status + return false; + } + return mc.currentScreen != null; + } + + public boolean tick(boolean isLeftClick) { + if (!fakeBreak()) { + if (didBreakLastTick) { + stopBreakingBlock(); + } + return isLeftClick; + } + + RayTraceResult trace = playerContext.objectMouseOver(); boolean isBlockTrace = trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK; - // If we're forcing left click, we're in a gui screen, and we're looking - // at a block, break the block without a direct game input manipulation. - if (mc.currentScreen != null && isLeftClick && isBlockTrace) { + if (isLeftClick && isBlockTrace) { tryBreakBlock(trace.getBlockPos(), trace.sideHit); didBreakLastTick = true; } else if (didBreakLastTick) { stopBreakingBlock(); didBreakLastTick = false; } - return !didBreakLastTick && isLeftClick; + return false; // fakeBreak is true so no matter what we aren't forcing CLICK_LEFT } } diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index 547e40c3..b6b264d0 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -18,13 +18,17 @@ package baritone.utils; import baritone.Baritone; +import baritone.api.utils.IPlayerContext; import baritone.cache.CachedRegion; import baritone.cache.WorldData; -import baritone.pathing.movement.CalculationContext; +import baritone.utils.accessor.IChunkProviderClient; +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.ChunkPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; @@ -33,33 +37,47 @@ import net.minecraft.world.chunk.Chunk; * * @author leijurv */ -public class BlockStateInterface implements Helper { +public class BlockStateInterface { - private final World world; + private final Long2ObjectMap loadedChunks; private final WorldData worldData; - private Chunk prev = null; private CachedRegion prevCached = null; private static final IBlockState AIR = Blocks.AIR.getDefaultState(); + public BlockStateInterface(IPlayerContext ctx) { + this(ctx.world(), (WorldData) ctx.worldData()); + } + public BlockStateInterface(World world, WorldData worldData) { this.worldData = worldData; - this.world = world; + this.loadedChunks = ((IChunkProviderClient) world.getChunkProvider()).loadedChunks(); + if (!Minecraft.getMinecraft().isCallingFromMinecraftThread()) { + throw new IllegalStateException(); + } } - public static Block getBlock(BlockPos pos) { // won't be called from the pathing thread because the pathing thread doesn't make a single blockpos pog - return get(pos).getBlock(); + public boolean worldContainsLoadedChunk(int blockX, int blockZ) { + return loadedChunks.containsKey(ChunkPos.asLong(blockX >> 4, blockZ >> 4)); } - public static IBlockState get(BlockPos pos) { - return new CalculationContext().get(pos); // immense iq + public static Block getBlock(IPlayerContext ctx, BlockPos pos) { // won't be called from the pathing thread because the pathing thread doesn't make a single blockpos pog + return get(ctx, pos).getBlock(); + } + + public static IBlockState get(IPlayerContext ctx, BlockPos pos) { + return new BlockStateInterface(ctx).get0(pos.getX(), pos.getY(), pos.getZ()); // immense iq // can't just do world().get because that doesn't work for out of bounds // and toBreak and stuff fails when the movement is instantiated out of load range but it's not able to BlockStateInterface.get what it's going to walk on } - public IBlockState get0(int x, int y, int z) { + public IBlockState get0(BlockPos pos) { + return get0(pos.getX(), pos.getY(), pos.getZ()); + } + + public IBlockState get0(int x, int y, int z) { // Mickey resigned // Invalid vertical position if (y < 0 || y >= 256) { @@ -77,8 +95,9 @@ public class BlockStateInterface implements Helper { if (cached != null && cached.x == x >> 4 && cached.z == z >> 4) { return cached.getBlockState(x, y, z); } - Chunk chunk = world.getChunk(x >> 4, z >> 4); - if (chunk.isLoaded()) { + Chunk chunk = loadedChunks.get(ChunkPos.asLong(x >> 4, z >> 4)); + + if (chunk != null && chunk.isLoaded()) { prev = chunk; return chunk.getBlockState(x, y, z); } @@ -109,8 +128,8 @@ public class BlockStateInterface implements Helper { if (prevChunk != null && prevChunk.x == x >> 4 && prevChunk.z == z >> 4) { return true; } - prevChunk = world.getChunk(x >> 4, z >> 4); - if (prevChunk.isLoaded()) { + prevChunk = loadedChunks.get(ChunkPos.asLong(x >> 4, z >> 4)); + if (prevChunk != null && prevChunk.isLoaded()) { prev = prevChunk; return true; } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 2f6bef6c..36d031c2 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -23,17 +23,16 @@ import baritone.api.cache.IWaypoint; import baritone.api.event.events.ChatEvent; import baritone.api.pathing.goals.*; import baritone.api.pathing.movement.ActionCosts; -import baritone.api.utils.RayTraceUtils; import baritone.api.utils.SettingsUtil; import baritone.behavior.Behavior; import baritone.behavior.PathingBehavior; import baritone.cache.ChunkPacker; import baritone.cache.Waypoint; -import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.process.CustomGoalProcess; +import comms.SocketConnection; import net.minecraft.block.Block; import net.minecraft.client.multiplayer.ChunkProviderClient; import net.minecraft.entity.Entity; @@ -41,6 +40,8 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.Chunk; +import java.io.IOException; +import java.net.Socket; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -165,7 +166,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { try { switch (params.length) { case 0: - goal = new GoalBlock(playerFeet()); + goal = new GoalBlock(ctx.playerFeet()); break; case 1: if (params[0].equals("clear") || params[0].equals("none")) { @@ -195,7 +196,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { if (msg.equals("path")) { if (pathingBehavior.getGoal() == null) { logDirect("No goal."); - } else if (pathingBehavior.getGoal().isInGoal(playerFeet())) { + } else if (pathingBehavior.getGoal().isInGoal(ctx.playerFeet())) { logDirect("Already in goal"); } else if (pathingBehavior.isPathing()) { logDirect("Currently executing a path. Please cancel it first."); @@ -205,9 +206,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("repack") || msg.equals("rescan")) { - ChunkProviderClient cli = world().getChunkProvider(); - int playerChunkX = playerFeet().getX() >> 4; - int playerChunkZ = playerFeet().getZ() >> 4; + ChunkProviderClient cli = (ChunkProviderClient) ctx.world().getChunkProvider(); + int playerChunkX = ctx.playerFeet().getX() >> 4; + int playerChunkZ = ctx.playerFeet().getZ() >> 4; int count = 0; for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) { for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) { @@ -232,7 +233,6 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } if (msg.equals("forcecancel")) { pathingBehavior.cancelEverything(); - AbstractNodeCostSearch.forceCancel(); pathingBehavior.forceCancel(); logDirect("ok force canceled"); return true; @@ -252,7 +252,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } else { logDirect("Goal must be GoalXZ or GoalBlock to invert"); logDirect("Inverting goal of player feet"); - runAwayFrom = playerFeet(); + runAwayFrom = ctx.playerFeet(); } customGoalProcess.setGoalAndPath(new GoalRunAway(1, runAwayFrom) { @Override @@ -271,11 +271,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { String name = msg.substring(6).trim(); Optional toFollow = Optional.empty(); if (name.length() == 0) { - toFollow = RayTraceUtils.getSelectedEntity(); + toFollow = ctx.getSelectedEntity(); } else { - for (EntityPlayer pl : world().playerEntities) { + for (EntityPlayer pl : ctx.world().playerEntities) { String theirName = pl.getName().trim().toLowerCase(); - if (!theirName.equals(player().getName().trim().toLowerCase()) && (theirName.contains(name) || name.contains(theirName))) { // don't follow ourselves lol + if (!theirName.equals(ctx.player().getName().trim().toLowerCase()) && (theirName.contains(name) || name.contains(theirName))) { // don't follow ourselves lol toFollow = Optional.of(pl); } } @@ -301,10 +301,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } if (msg.startsWith("find")) { String blockType = msg.substring(4).trim(); - LinkedList locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, 4); + LinkedList locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 4); logDirect("Have " + locs.size() + " locations"); for (BlockPos pos : locs) { - Block actually = BlockStateInterface.get(pos).getBlock(); + Block actually = BlockStateInterface.get(ctx, pos).getBlock(); if (!ChunkPacker.blockToString(actually).equalsIgnoreCase(blockType)) { System.out.println("Was looking for " + blockType + " but actually found " + actually + " " + ChunkPacker.blockToString(actually)); } @@ -334,7 +334,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } if (msg.startsWith("thisway")) { try { - Goal goal = GoalXZ.fromDirection(playerFeetAsVec(), player().rotationYaw, Double.parseDouble(msg.substring(7).trim())); + Goal goal = GoalXZ.fromDirection(ctx.playerFeetAsVec(), ctx.player().rotationYaw, Double.parseDouble(msg.substring(7).trim())); customGoalProcess.setGoal(goal); logDirect("Goal: " + goal); } catch (NumberFormatException ex) { @@ -365,7 +365,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } if (msg.startsWith("save")) { String name = msg.substring(4).trim(); - BlockPos pos = playerFeet(); + BlockPos pos = ctx.playerFeet(); if (name.contains(" ")) { logDirect("Name contains a space, assuming it's in the format 'save waypointName X Y Z'"); String[] parts = name.split(" "); @@ -421,7 +421,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { if (msg.equals("spawn") || msg.equals("bed")) { IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(Waypoint.Tag.BED); if (waypoint == null) { - BlockPos spawnPoint = player().getBedLocation(); + BlockPos spawnPoint = ctx.player().getBedLocation(); // for some reason the default spawnpoint is underground sometimes Goal goal = new GoalXZ(spawnPoint.getX(), spawnPoint.getZ()); logDirect("spawn not saved, defaulting to world spawn. set goal to " + goal); @@ -434,7 +434,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("sethome")) { - baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", Waypoint.Tag.HOME, playerFeet())); + baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", Waypoint.Tag.HOME, ctx.playerFeet())); logDirect("Saved. Say home to set goal."); return true; } @@ -450,7 +450,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("costs")) { - List moves = Stream.of(Moves.values()).map(x -> x.apply0(new CalculationContext(), playerFeet())).collect(Collectors.toCollection(ArrayList::new)); + List moves = Stream.of(Moves.values()).map(x -> x.apply0(new CalculationContext(baritone), ctx.playerFeet())).collect(Collectors.toCollection(ArrayList::new)); while (moves.contains(null)) { moves.remove(null); } @@ -466,6 +466,23 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } return true; } + if (msg.startsWith("connect")) { + String dest = msg.substring(7).trim(); + String[] parts = dest.split(" "); + if (parts.length != 2) { + logDirect("Unable to parse"); + return true; + } + try { + Socket s = new Socket(parts[0], Integer.parseInt(parts[1])); + SocketConnection conn = new SocketConnection(s); + baritone.getControllerBehavior().connectTo(conn); + logDirect("Created and attached socket connection"); + } catch (IOException | NumberFormatException e) { + logDirect("Unable to connect " + e); + } + return true; + } if (msg.equals("damn")) { logDirect("daniel"); } diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index 31b3fc10..0687d560 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -18,21 +18,14 @@ package baritone.utils; import baritone.Baritone; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.Rotation; -import net.minecraft.block.BlockSlab; import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.client.multiplayer.PlayerControllerMP; -import net.minecraft.client.multiplayer.WorldClient; -import net.minecraft.util.math.Vec3d; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; /** * @author Brady - * @since 8/1/2018 12:18 AM + * @since 8/1/2018 */ public interface Helper { @@ -51,48 +44,6 @@ public interface Helper { Minecraft mc = Minecraft.getMinecraft(); - default EntityPlayerSP player() { - if (!mc.isCallingFromMinecraftThread()) { - throw new IllegalStateException("h00000000"); - } - return mc.player; - } - - default PlayerControllerMP playerController() { // idk - if (!mc.isCallingFromMinecraftThread()) { - throw new IllegalStateException("h00000000"); - } - return mc.playerController; - } - - default WorldClient world() { - if (!mc.isCallingFromMinecraftThread()) { - throw new IllegalStateException("h00000000"); - } - return mc.world; - } - - 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 (BlockStateInterface.get(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); - } - /** * Send a message to chat only if chatDebug is on * diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 9c3eed7f..c6e19c15 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -19,11 +19,12 @@ package baritone.utils; import baritone.Baritone; import baritone.api.event.events.TickEvent; +import baritone.api.utils.IInputOverrideHandler; +import baritone.api.utils.input.Input; import baritone.behavior.Behavior; import net.minecraft.client.settings.KeyBinding; import org.lwjgl.input.Keyboard; -import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -33,25 +34,29 @@ import java.util.Map; * physically forcing down the assigned key. * * @author Brady - * @since 7/31/2018 11:20 PM + * @since 7/31/2018 */ -public final class InputOverrideHandler extends Behavior implements Helper { - - public InputOverrideHandler(Baritone baritone) { - super(baritone); - } +public final class InputOverrideHandler extends Behavior implements IInputOverrideHandler { /** * Maps inputs to whether or not we are forcing their state down. */ private final Map inputForceStateMap = new HashMap<>(); + private final BlockBreakHelper blockBreakHelper; + + public InputOverrideHandler(Baritone baritone) { + super(baritone); + this.blockBreakHelper = new BlockBreakHelper(baritone.getPlayerContext()); + } + /** * Returns whether or not we are forcing down the specified {@link KeyBinding}. * * @param key The KeyBinding object * @return Whether or not it is being forced down */ + @Override public final boolean isInputForcedDown(KeyBinding key) { return isInputForcedDown(Input.getInputForBind(key)); } @@ -62,6 +67,7 @@ public final class InputOverrideHandler extends Behavior implements Helper { * @param input The input * @return Whether or not it is being forced down */ + @Override public final boolean isInputForcedDown(Input input) { return input == null ? false : this.inputForceStateMap.getOrDefault(input, false); } @@ -72,6 +78,7 @@ public final class InputOverrideHandler extends Behavior implements Helper { * @param input The {@link Input} * @param forced Whether or not the state is being forced */ + @Override public final void setInputForceState(Input input, boolean forced) { this.inputForceStateMap.put(input, forced); } @@ -79,6 +86,7 @@ public final class InputOverrideHandler extends Behavior implements Helper { /** * Clears the override state for all keys */ + @Override public final void clearAllKeys() { this.inputForceStateMap.clear(); } @@ -86,7 +94,7 @@ public final class InputOverrideHandler extends Behavior implements Helper { @Override public final void onProcessKeyBinds() { // Simulate the key being held down this tick - for (InputOverrideHandler.Input input : Input.values()) { + for (Input input : Input.values()) { KeyBinding keyBinding = input.getKeyBinding(); if (isInputForcedDown(keyBinding) && !keyBinding.isKeyDown()) { @@ -104,93 +112,11 @@ public final class InputOverrideHandler extends Behavior implements Helper { if (event.getType() == TickEvent.Type.OUT) { return; } - if (Baritone.settings().leftClickWorkaround.get()) { - boolean stillClick = BlockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.keyBinding)); - setInputForceState(Input.CLICK_LEFT, stillClick); - } + boolean stillClick = blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT)); + setInputForceState(Input.CLICK_LEFT, stillClick); } - /** - * 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(mc.gameSettings.keyBindForward), - - /** - * The move back input - */ - MOVE_BACK(mc.gameSettings.keyBindBack), - - /** - * The move left input - */ - MOVE_LEFT(mc.gameSettings.keyBindLeft), - - /** - * The move right input - */ - MOVE_RIGHT(mc.gameSettings.keyBindRight), - - /** - * The attack input - */ - CLICK_LEFT(mc.gameSettings.keyBindAttack), - - /** - * The use item input - */ - CLICK_RIGHT(mc.gameSettings.keyBindUseItem), - - /** - * The jump input - */ - JUMP(mc.gameSettings.keyBindJump), - - /** - * The sneak input - */ - SNEAK(mc.gameSettings.keyBindSneak), - - /** - * The sprint input - */ - SPRINT(mc.gameSettings.keyBindSprint); - - /** - * Map of {@link KeyBinding} to {@link Input}. Values should be queried through {@link #getInputForBind(KeyBinding)} - */ - private static final Map bindToInputMap = new HashMap<>(); - - /** - * The actual game {@link KeyBinding} being forced. - */ - private final KeyBinding keyBinding; - - Input(KeyBinding keyBinding) { - this.keyBinding = keyBinding; - } - - /** - * @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)); - } + public BlockBreakHelper getBlockBreakHelper() { + return blockBreakHelper; } } diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index bf73149e..e14c14da 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -18,6 +18,7 @@ package baritone.utils; import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.event.events.RenderEvent; import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; @@ -27,16 +28,13 @@ import baritone.api.pathing.goals.GoalXZ; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.behavior.PathingBehavior; -import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.path.PathExecutor; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; -import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; @@ -51,7 +49,7 @@ import static org.lwjgl.opengl.GL11.*; /** * @author Brady - * @since 8/9/2018 4:39 PM + * @since 8/9/2018 */ public final class PathRenderer implements Helper { @@ -65,9 +63,26 @@ public final class PathRenderer implements Helper { // System.out.println(event.getPartialTicks()); float partialTicks = event.getPartialTicks(); Goal goal = behavior.getGoal(); - EntityPlayerSP player = mc.player; + + int thisPlayerDimension = behavior.baritone.getPlayerContext().world().provider.getDimensionType().getId(); + int currentRenderViewDimension = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().provider.getDimensionType().getId(); + + if (thisPlayerDimension != currentRenderViewDimension) { + // this is a path for a bot in a different dimension, don't render it + return; + } + + Entity renderView = mc.getRenderViewEntity(); + + if (renderView.world != BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world()) { + System.out.println("I have no idea what's going on"); + System.out.println("The primary baritone is in a different world than the render view entity"); + System.out.println("Not rendering the path"); + return; + } + if (goal != null && Baritone.settings().renderGoal.value) { - drawLitDankGoalBox(player, goal, partialTicks, Baritone.settings().colorGoalBox.get()); + drawLitDankGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.get()); } if (!Baritone.settings().renderPath.get()) { return; @@ -79,34 +94,32 @@ public final class PathRenderer implements Helper { PathExecutor current = behavior.getCurrent(); // this should prevent most race conditions? PathExecutor next = behavior.getNext(); // like, now it's not possible for current!=null to be true, then suddenly false because of another thread - // TODO is this enough, or do we need to acquire a lock here? - // TODO benchmark synchronized in render loop // Render the current path, if there is one if (current != null && current.getPath() != null) { int renderBegin = Math.max(current.getPosition() - 3, 0); - drawPath(current.getPath(), renderBegin, player, partialTicks, Baritone.settings().colorCurrentPath.get(), Baritone.settings().fadePath.get(), 10, 20); + drawPath(current.getPath(), renderBegin, renderView, partialTicks, Baritone.settings().colorCurrentPath.get(), Baritone.settings().fadePath.get(), 10, 20); } if (next != null && next.getPath() != null) { - drawPath(next.getPath(), 0, player, partialTicks, Baritone.settings().colorNextPath.get(), Baritone.settings().fadePath.get(), 10, 20); + drawPath(next.getPath(), 0, renderView, partialTicks, Baritone.settings().colorNextPath.get(), Baritone.settings().fadePath.get(), 10, 20); } //long split = System.nanoTime(); if (current != null) { - drawManySelectionBoxes(player, current.toBreak(), partialTicks, Baritone.settings().colorBlocksToBreak.get()); - drawManySelectionBoxes(player, current.toPlace(), partialTicks, Baritone.settings().colorBlocksToPlace.get()); - drawManySelectionBoxes(player, current.toWalkInto(), partialTicks, Baritone.settings().colorBlocksToWalkInto.get()); + drawManySelectionBoxes(renderView, current.toBreak(), partialTicks, Baritone.settings().colorBlocksToBreak.get()); + drawManySelectionBoxes(renderView, current.toPlace(), partialTicks, Baritone.settings().colorBlocksToPlace.get()); + drawManySelectionBoxes(renderView, current.toWalkInto(), partialTicks, Baritone.settings().colorBlocksToWalkInto.get()); } // If there is a path calculation currently running, render the path calculation process - AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(currentlyRunning -> { + behavior.getInProgress().ifPresent(currentlyRunning -> { currentlyRunning.bestPathSoFar().ifPresent(p -> { - drawPath(p, 0, player, partialTicks, Baritone.settings().colorBestPathSoFar.get(), Baritone.settings().fadePath.get(), 10, 20); + drawPath(p, 0, renderView, partialTicks, Baritone.settings().colorBestPathSoFar.get(), Baritone.settings().fadePath.get(), 10, 20); }); currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> { - drawPath(mr, 0, player, partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); - drawManySelectionBoxes(player, Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); + drawPath(mr, 0, renderView, partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); + drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); }); }); //long end = System.nanoTime(); @@ -116,7 +129,7 @@ public final class PathRenderer implements Helper { //} } - public static void drawPath(IPath path, int startIndex, EntityPlayerSP player, float partialTicks, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) { + public static void drawPath(IPath path, int startIndex, Entity player, float partialTicks, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F); @@ -175,7 +188,7 @@ public final class PathRenderer implements Helper { GlStateManager.disableBlend(); } - public static void drawLine(EntityPlayer player, double bp1x, double bp1y, double bp1z, double bp2x, double bp2y, double bp2z, float partialTicks) { + public static void drawLine(Entity player, double bp1x, double bp1y, double bp1z, double bp2x, double bp2y, double bp2z, float partialTicks) { double d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks; double d1 = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; double d2 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; @@ -187,7 +200,7 @@ public final class PathRenderer implements Helper { BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).endVertex(); } - public static void drawManySelectionBoxes(EntityPlayer player, Collection positions, float partialTicks, Color color) { + public static void drawManySelectionBoxes(Entity player, Collection positions, float partialTicks, Color color) { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F); @@ -206,12 +219,12 @@ public final class PathRenderer implements Helper { double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; positions.forEach(pos -> { - IBlockState state = BlockStateInterface.get(pos); + IBlockState state = BlockStateInterface.get(BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext(), pos); AxisAlignedBB toDraw; if (state.getBlock().equals(Blocks.AIR)) { - toDraw = Blocks.DIRT.getDefaultState().getSelectedBoundingBox(Minecraft.getMinecraft().world, pos); + toDraw = Blocks.DIRT.getDefaultState().getSelectedBoundingBox(player.world, pos); } else { - toDraw = state.getSelectedBoundingBox(Minecraft.getMinecraft().world, pos); + toDraw = state.getSelectedBoundingBox(player.world, pos); } toDraw = toDraw.expand(expand, expand, expand).offset(-renderPosX, -renderPosY, -renderPosZ); BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); @@ -249,7 +262,7 @@ public final class PathRenderer implements Helper { GlStateManager.disableBlend(); } - public static void drawLitDankGoalBox(EntityPlayer player, Goal goal, float partialTicks, Color color) { + public static void drawLitDankGoalBox(Entity player, Goal goal, float partialTicks, Color color) { double renderPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks; double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 9ea193a1..f5fff546 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -20,21 +20,18 @@ package baritone.utils; import baritone.Baritone; import baritone.api.event.events.TickEvent; import baritone.api.event.listener.AbstractGameEventListener; +import baritone.api.pathing.calc.IPathingControlManager; import baritone.api.pathing.goals.Goal; import baritone.api.process.IBaritoneProcess; import baritone.api.process.PathingCommand; import baritone.behavior.PathingBehavior; -import baritone.pathing.calc.AbstractNodeCostSearch; import baritone.pathing.path.PathExecutor; import net.minecraft.util.math.BlockPos; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; +import java.util.*; import java.util.stream.Collectors; -public class PathingControlManager { +public class PathingControlManager implements IPathingControlManager { private final Baritone baritone; private final HashSet processes; // unGh private IBaritoneProcess inControlLastTick; @@ -44,7 +41,7 @@ public class PathingControlManager { public PathingControlManager(Baritone baritone) { this.baritone = baritone; this.processes = new HashSet<>(); - baritone.registerEventListener(new AbstractGameEventListener() { // needs to be after all behavior ticks + baritone.getGameEventHandler().registerEventListener(new AbstractGameEventListener() { // needs to be after all behavior ticks @Override public void onTick(TickEvent event) { if (event.getType() == TickEvent.Type.OUT) { @@ -55,12 +52,16 @@ public class PathingControlManager { }); } + @Override public void registerProcess(IBaritoneProcess process) { process.onLostControl(); // make sure it's reset processes.add(process); } - public void cancelEverything() { + public void cancelEverything() { // called by PathingBehavior on TickEvent Type OUT + inControlLastTick = null; + inControlThisTick = null; + command = null; for (IBaritoneProcess proc : processes) { proc.onLostControl(); if (proc.isActive() && !proc.isTemporary()) { // it's okay for a temporary thing (like combat pause) to maintain control even if you say to cancel @@ -70,8 +71,14 @@ public class PathingControlManager { } } - public IBaritoneProcess inControlThisTick() { - return inControlThisTick; + @Override + public Optional mostRecentInControl() { + return Optional.ofNullable(inControlThisTick); + } + + @Override + public Optional mostRecentCommand() { + return Optional.ofNullable(command); } public void preTick() { @@ -90,12 +97,12 @@ public class PathingControlManager { p.cancelSegmentIfSafe(); break; case FORCE_REVALIDATE_GOAL_AND_PATH: - if (!p.isPathing() && !AbstractNodeCostSearch.getCurrentlyRunning().isPresent()) { + if (!p.isPathing() && !p.getInProgress().isPresent()) { p.secretInternalSetGoalAndPath(command.goal); } break; case REVALIDATE_GOAL_AND_PATH: - if (!p.isPathing() && !AbstractNodeCostSearch.getCurrentlyRunning().isPresent()) { + if (!p.isPathing() && !p.getInProgress().isPresent()) { p.secretInternalSetGoalAndPath(command.goal); } break; diff --git a/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java index 8606bc3f..50582b8f 100644 --- a/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java +++ b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java @@ -22,10 +22,9 @@ import baritone.cache.WorldProvider; import java.io.File; /** - * @see WorldProvider - * * @author Brady - * @since 8/4/2018 11:36 AM + * @see WorldProvider + * @since 8/4/2018 */ public interface IAnvilChunkLoader { diff --git a/src/main/java/baritone/utils/accessor/IChunkProviderClient.java b/src/main/java/baritone/utils/accessor/IChunkProviderClient.java new file mode 100644 index 00000000..19f14685 --- /dev/null +++ b/src/main/java/baritone/utils/accessor/IChunkProviderClient.java @@ -0,0 +1,25 @@ +/* + * 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.utils.accessor; + +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import net.minecraft.world.chunk.Chunk; + +public interface IChunkProviderClient { + Long2ObjectMap loadedChunks(); +} diff --git a/src/main/java/baritone/utils/accessor/IChunkProviderServer.java b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java index 176f05a3..e3e412b5 100644 --- a/src/main/java/baritone/utils/accessor/IChunkProviderServer.java +++ b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java @@ -21,10 +21,9 @@ import net.minecraft.world.WorldProvider; import net.minecraft.world.chunk.storage.IChunkLoader; /** - * @see WorldProvider - * * @author Brady - * @since 8/4/2018 11:33 AM + * @see WorldProvider + * @since 8/4/2018 */ public interface IChunkProviderServer { diff --git a/src/main/java/baritone/utils/pathing/PathingBlockType.java b/src/main/java/baritone/utils/pathing/PathingBlockType.java index 35e21fc3..43a7ebef 100644 --- a/src/main/java/baritone/utils/pathing/PathingBlockType.java +++ b/src/main/java/baritone/utils/pathing/PathingBlockType.java @@ -19,7 +19,7 @@ package baritone.utils.pathing; /** * @author Brady - * @since 8/4/2018 1:11 AM + * @since 8/4/2018 */ public enum PathingBlockType { diff --git a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java new file mode 100644 index 00000000..a0b8e27c --- /dev/null +++ b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java @@ -0,0 +1,87 @@ +/* + * 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.utils.pathing; + +import baritone.Baritone; +import baritone.api.pathing.calc.IPath; +import baritone.api.pathing.goals.Goal; +import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.PathCalculationResult; +import baritone.behavior.PathingBehavior; +import baritone.pathing.calc.AbstractNodeCostSearch; +import baritone.pathing.movement.CalculationContext; +import baritone.pathing.path.SplicedPath; + +import java.util.Optional; +import java.util.function.Consumer; + +/** + * Calculate and splice many path segments to reach a goal + * + * @author leijurv + */ +public class SegmentedCalculator { + private final BetterBlockPos start; + private final Goal goal; + private final CalculationContext context; + + private SegmentedCalculator(BetterBlockPos start, Goal goal, CalculationContext context) { + this.start = start; + this.goal = goal; + this.context = context; + } + + private Optional doCalc() { + Optional soFar = Optional.empty(); + while (true) { + PathCalculationResult result = segment(soFar); + switch (result.getType()) { + case SUCCESS_SEGMENT: + 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; + default: // CANCELLATION and null should not be possible, nothing else has access to this, so it can't have been canceled + throw new IllegalStateException(); + } + 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); + soFar = Optional.of(combined); + } + } + + 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); + 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 + } + + public static void calculateSegmentsThreaded(BetterBlockPos start, Goal goal, CalculationContext context, Consumer> onCompletion) { + Baritone.getExecutor().execute(() -> { + Optional result; + try { + result = new SegmentedCalculator(start, goal, context).doCalc(); + } catch (Exception ex) { + ex.printStackTrace(); + result = Optional.empty(); + } + onCompletion.accept(result); + }); + } +} diff --git a/src/main/java/baritone/utils/player/PrimaryPlayerContext.java b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java new file mode 100644 index 00000000..4247e92b --- /dev/null +++ b/src/main/java/baritone/utils/player/PrimaryPlayerContext.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.utils.player; + +import baritone.api.BaritoneAPI; +import baritone.api.cache.IWorldData; +import baritone.api.utils.IPlayerContext; +import baritone.utils.Helper; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.multiplayer.PlayerControllerMP; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.world.World; + +/** + * Implementation of {@link IPlayerContext} that provides information about the local player. + * + * @author Brady + * @since 11/12/2018 + */ +public enum PrimaryPlayerContext implements IPlayerContext, Helper { + + INSTANCE; + + @Override + public EntityPlayerSP player() { + return mc.player; + } + + @Override + public PlayerControllerMP playerController() { + return mc.playerController; + } + + @Override + public World world() { + return mc.world; + } + + @Override + public IWorldData worldData() { + return BaritoneAPI.getProvider().getPrimaryBaritone().getWorldProvider().getCurrentWorld(); + } + + @Override + public RayTraceResult objectMouseOver() { + return mc.objectMouseOver; + } +}