From e81b6d4d96e498a5db60820dc332a689a2788cdf Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 12 Nov 2018 16:39:58 -0800 Subject: [PATCH 01/77] fought --- src/main/java/baritone/cache/WorldProvider.java | 4 ++-- src/main/java/baritone/process/FollowProcess.java | 5 +---- src/main/java/baritone/utils/InputOverrideHandler.java | 8 ++++---- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index dd6e3561..1bd27a98 100644 --- a/src/main/java/baritone/cache/WorldProvider.java +++ b/src/main/java/baritone/cache/WorldProvider.java @@ -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/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index 41a59808..959e3a48 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -79,10 +79,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo if (entity.equals(player())) { return false; } - if (!world().loadedEntityList.contains(entity) && !world().playerEntities.contains(entity)) { - return false; - } - return true; + return world().loadedEntityList.contains(entity) || world().playerEntities.contains(entity); } private void scanWorld() { diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 9c3eed7f..fc902cf1 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -37,15 +37,15 @@ import java.util.Map; */ public final class InputOverrideHandler extends Behavior implements Helper { - public InputOverrideHandler(Baritone baritone) { - super(baritone); - } - /** * Maps inputs to whether or not we are forcing their state down. */ private final Map inputForceStateMap = new HashMap<>(); + public InputOverrideHandler(Baritone baritone) { + super(baritone); + } + /** * Returns whether or not we are forcing down the specified {@link KeyBinding}. * From 1ab3e61984dc8ee3886629cbc2624fba922d3ff3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 12 Nov 2018 21:01:40 -0800 Subject: [PATCH 02/77] reformatted --- .../movement/movements/MovementParkour.java | 16 ++++++++-------- .../utils/accessor/IAnvilChunkLoader.java | 3 +-- .../utils/accessor/IChunkProviderServer.java | 3 +-- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 2b255d62..0b0e0e75 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -77,20 +77,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, 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 +106,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, x + xDiff * i, y - 1, z + zDiff * i)) { res.x = x + xDiff * i; res.y = y; res.z = z + zDiff * i; @@ -143,7 +143,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, againstX, y - 1, againstZ)) { res.x = destX; res.y = y; res.z = destZ; diff --git a/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java index 8606bc3f..73936deb 100644 --- a/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java +++ b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java @@ -22,9 +22,8 @@ import baritone.cache.WorldProvider; import java.io.File; /** - * @see WorldProvider - * * @author Brady + * @see WorldProvider * @since 8/4/2018 11:36 AM */ public interface IAnvilChunkLoader { diff --git a/src/main/java/baritone/utils/accessor/IChunkProviderServer.java b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java index 176f05a3..b5512a1a 100644 --- a/src/main/java/baritone/utils/accessor/IChunkProviderServer.java +++ b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java @@ -21,9 +21,8 @@ import net.minecraft.world.WorldProvider; import net.minecraft.world.chunk.storage.IChunkLoader; /** - * @see WorldProvider - * * @author Brady + * @see WorldProvider * @since 8/4/2018 11:33 AM */ public interface IChunkProviderServer { From bae34e5b80412e97e4a849b2f1d86831f1bd5b0d Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Nov 2018 11:50:29 -0600 Subject: [PATCH 03/77] Initial meme Still need to fix MovementHelper LUL --- src/api/java/baritone/api/IBaritone.java | 6 + .../java/baritone/api/cache/ICachedWorld.java | 4 +- .../baritone/api/cache/IWorldScanner.java | 5 +- .../api/pathing/movement/IMovement.java | 1 + .../api/utils/IInputOverrideHandler.java | 39 ++++++ .../baritone/api/utils/IPlayerContext.java | 50 ++++++++ .../java/baritone/api/utils/input/Input.java | 111 ++++++++++++++++++ src/main/java/baritone/Baritone.java | 13 ++ src/main/java/baritone/behavior/Behavior.java | 3 + .../java/baritone/behavior/LookBehavior.java | 20 ++-- .../baritone/behavior/MemoryBehavior.java | 8 +- .../baritone/behavior/PathingBehavior.java | 18 +-- src/main/java/baritone/cache/CachedWorld.java | 13 +- .../java/baritone/cache/WorldScanner.java | 11 +- src/main/java/baritone/pathing/calc/Path.java | 2 +- .../pathing/movement/CalculationContext.java | 18 ++- .../baritone/pathing/movement/Movement.java | 41 ++++--- .../pathing/movement/MovementHelper.java | 39 ++---- .../pathing/movement/MovementState.java | 2 +- .../java/baritone/pathing/movement/Moves.java | 107 ++++++++--------- .../movement/movements/MovementAscend.java | 33 +++--- .../movement/movements/MovementDescend.java | 27 +++-- .../movement/movements/MovementDiagonal.java | 23 ++-- .../movement/movements/MovementDownward.java | 13 +- .../movement/movements/MovementFall.java | 41 +++---- .../movement/movements/MovementParkour.java | 61 +++++----- .../movement/movements/MovementPillar.java | 55 ++++----- .../movement/movements/MovementTraverse.java | 85 +++++++------- .../baritone/pathing/path/PathExecutor.java | 77 ++++++------ .../baritone/process/CustomGoalProcess.java | 2 +- .../java/baritone/process/FollowProcess.java | 6 +- .../baritone/process/GetToBlockProcess.java | 6 +- .../java/baritone/process/MineProcess.java | 44 +++---- .../java/baritone/utils/BaritoneAutoTest.java | 11 +- .../baritone/utils/BaritoneProcessHelper.java | 4 + .../baritone/utils/BlockStateInterface.java | 3 +- .../utils/ExampleBaritoneControl.java | 29 +++-- src/main/java/baritone/utils/Helper.java | 9 +- .../baritone/utils/InputOverrideHandler.java | 97 ++------------- .../utils/player/AbstractPlayerContext.java | 40 +++++++ .../utils/player/LocalPlayerContext.java | 54 +++++++++ 41 files changed, 745 insertions(+), 486 deletions(-) create mode 100644 src/api/java/baritone/api/utils/IInputOverrideHandler.java create mode 100644 src/api/java/baritone/api/utils/IPlayerContext.java create mode 100644 src/api/java/baritone/api/utils/input/Input.java create mode 100644 src/main/java/baritone/utils/player/AbstractPlayerContext.java create mode 100644 src/main/java/baritone/utils/player/LocalPlayerContext.java diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index aee9dead..7646cb8f 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -27,6 +27,8 @@ 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 @@ -76,10 +78,14 @@ public interface IBaritone { */ IWorldScanner getWorldScanner(); + IInputOverrideHandler getInputOverrideHandler(); + ICustomGoalProcess getCustomGoalProcess(); IGetToBlockProcess getGetToBlockProcess(); + IPlayerContext getPlayerContext(); + /** * Registers a {@link IGameEventListener} with Baritone's "event bus". * 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/pathing/movement/IMovement.java b/src/api/java/baritone/api/pathing/movement/IMovement.java index 7b3eca5f..5c3eac14 100644 --- a/src/api/java/baritone/api/pathing/movement/IMovement.java +++ b/src/api/java/baritone/api/pathing/movement/IMovement.java @@ -18,6 +18,7 @@ package baritone.api.pathing.movement; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.IPlayerContext; import net.minecraft.util.math.BlockPos; import java.util.List; 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..b886c063 --- /dev/null +++ b/src/api/java/baritone/api/utils/IPlayerContext.java @@ -0,0 +1,50 @@ +/* + * 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 net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.multiplayer.PlayerControllerMP; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.World; + +/** + * @author Brady + * @since 11/12/2018 + */ +public interface IPlayerContext { + + EntityPlayerSP player(); + + PlayerControllerMP playerController(); + + World world(); + + BetterBlockPos playerFeet(); + + 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); + } +} 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..4abc0544 --- /dev/null +++ b/src/api/java/baritone/api/utils/input/Input.java @@ -0,0 +1,111 @@ +/* + * 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) { + 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/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index f4546012..b752b63e 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -21,6 +21,7 @@ import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.event.listener.IGameEventListener; +import baritone.api.utils.IPlayerContext; import baritone.behavior.Behavior; import baritone.behavior.LookBehavior; import baritone.behavior.MemoryBehavior; @@ -36,6 +37,7 @@ import baritone.utils.BaritoneAutoTest; import baritone.utils.ExampleBaritoneControl; import baritone.utils.InputOverrideHandler; import baritone.utils.PathingControlManager; +import baritone.utils.player.LocalPlayerContext; import net.minecraft.client.Minecraft; import java.io.File; @@ -139,6 +141,7 @@ public enum Baritone implements IBaritone { return this.gameEventHandler; } + @Override public InputOverrideHandler getInputOverrideHandler() { return this.inputOverrideHandler; } @@ -162,6 +165,11 @@ public enum Baritone implements IBaritone { return getToBlockProcess; } + @Override + public IPlayerContext getPlayerContext() { + return LocalPlayerContext.INSTANCE; + } + @Override public FollowProcess getFollowProcess() { return followProcess; @@ -192,6 +200,11 @@ public enum Baritone implements IBaritone { return worldProvider; } + /** + * TODO-yeet This shouldn't be baritone-instance specific + * + * @return world scanner instance + */ @Override public WorldScanner getWorldScanner() { return WorldScanner.INSTANCE; diff --git a/src/main/java/baritone/behavior/Behavior.java b/src/main/java/baritone/behavior/Behavior.java index 66434d7a..f1fe0d9f 100644 --- a/src/main/java/baritone/behavior/Behavior.java +++ b/src/main/java/baritone/behavior/Behavior.java @@ -19,6 +19,7 @@ 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. @@ -29,9 +30,11 @@ import baritone.api.behavior.IBehavior; 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/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index ee8548a2..de0af60d 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -69,24 +69,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 +114,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..f5ea8a32 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -68,7 +68,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) { @@ -127,7 +127,7 @@ public final class MemoryBehavior extends Behavior implements IMemoryBehavior, H @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 +135,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..1d2533ad 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -115,13 +115,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 @@ -314,7 +314,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) { @@ -338,11 +338,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * @return The starting {@link BlockPos} for a new path */ public BlockPos pathStart() { - BetterBlockPos feet = playerFeet(); + BetterBlockPos feet = ctx.playerFeet(); if (!MovementHelper.canWalkOn(feet.down())) { - if (player().onGround) { - double playerX = player().posX; - double playerZ = player().posZ; + 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++) { @@ -390,7 +390,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } isPathCalcInProgress = true; } - CalculationContext context = new CalculationContext(); // not safe to create on the other thread, it looks up a lot of stuff in minecraft + CalculationContext context = new CalculationContext(baritone); // not safe to create on the other thread, it looks up a lot of stuff in minecraft Baritone.getExecutor().execute(() -> { if (talkAboutIt) { logDebug("Starting to search for path from " + start + " to " + goal); @@ -421,7 +421,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) { diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index b775902e..9c73df70 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -106,10 +106,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 +119,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. @@ -192,7 +192,8 @@ public final class CachedWorld implements ICachedWorld, Helper { private BlockPos guessPosition() { WorldData data = Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); if (data != null && data.getCachedWorld() == this) { - return playerFeet(); + // TODO-yeet fix + return Baritone.INSTANCE.getPlayerContext().playerFeet(); } CachedChunk mostRecentlyModified = null; for (CachedRegion region : allRegions()) { diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index 6366b157..378bbc9c 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -18,6 +18,7 @@ package baritone.cache; import baritone.api.cache.IWorldScanner; +import baritone.api.utils.IPlayerContext; import baritone.utils.Helper; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -35,7 +36,7 @@ public enum WorldScanner implements IWorldScanner, Helper { 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 +44,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/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index 0b5b2cc7..ee3b182b 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -129,7 +129,7 @@ class Path extends PathBase { private Movement runBackwards(BetterBlockPos src, BetterBlockPos dest, double cost) { for (Moves moves : Moves.values()) { - Movement move = moves.apply0(context, src); + Movement move = moves.apply0(context.getBaritone(), src); if (move.getDest().equals(dest)) { // have to calculate the cost at calculation time so we can accurately judge whether a cost increase happened between cached calculation and real execution move.override(cost); diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index e419bb72..7d0d9dab 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; @@ -42,6 +42,7 @@ 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 this.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 f11e1955..e379d27b 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -17,13 +17,13 @@ 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 +34,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 { 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; @@ -66,21 +67,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; } @@ -99,7 +102,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { @Override public double calculateCostWithoutCaching() { - return calculateCost(new CalculationContext()); + return calculateCost(new CalculationContext(baritone)); } /** @@ -110,18 +113,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.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())); @@ -129,13 +132,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(); @@ -149,9 +152,9 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { for (BetterBlockPos blockPos : positionsToBreak) { if (!MovementHelper.canWalkThrough(blockPos) && !(BlockStateInterface.getBlock(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(blockPos)); state.setTarget(new MovementState.MovementTarget(reachable.get(), true)); if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), blockPos)) { state.setInput(Input.CLICK_LEFT, true); @@ -162,11 +165,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; } } diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index a7e9c378..c27de97a 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; @@ -63,7 +63,7 @@ public interface MovementHelper extends ActionCosts, Helper { * @return */ static boolean canWalkThrough(BetterBlockPos pos) { - return canWalkThrough(new CalculationContext(), pos.x, pos.y, pos.z, BlockStateInterface.get(pos)); + return canWalkThrough(new CalculationContext(Baritone.INSTANCE), pos.x, pos.y, pos.z, BlockStateInterface.get(pos)); } static boolean canWalkThrough(CalculationContext context, int x, int y, int z) { @@ -295,11 +295,11 @@ public interface MovementHelper extends ActionCosts, Helper { } static boolean canWalkOn(BetterBlockPos pos, IBlockState state) { - return canWalkOn(new CalculationContext(), pos.x, pos.y, pos.z, state); + return canWalkOn(new CalculationContext(Baritone.INSTANCE), 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)); + return canWalkOn(new CalculationContext(Baritone.INSTANCE), pos.x, pos.y, pos.z, BlockStateInterface.get(pos)); } static boolean canWalkOn(CalculationContext context, int x, int y, int z) { @@ -360,26 +360,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 +375,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 +415,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); } /** 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..ebb97081 100644 --- a/src/main/java/baritone/pathing/movement/Moves.java +++ b/src/main/java/baritone/pathing/movement/Moves.java @@ -17,6 +17,7 @@ package baritone.pathing.movement; +import baritone.api.IBaritone; import baritone.api.utils.BetterBlockPos; import baritone.pathing.movement.movements.*; import baritone.utils.pathing.MutableMoveResult; @@ -30,8 +31,8 @@ import net.minecraft.util.EnumFacing; public enum Moves { DOWNWARD(0, -1, 0) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementDownward(src, src.down()); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementDownward(baritone, src, src.down()); } @Override @@ -42,8 +43,8 @@ public enum Moves { PILLAR(0, +1, 0) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementPillar(src, src.up()); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementPillar(baritone, src, src.up()); } @Override @@ -54,8 +55,8 @@ public enum Moves { TRAVERSE_NORTH(0, 0, -1) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementTraverse(src, src.north()); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementTraverse(baritone, src, src.north()); } @Override @@ -66,8 +67,8 @@ public enum Moves { TRAVERSE_SOUTH(0, 0, +1) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementTraverse(src, src.south()); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementTraverse(baritone, src, src.south()); } @Override @@ -78,8 +79,8 @@ public enum Moves { TRAVERSE_EAST(+1, 0, 0) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementTraverse(src, src.east()); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementTraverse(baritone, src, src.east()); } @Override @@ -90,8 +91,8 @@ public enum Moves { TRAVERSE_WEST(-1, 0, 0) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementTraverse(src, src.west()); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementTraverse(baritone, src, src.west()); } @Override @@ -102,8 +103,8 @@ 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)); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementAscend(baritone, src, new BetterBlockPos(src.x, src.y + 1, src.z - 1)); } @Override @@ -114,8 +115,8 @@ 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)); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementAscend(baritone, src, new BetterBlockPos(src.x, src.y + 1, src.z + 1)); } @Override @@ -126,8 +127,8 @@ 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)); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementAscend(baritone, src, new BetterBlockPos(src.x + 1, src.y + 1, src.z)); } @Override @@ -138,8 +139,8 @@ 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)); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementAscend(baritone, src, new BetterBlockPos(src.x - 1, src.y + 1, src.z)); } @Override @@ -150,13 +151,13 @@ public enum Moves { DESCEND_EAST(+1, -1, 0, false, true) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { + public Movement apply0(IBaritone baritone, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(context, src.x, src.y, src.z, res); + apply(new CalculationContext(baritone), 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(baritone, 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(baritone, src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -168,13 +169,13 @@ public enum Moves { DESCEND_WEST(-1, -1, 0, false, true) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { + public Movement apply0(IBaritone baritone, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(context, src.x, src.y, src.z, res); + apply(new CalculationContext(baritone), 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(baritone, 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(baritone, src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -186,13 +187,13 @@ public enum Moves { DESCEND_NORTH(0, -1, -1, false, true) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { + public Movement apply0(IBaritone baritone, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(context, src.x, src.y, src.z, res); + apply(new CalculationContext(baritone), 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(baritone, 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(baritone, src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -204,13 +205,13 @@ public enum Moves { DESCEND_SOUTH(0, -1, +1, false, true) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { + public Movement apply0(IBaritone baritone, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(context, src.x, src.y, src.z, res); + apply(new CalculationContext(baritone), 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(baritone, 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(baritone, src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -222,8 +223,8 @@ public enum Moves { DIAGONAL_NORTHEAST(+1, 0, -1) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementDiagonal(src, EnumFacing.NORTH, EnumFacing.EAST); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementDiagonal(baritone, src, EnumFacing.NORTH, EnumFacing.EAST); } @Override @@ -234,8 +235,8 @@ public enum Moves { DIAGONAL_NORTHWEST(-1, 0, -1) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementDiagonal(src, EnumFacing.NORTH, EnumFacing.WEST); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementDiagonal(baritone, src, EnumFacing.NORTH, EnumFacing.WEST); } @Override @@ -246,8 +247,8 @@ public enum Moves { DIAGONAL_SOUTHEAST(+1, 0, +1) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementDiagonal(src, EnumFacing.SOUTH, EnumFacing.EAST); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementDiagonal(baritone, src, EnumFacing.SOUTH, EnumFacing.EAST); } @Override @@ -258,8 +259,8 @@ public enum Moves { DIAGONAL_SOUTHWEST(-1, 0, +1) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return new MovementDiagonal(src, EnumFacing.SOUTH, EnumFacing.WEST); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return new MovementDiagonal(baritone, src, EnumFacing.SOUTH, EnumFacing.WEST); } @Override @@ -270,8 +271,8 @@ public enum Moves { PARKOUR_NORTH(0, 0, -4, true, false) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return MovementParkour.cost(context, src, EnumFacing.NORTH); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return MovementParkour.cost(baritone, src, EnumFacing.NORTH); } @Override @@ -282,8 +283,8 @@ public enum Moves { PARKOUR_SOUTH(0, 0, +4, true, false) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return MovementParkour.cost(context, src, EnumFacing.SOUTH); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return MovementParkour.cost(baritone, src, EnumFacing.SOUTH); } @Override @@ -294,8 +295,8 @@ public enum Moves { PARKOUR_EAST(+4, 0, 0, true, false) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return MovementParkour.cost(context, src, EnumFacing.EAST); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return MovementParkour.cost(baritone, src, EnumFacing.EAST); } @Override @@ -306,8 +307,8 @@ public enum Moves { PARKOUR_WEST(-4, 0, 0, true, false) { @Override - public Movement apply0(CalculationContext context, BetterBlockPos src) { - return MovementParkour.cost(context, src, EnumFacing.WEST); + public Movement apply0(IBaritone baritone, BetterBlockPos src) { + return MovementParkour.cost(baritone, src, EnumFacing.WEST); } @Override @@ -335,7 +336,7 @@ public enum Moves { this(x, y, z, false, false); } - public abstract Movement apply0(CalculationContext context, BetterBlockPos src); + public abstract Movement apply0(IBaritone baritone, BetterBlockPos src); public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { if (dynamicXZ || dynamicY) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 1d161554..37897b53 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -18,16 +18,17 @@ 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; @@ -42,8 +43,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 @@ -161,7 +162,7 @@ public class MovementAscend extends Movement { return state; } - if (playerFeet().equals(dest)) { + if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } @@ -173,28 +174,28 @@ public class MovementAscend extends Movement { continue; } if (MovementHelper.canPlaceAgainst(anAgainst)) { - if (!MovementHelper.throwaway(true)) {//get ready to place a throwaway block + 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)); + state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true)); EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; RayTraceUtils.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,7 +204,7 @@ public class MovementAscend extends Movement { } return state.setStatus(MovementStatus.UNREACHABLE); } - MovementHelper.moveTowards(state, dest); + MovementHelper.moveTowards(ctx, state, dest); if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(BlockStateInterface.get(src.down()))) { return state; // don't jump while walking from a non double slab into a bottom slab } @@ -213,13 +214,13 @@ public class MovementAscend extends Movement { } 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,7 +229,7 @@ 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() { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index 84f0d781..22e8dbee 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -18,13 +18,14 @@ 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.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.pathing.MutableMoveResult; import net.minecraft.block.Block; import net.minecraft.block.BlockFalling; @@ -36,8 +37,8 @@ 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 @@ -181,30 +182,30 @@ 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(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); + 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; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 8e5dd910..832bc00a 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 @@ -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.playerFeet())) { + state.setInput(Input.SPRINT, true); } - MovementHelper.moveTowards(state, dest); + MovementHelper.moveTowards(ctx, state, dest); return state; } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java index 07c101e6..49ca589e 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 @@ -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..dc63e84a 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,40 @@ public class MovementFall extends Movement { return state; } - BlockPos playerFeet = playerFeet(); + BlockPos playerFeet = ctx.playerFeet(); 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 (!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().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER); - targetRotation = new Rotation(player().rotationYaw, 90.0F); + targetRotation = new Rotation(ctx.player().rotationYaw, 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); + 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(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)), false)); } - if (playerFeet.equals(dest) && (player().posY - playerFeet.getY() < 0.094 || MovementHelper.isWater(dest))) { // 0.094 because lilypads + if (playerFeet.equals(dest) && (ctx.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 (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 +106,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 +116,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) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 2b255d62..7d31ff5c 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -18,18 +18,19 @@ 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.state.IBlockState; @@ -44,23 +45,23 @@ import java.util.Objects; public class MovementParkour extends Movement { - private static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN}; + private static final EnumFacing[] HORIZONTAL_AND_DOWN = { EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN }; private static final BetterBlockPos[] EMPTY = new BetterBlockPos[]{}; 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; } - public static MovementParkour cost(CalculationContext context, BetterBlockPos src, EnumFacing direction) { + public static MovementParkour cost(IBaritone baritone, BetterBlockPos src, EnumFacing direction) { MutableMoveResult res = new MutableMoveResult(); - cost(context, src.x, src.y, src.z, direction, res); + cost(new CalculationContext(baritone), 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(baritone, src, dist, direction); } public static void cost(CalculationContext context, int x, int y, int z, EnumFacing dir, MutableMoveResult res) { @@ -138,8 +139,8 @@ public class MovementParkour extends Movement { return; } for (int i = 0; i < 5; i++) { - int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); - int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getZOffset(); + int againstX = destX + HORIZONTAL_AND_DOWN[i].getXOffset(); + int againstZ = destZ + HORIZONTAL_AND_DOWN[i].getZOffset(); if (againstX == x + xDiff * 3 && againstZ == z + zDiff * 3) { // we can't turn around that fast continue; } @@ -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)) { + MovementHelper.moveTowards(ctx, state, dest); + if (ctx.playerFeet().equals(dest)) { Block d = BlockStateInterface.getBlock(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(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]); + BlockPos against1 = positionToPlace.offset(HORIZONTAL_AND_DOWN[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.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; 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..9339ad1a 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 @@ -145,38 +146,38 @@ public class MovementPillar extends Movement { IBlockState fromDown = BlockStateInterface.get(src); if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(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; 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); + state.setInput(Input.JUMP, true); } /* if (thePlayer.getPosition0().getX() != from.getX() || thePlayer.getPosition0().getZ() != from.getZ()) { @@ -184,28 +185,28 @@ 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.JUMP, ctx.player().posY < dest.getY()); + state.setInput(Input.SNEAK, ctx.player().posY > dest.getY()); // 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); 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)); @@ -214,17 +215,17 @@ public class MovementPillar extends Movement { if (!blockIsThere) { Block fr = BlockStateInterface.get(src).getBlock(); - if (!(fr instanceof BlockAir || fr.isReplaceable(world(), src))) { - state.setInput(InputOverrideHandler.Input.CLICK_LEFT, true); + 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,10 +234,10 @@ public class MovementPillar extends Movement { @Override protected boolean prepared(MovementState state) { - if (playerFeet().equals(src) || playerFeet().equals(src.down())) { + if (ctx.playerFeet().equals(src) || ctx.playerFeet().equals(src.down())) { Block block = BlockStateInterface.getBlock(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())) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index a4f32855..28251353 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -18,14 +18,15 @@ 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.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; @@ -43,8 +44,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 @@ -159,22 +160,22 @@ public class MovementTraverse extends Movement { 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(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(); boolean ladder = fd instanceof BlockLadder || fd instanceof BlockVine; @@ -190,8 +191,8 @@ public class MovementTraverse extends Movement { 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(positionsToBreak[0])), true)) + .setInput(Input.CLICK_RIGHT, true); } } @@ -204,34 +205,34 @@ public class MovementTraverse extends Movement { } 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(blocked)), true)) + .setInput(Input.CLICK_RIGHT, true); } } boolean isTheBridgeBlockThere = MovementHelper.canWalkOn(positionToPlace) || ladder; - BlockPos whereAmI = playerFeet(); + 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); + if (wasTheBridgeBlockAlwaysThere && !MovementHelper.isLiquid(ctx.playerFeet())) { + state.setInput(Input.SPRINT, true); } Block destDown = BlockStateInterface.get(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; @@ -242,43 +243,43 @@ public class MovementTraverse extends Movement { } against1 = against1.down(); if (MovementHelper.canPlaceAgainst(against1)) { - 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); } 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.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); + if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && RayTraceUtils.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 +289,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); + state.setInput(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 + 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 } @@ -322,10 +323,10 @@ public class MovementTraverse extends Movement { @Override protected boolean prepared(MovementState state) { - if (playerFeet().equals(src) || playerFeet().equals(src.down())) { + if (ctx.playerFeet().equals(src) || ctx.playerFeet().equals(src.down())) { Block block = BlockStateInterface.getBlock(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..1950ebcd 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -24,7 +24,10 @@ 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; @@ -32,7 +35,6 @@ 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 +50,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 +75,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,13 +99,13 @@ 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; } @@ -278,7 +286,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; @@ -292,14 +300,14 @@ public class PathExecutor implements IPathExecutor, Helper { if (!current.isPresent()) { return false; } - if (!player().onGround) { + if (!ctx.player().onGround) { return false; } - if (!MovementHelper.canWalkOn(playerFeet().down())) { + if (!MovementHelper.canWalkOn(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.playerFeet()) || !MovementHelper.canWalkThrough(ctx.playerFeet().up())) { // suffocating? return false; } @@ -317,7 +325,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 +334,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 +347,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,24 +357,23 @@ 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); @@ -379,7 +386,7 @@ public class PathExecutor implements IPathExecutor, Helper { 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); + ctx.player().setSprinting(false); return; } } @@ -387,8 +394,8 @@ public class PathExecutor implements IPathExecutor, Helper { 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 @@ -396,12 +403,12 @@ public class PathExecutor implements IPathExecutor, Helper { return; } if (canSprintInto(current, next)) { - if (playerFeet().equals(current.getDest())) { + if (ctx.playerFeet().equals(current.getDest())) { pathPosition++; onChangeInPathPosition(); } - if (!player().isSprinting()) { - player().setSprinting(true); + if (!ctx.player().isSprinting()) { + ctx.player().setSprinting(true); } return; } @@ -411,16 +418,16 @@ 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) { @@ -438,9 +445,9 @@ 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() { @@ -462,7 +469,7 @@ public class PathExecutor implements IPathExecutor, Helper { 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 +486,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/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..a03cde3e 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -76,17 +76,17 @@ 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)) { + if (!ctx.world().loadedEntityList.contains(entity) && !ctx.world().playerEntities.contains(entity)) { return false; } return true; } 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..73d4a99c 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -29,7 +29,6 @@ import net.minecraft.block.Block; import net.minecraft.util.math.BlockPos; import java.util.ArrayList; -import java.util.Collections; import java.util.List; public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBlockProcess { @@ -79,7 +78,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl Baritone.getExecutor().execute(() -> rescan(current)); } 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); @@ -97,6 +96,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } private void rescan(List known) { - knownLocations = MineProcess.searchWorld(Collections.singletonList(gettingTo), 64, baritone.getWorldProvider(), world(), known); + // TODO-yeet +// knownLocations = MineProcess.searchWorld(ctx, Collections.singletonList(gettingTo), 64, baritone.getWorldProvider(), 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..716ce313 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -22,6 +22,7 @@ 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; @@ -74,7 +75,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))); @@ -118,7 +119,7 @@ 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 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)); knownOreLocations = locs2; @@ -138,7 +139,7 @@ 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 @@ -160,8 +161,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro 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(mining, ORE_LOCATIONS_COUNT, baritone.getWorldProvider(), already); + locs.addAll(droppedItemsScan(mining, ctx.world())); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); cancel(); @@ -218,13 +219,13 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro /*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 List searchWorld(List mining, int max, WorldProvider provider, 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(provider.getCurrentWorld().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 1)); } else { uninteresting.add(m); } @@ -235,43 +236,44 @@ 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, 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(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(); + int searchDist = 4; // why four? idk for (int x = playerFeet.getX() - searchDist; x <= playerFeet.getX() + searchDist; x++) { for (int y = playerFeet.getY() - searchDist; y <= playerFeet.getY() + searchDist; y++) { for (int z = playerFeet.getZ() - searchDist; z <= playerFeet.getZ() + searchDist; z++) { 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 + // crucial to only add blocks we can see because otherwise this is an x-ray and it'll get caught + if (mining.contains(BlockStateInterface.getBlock(pos)) && RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()).isPresent()) { knownOreLocations.add(pos); } } } } - knownOreLocations = prune(knownOreLocations, mining, ORE_LOCATIONS_COUNT, world()); + knownOreLocations = prune(knownOreLocations, mining, ORE_LOCATIONS_COUNT); } - public static List prune(List locs2, List mining, int max, World world) { - List dropped = droppedItemsScan(mining, world); + public List prune(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(BlockStateInterface.get(pos).getBlock()) || dropped.contains(pos)) // remove any that are implausible to mine (encased in bedrock, or touching lava) - .filter(MineProcess::plausibleToBreak) + .filter(this::plausibleToBreak) - .sorted(Comparator.comparingDouble(Helper.HELPER.playerFeet()::distanceSq)) + .sorted(Comparator.comparingDouble(ctx.playerFeet()::distanceSq)) .collect(Collectors.toList()); if (locs.size() > max) { @@ -280,8 +282,8 @@ 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 boolean plausibleToBreak(BlockPos pos) { + if (MovementHelper.avoidBreaking(new CalculationContext(baritone), pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(pos))) { return false; } // bedrock above and below makes it implausible, otherwise we're good diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index 4aee4bd4..bf05e691 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -22,6 +22,7 @@ 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; @@ -40,6 +41,8 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { private static final BlockPos STARTING_POSITION = new BlockPos(0, 65, 0); private static final Goal GOAL = new GoalBlock(69, 121, 420); private static final int MAX_TICKS = 3500; + private static final Baritone baritone = Baritone.INSTANCE; + private static final IPlayerContext ctx = baritone.getPlayerContext(); /** * Called right after the {@link GameSettings} object is created in the {@link Minecraft} instance. @@ -101,15 +104,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); + baritone.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/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index 547e40c3..9f9d3d8d 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -38,7 +38,6 @@ public class BlockStateInterface implements Helper { private final World world; private final WorldData worldData; - private Chunk prev = null; private CachedRegion prevCached = null; @@ -54,7 +53,7 @@ public class BlockStateInterface implements Helper { } public static IBlockState get(BlockPos pos) { - return new CalculationContext().get(pos); // immense iq + return new CalculationContext(Baritone.INSTANCE).get(pos); // 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 } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 2f6bef6c..790b2375 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -30,7 +30,6 @@ 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; @@ -165,7 +164,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 +194,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 +204,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++) { @@ -252,7 +251,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 @@ -273,9 +272,9 @@ public class ExampleBaritoneControl extends Behavior implements Helper { if (name.length() == 0) { toFollow = RayTraceUtils.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,7 +300,7 @@ 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(); @@ -334,7 +333,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 +364,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 +420,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 +433,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 +449,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(baritone, ctx.playerFeet())).collect(Collectors.toCollection(ArrayList::new)); while (moves.contains(null)) { moves.remove(null); } diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index 31b3fc10..2429757a 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -18,14 +18,7 @@ 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; @@ -51,6 +44,7 @@ public interface Helper { Minecraft mc = Minecraft.getMinecraft(); + /* default EntityPlayerSP player() { if (!mc.isCallingFromMinecraftThread()) { throw new IllegalStateException("h00000000"); @@ -92,6 +86,7 @@ public interface Helper { 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..e4574481 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; @@ -35,7 +36,7 @@ import java.util.Map; * @author Brady * @since 7/31/2018 11:20 PM */ -public final class InputOverrideHandler extends Behavior implements Helper { +public final class InputOverrideHandler extends Behavior implements IInputOverrideHandler { public InputOverrideHandler(Baritone baritone) { super(baritone); @@ -52,6 +53,7 @@ public final class InputOverrideHandler extends Behavior implements Helper { * @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 +64,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 +75,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 +83,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 +91,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()) { @@ -105,92 +110,8 @@ public final class InputOverrideHandler extends Behavior implements Helper { return; } if (Baritone.settings().leftClickWorkaround.get()) { - boolean stillClick = BlockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.keyBinding)); + boolean stillClick = BlockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.getKeyBinding())); 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)); - } - } } diff --git a/src/main/java/baritone/utils/player/AbstractPlayerContext.java b/src/main/java/baritone/utils/player/AbstractPlayerContext.java new file mode 100644 index 00000000..88d6d6be --- /dev/null +++ b/src/main/java/baritone/utils/player/AbstractPlayerContext.java @@ -0,0 +1,40 @@ +/* + * 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.utils.BetterBlockPos; +import baritone.api.utils.IPlayerContext; +import baritone.utils.BlockStateInterface; +import net.minecraft.block.BlockSlab; + +/** + * @author Brady + * @since 11/12/2018 + */ +public abstract class AbstractPlayerContext implements IPlayerContext { + + @Override + public 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; + } +} diff --git a/src/main/java/baritone/utils/player/LocalPlayerContext.java b/src/main/java/baritone/utils/player/LocalPlayerContext.java new file mode 100644 index 00000000..ea81f0ed --- /dev/null +++ b/src/main/java/baritone/utils/player/LocalPlayerContext.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 baritone.utils.player; + +import baritone.api.utils.IPlayerContext; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.multiplayer.PlayerControllerMP; +import net.minecraft.world.World; + +/** + * Implementation of {@link IPlayerContext} that provides information about the local player. + * + * @author Brady + * @since 11/12/2018 + */ +public final class LocalPlayerContext extends AbstractPlayerContext { + + private static final Minecraft mc = Minecraft.getMinecraft(); + + public static final LocalPlayerContext INSTANCE = new LocalPlayerContext(); + + private LocalPlayerContext() {} + + @Override + public EntityPlayerSP player() { + return mc.player; + } + + @Override + public PlayerControllerMP playerController() { + return mc.playerController; + } + + @Override + public World world() { + return mc.world; + } +} From 71e7f0a04c737ef221f6f47e3471b203b4abc860 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Nov 2018 11:59:02 -0600 Subject: [PATCH 04/77] Fix GetToBlockProcess rescan --- .../baritone/process/GetToBlockProcess.java | 4 ++-- .../java/baritone/process/MineProcess.java | 23 +++++++++++-------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 73d4a99c..0a02a248 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -29,6 +29,7 @@ import net.minecraft.block.Block; import net.minecraft.util.math.BlockPos; import java.util.ArrayList; +import java.util.Collections; import java.util.List; public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBlockProcess { @@ -96,7 +97,6 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } private void rescan(List known) { - // TODO-yeet -// knownLocations = MineProcess.searchWorld(ctx, Collections.singletonList(gettingTo), 64, baritone.getWorldProvider(), known); + knownLocations = MineProcess.searchWorld(baritone, 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 716ce313..0aae73be 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -18,6 +18,7 @@ package baritone.process; import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.pathing.goals.*; import baritone.api.process.IMineProcess; import baritone.api.process.PathingCommand; @@ -119,7 +120,7 @@ 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); + List locs2 = prune(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)); knownOreLocations = locs2; @@ -161,7 +162,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (Baritone.settings().legitMine.get()) { return; } - List locs = searchWorld(mining, ORE_LOCATIONS_COUNT, baritone.getWorldProvider(), already); + List locs = searchWorld(baritone, mining, ORE_LOCATIONS_COUNT, already); locs.addAll(droppedItemsScan(mining, ctx.world())); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); @@ -219,13 +220,15 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro /*public static List searchWorld(List mining, int max, World world) { }*/ - public List searchWorld(List mining, int max, WorldProvider provider, List alreadyKnown) { + public static List searchWorld(IBaritone baritone, List mining, int max, List alreadyKnown) { + IPlayerContext ctx = baritone.getPlayerContext(); + 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, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 1)); + locs.addAll(baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 1)); } else { uninteresting.add(m); } @@ -240,7 +243,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro //System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms"); } locs.addAll(alreadyKnown); - return prune(locs, mining, max); + return prune(baritone, locs, mining, max); } public void addNearby() { @@ -258,10 +261,12 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } } - knownOreLocations = prune(knownOreLocations, mining, ORE_LOCATIONS_COUNT); + knownOreLocations = prune(baritone, knownOreLocations, mining, ORE_LOCATIONS_COUNT); } - public List prune(List locs2, List mining, int max) { + public static List prune(IBaritone baritone, List locs2, List mining, int max) { + IPlayerContext ctx = baritone.getPlayerContext(); + List dropped = droppedItemsScan(mining, ctx.world()); List locs = locs2 .stream() @@ -271,7 +276,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro .filter(pos -> ctx.world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock()) || dropped.contains(pos)) // remove any that are implausible to mine (encased in bedrock, or touching lava) - .filter(this::plausibleToBreak) + .filter(pos -> MineProcess.plausibleToBreak(baritone, pos)) .sorted(Comparator.comparingDouble(ctx.playerFeet()::distanceSq)) .collect(Collectors.toList()); @@ -282,7 +287,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return locs; } - public boolean plausibleToBreak(BlockPos pos) { + public static boolean plausibleToBreak(IBaritone baritone, BlockPos pos) { if (MovementHelper.avoidBreaking(new CalculationContext(baritone), pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(pos))) { return false; } From ef5e3ab06e5c90349bf5d8a53e25e529a4779982 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Nov 2018 13:39:11 -0600 Subject: [PATCH 05/77] pwnage --- src/main/java/baritone/utils/player/AbstractPlayerContext.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/baritone/utils/player/AbstractPlayerContext.java b/src/main/java/baritone/utils/player/AbstractPlayerContext.java index 88d6d6be..252c30a3 100644 --- a/src/main/java/baritone/utils/player/AbstractPlayerContext.java +++ b/src/main/java/baritone/utils/player/AbstractPlayerContext.java @@ -19,7 +19,6 @@ package baritone.utils.player; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.IPlayerContext; -import baritone.utils.BlockStateInterface; import net.minecraft.block.BlockSlab; /** @@ -32,7 +31,7 @@ public abstract class AbstractPlayerContext implements IPlayerContext { public 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) { + if (world().getBlockState(feet).getBlock() instanceof BlockSlab) { return feet.up(); } return feet; From 72058c792a0f7982765c59e741cbd43c78d14554 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 13 Nov 2018 12:20:27 -0800 Subject: [PATCH 06/77] fix toxic clouds in legit mine --- src/api/java/baritone/api/pathing/goals/GoalRunAway.java | 2 +- .../baritone/pathing/movement/movements/MovementFall.java | 7 ++++--- .../pathing/movement/movements/MovementPillar.java | 6 ++++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index bbbe1595..44c5fa80 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java +++ b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java @@ -75,7 +75,7 @@ public class GoalRunAway implements Goal { } min = -min; if (maintainY.isPresent()) { - min = min * 0.5 + GoalYLevel.calculate(maintainY.get(), y); + min = min * 0.6 + GoalYLevel.calculate(maintainY.get(), y) * 1.5; } return min; } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index ba57eeac..26018d3b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -64,16 +64,17 @@ public class MovementFall extends Movement { } BlockPos playerFeet = playerFeet(); + Rotation toDest = RotationUtils.calcRotationFromVec3d(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()) { return state.setStatus(MovementStatus.UNREACHABLE); } - if (player().posY - dest.getY() < playerController().getBlockReachDistance()) { + if (player().posY - dest.getY() < playerController().getBlockReachDistance() && !player().onGround) { player().inventory.currentItem = 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) { @@ -84,7 +85,7 @@ public class MovementFall extends Movement { 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)) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 846e4018..f961b043 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -192,8 +192,7 @@ public class MovementPillar extends Movement { 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 // since (lower down) we only right click once player.isSneaking, and that happens the tick after we request to sneak @@ -209,6 +208,9 @@ public class MovementPillar extends Movement { // 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 our Y coordinate is above our goal, stop jumping + state.setInput(InputOverrideHandler.Input.JUMP, player().posY < dest.getY()); } From d3db551cc94db022bfaf3035852eb18ba5a9104f Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Nov 2018 15:14:29 -0600 Subject: [PATCH 07/77] Awesome --- .../baritone/api/utils/IPlayerContext.java | 3 + .../baritone/behavior/MemoryBehavior.java | 2 +- .../baritone/behavior/PathingBehavior.java | 6 +- .../baritone/pathing/movement/Movement.java | 10 +-- .../pathing/movement/MovementHelper.java | 80 +++++++++---------- .../movement/movements/MovementAscend.java | 16 ++-- .../movement/movements/MovementDescend.java | 10 +-- .../movement/movements/MovementDiagonal.java | 10 +-- .../movement/movements/MovementDownward.java | 2 +- .../movement/movements/MovementFall.java | 8 +- .../movement/movements/MovementParkour.java | 22 ++--- .../movement/movements/MovementPillar.java | 14 ++-- .../movement/movements/MovementTraverse.java | 36 ++++----- .../baritone/pathing/path/PathExecutor.java | 14 ++-- .../baritone/process/GetToBlockProcess.java | 2 +- .../java/baritone/process/MineProcess.java | 62 +++++--------- .../baritone/utils/BlockStateInterface.java | 16 ++-- .../utils/ExampleBaritoneControl.java | 2 +- .../java/baritone/utils/PathRenderer.java | 2 +- .../utils/player/LocalPlayerContext.java | 7 ++ 20 files changed, 161 insertions(+), 163 deletions(-) diff --git a/src/api/java/baritone/api/utils/IPlayerContext.java b/src/api/java/baritone/api/utils/IPlayerContext.java index b886c063..470e1378 100644 --- a/src/api/java/baritone/api/utils/IPlayerContext.java +++ b/src/api/java/baritone/api/utils/IPlayerContext.java @@ -17,6 +17,7 @@ package baritone.api.utils; +import baritone.api.cache.IWorldData; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.multiplayer.PlayerControllerMP; import net.minecraft.util.math.Vec3d; @@ -34,6 +35,8 @@ public interface IPlayerContext { World world(); + IWorldData worldData(); + BetterBlockPos playerFeet(); default Vec3d playerFeetAsVec() { diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index f5ea8a32..2fa085ae 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -120,7 +120,7 @@ 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())); } } diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 1d2533ad..7cba8d58 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -339,7 +339,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, */ public BlockPos pathStart() { BetterBlockPos feet = ctx.playerFeet(); - if (!MovementHelper.canWalkOn(feet.down())) { + if (!MovementHelper.canWalkOn(ctx, feet.down())) { if (ctx.player().onGround) { double playerX = ctx.player().posX; double playerZ = ctx.player().posZ; @@ -358,7 +358,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // can't possibly be sneaking off of this one, we're too far away continue; } - if (MovementHelper.canWalkOn(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"); return possibleSupport; @@ -368,7 +368,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } else { // !onGround // we're in the middle of a jump - if (MovementHelper.canWalkOn(feet.down().down())) { + if (MovementHelper.canWalkOn(ctx, feet.down().down())) { logDebug("Faking path start assuming player is midair and falling"); return feet.down(); } diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index e379d27b..2a6b8800 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -115,7 +115,7 @@ public abstract class Movement implements IMovement, Helper, MovementHelper { public MovementStatus update() { ctx.player().capabilities.isFlying = false; currentState = updateState(currentState); - if (MovementHelper.isLiquid(ctx.playerFeet())) { + if (MovementHelper.isLiquid(ctx, ctx.playerFeet())) { currentState.setInput(Input.JUMP, true); } if (ctx.player().isEntityInsideOpaqueBlock()) { @@ -150,11 +150,11 @@ 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(ctx.player(), blockPos, ctx.playerController().getBlockReachDistance()); if (reachable.isPresent()) { - MovementHelper.switchToBestToolFor(ctx, 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)) { state.setInput(Input.CLICK_LEFT, true); @@ -254,7 +254,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); } } @@ -268,7 +268,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 c27de97a..a715ff9f 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -44,33 +44,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(Baritone.INSTANCE), 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; @@ -111,7 +105,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; } @@ -182,12 +176,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,12 +189,12 @@ 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; } @@ -245,7 +239,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 +261,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; } @@ -294,24 +288,28 @@ public interface MovementHelper extends ActionCosts, Helper { return block instanceof BlockStairs; } - static boolean canWalkOn(BetterBlockPos pos, IBlockState state) { - return canWalkOn(new CalculationContext(Baritone.INSTANCE), 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(Baritone.INSTANCE), 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 +323,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) { @@ -440,11 +438,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 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) { @@ -454,11 +453,12 @@ public interface MovementHelper extends ActionCosts, Helper { /** * Returns whether or not the specified pos has a liquid * + * @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/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 37897b53..5321e22e 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -72,7 +72,7 @@ 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; } @@ -88,7 +88,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; } @@ -98,7 +98,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 @@ -166,14 +166,14 @@ public class MovementAscend extends Movement { 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.canPlaceAgainst(ctx, anAgainst)) { if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block return state.setStatus(MovementStatus.UNREACHABLE); } @@ -205,7 +205,7 @@ public class MovementAscend extends Movement { return state.setStatus(MovementStatus.UNREACHABLE); } MovementHelper.moveTowards(ctx, state, dest); - if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(BlockStateInterface.get(src.down()))) { + 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 } @@ -236,7 +236,7 @@ public class MovementAscend extends Movement { 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 22e8dbee..05c140e4 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -89,7 +89,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; } @@ -118,7 +118,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++) { @@ -146,10 +146,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)) { @@ -183,7 +183,7 @@ public class MovementDescend extends Movement { } BlockPos playerFeet = ctx.playerFeet(); - if (playerFeet.equals(dest) && (MovementHelper.isLiquid(dest) || ctx.player().posY - playerFeet.getY() < 0.094)) { // lilypads + 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 { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java index 832bc00a..4a098380 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDiagonal.java @@ -62,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; @@ -145,7 +145,7 @@ public class MovementDiagonal extends Movement { state.setStatus(MovementStatus.SUCCESS); return state; } - if (!MovementHelper.isLiquid(ctx.playerFeet())) { + if (!MovementHelper.isLiquid(ctx, ctx.playerFeet())) { state.setInput(Input.SPRINT, true); } MovementHelper.moveTowards(ctx, state, dest); @@ -164,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]); } } @@ -179,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 49ca589e..f18fc538 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDownward.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDownward.java @@ -48,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); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index dc63e84a..22e048f4 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -66,7 +66,7 @@ public class MovementFall extends Movement { BlockPos playerFeet = ctx.playerFeet(); Rotation targetRotation = null; - if (!MovementHelper.isWater(dest) && src.getY() - dest.getY() > Baritone.settings().maxFallHeightNoWater.get() && !playerFeet.equals(dest)) { + 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); } @@ -87,8 +87,8 @@ public class MovementFall extends Movement { } else { state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)), false)); } - if (playerFeet.equals(dest) && (ctx.player().posY - playerFeet.getY() < 0.094 || MovementHelper.isWater(dest))) { // 0.094 because lilypads - if (MovementHelper.isWater(dest)) { + 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) { @@ -139,7 +139,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 7d31ff5c..d67e0929 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -78,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; @@ -107,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; @@ -144,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; @@ -201,7 +201,7 @@ public class MovementParkour extends Movement { } MovementHelper.moveTowards(ctx, state, dest); if (ctx.playerFeet().equals(dest)) { - Block d = BlockStateInterface.getBlock(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 @@ -213,14 +213,14 @@ public class MovementParkour extends Movement { } 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()) && !ctx.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(HORIZONTAL_AND_DOWN[i]); if (against1.up().equals(src.offset(direction, 3))) { // we can't turn around that fast continue; } - if (MovementHelper.canPlaceAgainst(against1)) { + if (MovementHelper.canPlaceAgainst(ctx, against1)) { if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block return state.setStatus(MovementStatus.UNREACHABLE); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 9339ad1a..b2f25467 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -143,8 +143,8 @@ 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(ctx.playerHead(), VecUtils.getBlockPosCenter(dest)), false)); Vec3d destCenter = VecUtils.getBlockPosCenter(dest); @@ -165,7 +165,7 @@ public class MovementPillar extends Movement { 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(baritone), src) : src.offset(fromDown.getValue(BlockLadder.FACING).getOpposite()); if (against == null) { @@ -176,7 +176,7 @@ public class MovementPillar extends Movement { if (ctx.playerFeet().equals(against.up()) || ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } - if (MovementHelper.isBottomSlab(BlockStateInterface.get(src.down()))) { + if (MovementHelper.isBottomSlab(BlockStateInterface.get(ctx, src.down()))) { state.setInput(Input.JUMP, true); } /* @@ -214,7 +214,7 @@ public class MovementPillar extends Movement { if (!blockIsThere) { - Block fr = BlockStateInterface.get(src).getBlock(); + Block fr = BlockStateInterface.get(ctx, src).getBlock(); if (!(fr instanceof BlockAir || fr.isReplaceable(ctx.world(), src))) { state.setInput(Input.CLICK_LEFT, true); blockIsThere = false; @@ -235,12 +235,12 @@ public class MovementPillar extends Movement { @Override protected boolean prepared(MovementState state) { if (ctx.playerFeet().equals(src) || ctx.playerFeet().equals(src.down())) { - Block block = BlockStateInterface.getBlock(src.down()); + Block block = BlockStateInterface.getBlock(ctx, src.down()); if (block == Blocks.LADDER || block == Blocks.VINE) { 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 28251353..ef7a9069 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -64,7 +64,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())) { @@ -122,7 +122,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; } } @@ -153,10 +153,10 @@ 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 @@ -177,17 +177,17 @@ public class MovementTraverse extends Movement { //sneak may have been set to true in the PREPPING state while mining an adjacent block 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()))) { @@ -198,9 +198,9 @@ public class MovementTraverse extends Movement { 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]; } @@ -210,7 +210,7 @@ public class MovementTraverse extends Movement { } } - boolean isTheBridgeBlockThere = MovementHelper.canWalkOn(positionToPlace) || ladder; + boolean isTheBridgeBlockThere = MovementHelper.canWalkOn(ctx, positionToPlace) || ladder; BlockPos whereAmI = ctx.playerFeet(); if (whereAmI.getY() != dest.getY() && !ladder) { logDebug("Wrong Y coordinate"); @@ -224,10 +224,10 @@ public class MovementTraverse extends Movement { if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } - if (wasTheBridgeBlockAlwaysThere && !MovementHelper.isLiquid(ctx.playerFeet())) { + if (wasTheBridgeBlockAlwaysThere && !MovementHelper.isLiquid(ctx, ctx.playerFeet())) { 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(baritone, dest.down(), dest).updateState(state); // i'm sorry return state; @@ -242,7 +242,7 @@ public class MovementTraverse extends Movement { continue; } against1 = against1.down(); - if (MovementHelper.canPlaceAgainst(against1)) { + 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); @@ -250,7 +250,7 @@ public class MovementTraverse extends Movement { if (!Baritone.settings().assumeSafeWalk.get()) { state.setInput(Input.SNEAK, true); } - Block standingOn = BlockStateInterface.get(ctx.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 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); if (dist < 0.85) { // 0.5 + 0.3 + epsilon @@ -318,13 +318,13 @@ 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 (ctx.playerFeet().equals(src) || ctx.playerFeet().equals(src.down())) { - Block block = BlockStateInterface.getBlock(src.down()); + Block block = BlockStateInterface.getBlock(ctx, src.down()); if (block == Blocks.LADDER || block == Blocks.VINE) { state.setInput(Input.SNEAK, true); } diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 1950ebcd..fadc2f21 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -110,7 +110,7 @@ public class PathExecutor implements IPathExecutor, Helper { } //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); @@ -303,11 +303,11 @@ public class PathExecutor implements IPathExecutor, Helper { if (!ctx.player().onGround) { return false; } - if (!MovementHelper.canWalkOn(ctx.playerFeet().down())) { + if (!MovementHelper.canWalkOn(ctx, ctx.playerFeet().down())) { // we're in some kind of sketchy situation, maybe parkouring return false; } - if (!MovementHelper.canWalkThrough(ctx.playerFeet()) || !MovementHelper.canWalkThrough(ctx.playerFeet().up())) { + if (!MovementHelper.canWalkThrough(ctx, ctx.playerFeet()) || !MovementHelper.canWalkThrough(ctx, ctx.playerFeet().up())) { // suffocating? return false; } @@ -384,7 +384,7 @@ public class PathExecutor implements IPathExecutor, Helper { 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)))) { + if (MovementHelper.avoidWalkingInto(BlockStateInterface.getBlock(ctx, into.up(y)))) { logDebug("Sprinting would be unsafe"); ctx.player().setSprinting(false); return; @@ -402,7 +402,7 @@ public class PathExecutor implements IPathExecutor, Helper { logDebug("Skipping descend to straight ascend"); return; } - if (canSprintInto(current, next)) { + if (canSprintInto(ctx, current, next)) { if (ctx.playerFeet().equals(current.getDest())) { pathPosition++; onChangeInPathPosition(); @@ -430,11 +430,11 @@ public class PathExecutor implements IPathExecutor, Helper { 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(); diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 0a02a248..5eefe6a9 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -97,6 +97,6 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } private void rescan(List known) { - knownLocations = MineProcess.searchWorld(baritone, Collections.singletonList(gettingTo), 64, known); + knownLocations = MineProcess.searchWorld(ctx, 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 0aae73be..60b36ea1 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -18,7 +18,6 @@ package baritone.process; import baritone.Baritone; -import baritone.api.IBaritone; import baritone.api.pathing.goals.*; import baritone.api.process.IMineProcess; import baritone.api.process.PathingCommand; @@ -27,13 +26,10 @@ 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; @@ -92,7 +88,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get(); if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain List curr = new ArrayList<>(knownOreLocations); - baritone.getExecutor().execute(() -> rescan(curr)); + Baritone.getExecutor().execute(() -> rescan(curr)); } if (Baritone.settings().legitMine.get()) { addNearby(); @@ -120,9 +116,9 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro private Goal updateGoal() { List locs = knownOreLocations; if (!locs.isEmpty()) { - List locs2 = prune(baritone, new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT); + List locs2 = prune(ctx, 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; } @@ -162,7 +158,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro if (Baritone.settings().legitMine.get()) { return; } - List locs = searchWorld(baritone, mining, ORE_LOCATIONS_COUNT, already); + List locs = searchWorld(ctx, mining, ORE_LOCATIONS_COUNT, already); locs.addAll(droppedItemsScan(mining, ctx.world())); if (locs.isEmpty()) { logDebug("No locations for " + mining + " known, cancelling"); @@ -172,26 +168,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) { @@ -220,15 +205,13 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro /*public static List searchWorld(List mining, int max, World world) { }*/ - public static List searchWorld(IBaritone baritone, List mining, int max, List alreadyKnown) { - IPlayerContext ctx = baritone.getPlayerContext(); - + public static List searchWorld(IPlayerContext 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(baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 1)); + locs.addAll(ctx.worldData().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 1)); } else { uninteresting.add(m); } @@ -243,7 +226,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro //System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms"); } locs.addAll(alreadyKnown); - return prune(baritone, locs, mining, max); + return prune(ctx, locs, mining, max); } public void addNearby() { @@ -254,29 +237,28 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro 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); - // crucial to only add blocks we can see because otherwise this is an x-ray and it'll get caught - if (mining.contains(BlockStateInterface.getBlock(pos)) && RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()).isPresent()) { + // crucial to only add blocks we can see because otherwise this + // is an x-ray and it'll get caught + if (mining.contains(BlockStateInterface.getBlock(ctx, pos)) && RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()).isPresent()) { knownOreLocations.add(pos); } } } } - knownOreLocations = prune(baritone, knownOreLocations, mining, ORE_LOCATIONS_COUNT); + knownOreLocations = prune(ctx, knownOreLocations, mining, ORE_LOCATIONS_COUNT); } - public static List prune(IBaritone baritone, List locs2, List mining, int max) { - IPlayerContext ctx = baritone.getPlayerContext(); - + public static List prune(IPlayerContext 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 -> ctx.world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.get(pos).getBlock()) || dropped.contains(pos)) + .filter(pos -> ctx.world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.getBlock(ctx, pos)) || dropped.contains(pos)) // remove any that are implausible to mine (encased in bedrock, or touching lava) - .filter(pos -> MineProcess.plausibleToBreak(baritone, pos)) + .filter(pos -> MineProcess.plausibleToBreak(ctx, pos)) .sorted(Comparator.comparingDouble(ctx.playerFeet()::distanceSq)) .collect(Collectors.toList()); @@ -287,12 +269,12 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return locs; } - public static boolean plausibleToBreak(IBaritone baritone, BlockPos pos) { - if (MovementHelper.avoidBreaking(new CalculationContext(baritone), pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(pos))) { + public static boolean plausibleToBreak(IPlayerContext ctx, BlockPos pos) { + if (MovementHelper.avoidBreaking(new BlockStateInterface(ctx), pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(ctx, 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 !(BlockStateInterface.getBlock(ctx, pos.up()) == Blocks.BEDROCK && BlockStateInterface.getBlock(ctx, pos.down()) == Blocks.BEDROCK); } @Override diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index 9f9d3d8d..e4e79867 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -18,6 +18,8 @@ package baritone.utils; import baritone.Baritone; +import baritone.api.IBaritone; +import baritone.api.utils.IPlayerContext; import baritone.cache.CachedRegion; import baritone.cache.WorldData; import baritone.pathing.movement.CalculationContext; @@ -43,22 +45,26 @@ public class BlockStateInterface implements Helper { 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; } - 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 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(BlockPos pos) { - return new CalculationContext(Baritone.INSTANCE).get(pos); // immense iq + 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(int x, int y, int z) { // Mickey resigned // Invalid vertical position if (y < 0 || y >= 256) { diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 790b2375..18e2f740 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -303,7 +303,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { 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)); } diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index bf73149e..61783bd1 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -206,7 +206,7 @@ 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(Baritone.INSTANCE.getPlayerContext(), pos); AxisAlignedBB toDraw; if (state.getBlock().equals(Blocks.AIR)) { toDraw = Blocks.DIRT.getDefaultState().getSelectedBoundingBox(Minecraft.getMinecraft().world, pos); diff --git a/src/main/java/baritone/utils/player/LocalPlayerContext.java b/src/main/java/baritone/utils/player/LocalPlayerContext.java index ea81f0ed..c95689bf 100644 --- a/src/main/java/baritone/utils/player/LocalPlayerContext.java +++ b/src/main/java/baritone/utils/player/LocalPlayerContext.java @@ -17,6 +17,8 @@ package baritone.utils.player; +import baritone.Baritone; +import baritone.api.cache.IWorldData; import baritone.api.utils.IPlayerContext; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; @@ -51,4 +53,9 @@ public final class LocalPlayerContext extends AbstractPlayerContext { public World world() { return mc.world; } + + @Override + public IWorldData worldData() { + return Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); + } } From 5e2f40a322039e0fb79fa0b37749c4c6c83aa4a8 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Nov 2018 16:33:45 -0600 Subject: [PATCH 08/77] Fix some things mentioned by @Leijurv --- .../baritone/api/utils/IPlayerContext.java | 10 ++++- .../java/baritone/behavior/LookBehavior.java | 3 +- .../baritone/behavior/MemoryBehavior.java | 3 +- src/main/java/baritone/cache/CachedChunk.java | 3 +- src/main/java/baritone/cache/ChunkPacker.java | 3 +- .../java/baritone/cache/WorldScanner.java | 3 +- .../pathing/movement/CalculationContext.java | 2 +- .../baritone/pathing/movement/Movement.java | 3 +- .../movement/movements/MovementParkour.java | 8 ++-- .../baritone/utils/BlockStateInterface.java | 2 +- .../utils/player/AbstractPlayerContext.java | 39 ------------------- .../utils/player/LocalPlayerContext.java | 2 +- 12 files changed, 22 insertions(+), 59 deletions(-) delete mode 100644 src/main/java/baritone/utils/player/AbstractPlayerContext.java diff --git a/src/api/java/baritone/api/utils/IPlayerContext.java b/src/api/java/baritone/api/utils/IPlayerContext.java index 470e1378..c7e7e24a 100644 --- a/src/api/java/baritone/api/utils/IPlayerContext.java +++ b/src/api/java/baritone/api/utils/IPlayerContext.java @@ -18,6 +18,7 @@ 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.util.math.Vec3d; @@ -37,7 +38,14 @@ public interface IPlayerContext { IWorldData worldData(); - BetterBlockPos playerFeet(); + 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); diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index de0af60d..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: diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 2fa085ae..59a3af44 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; @@ -45,7 +44,7 @@ import java.util.*; * @author Brady * @since 8/6/2018 9:47 PM */ -public final class MemoryBehavior extends Behavior implements IMemoryBehavior, Helper { +public final class MemoryBehavior extends Behavior implements IMemoryBehavior { private final Map worldDataContainers = new HashMap<>(); diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index abc741a5..406a9475 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; @@ -30,7 +29,7 @@ import java.util.*; * @author Brady * @since 8/3/2018 1:04 AM */ -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/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index d73cdb03..be7655b4 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; @@ -38,7 +37,7 @@ import java.util.*; * @author Brady * @since 8/3/2018 1:09 AM */ -public final class ChunkPacker implements Helper { +public final class ChunkPacker { private ChunkPacker() {} diff --git a/src/main/java/baritone/cache/WorldScanner.java b/src/main/java/baritone/cache/WorldScanner.java index 378bbc9c..1d220188 100644 --- a/src/main/java/baritone/cache/WorldScanner.java +++ b/src/main/java/baritone/cache/WorldScanner.java @@ -19,7 +19,6 @@ package baritone.cache; import baritone.api.cache.IWorldScanner; import baritone.api.utils.IPlayerContext; -import baritone.utils.Helper; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.multiplayer.ChunkProviderClient; @@ -31,7 +30,7 @@ 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; diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 7d0d9dab..d2398ae2 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -88,7 +88,7 @@ public class CalculationContext { } public final IBaritone getBaritone() { - return this.baritone; + return baritone; } public IBlockState get(int x, int y, int z) { diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 1d1552c3..c1b4e351 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -23,7 +23,6 @@ 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 net.minecraft.block.BlockLiquid; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -34,7 +33,7 @@ import java.util.List; import java.util.Objects; import java.util.Optional; -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}; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index d67e0929..9859f9ad 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -45,7 +45,7 @@ import java.util.Objects; public class MovementParkour extends Movement { - private static final EnumFacing[] HORIZONTAL_AND_DOWN = { EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN }; + private static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = { EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN }; private static final BetterBlockPos[] EMPTY = new BetterBlockPos[]{}; private final EnumFacing direction; @@ -139,8 +139,8 @@ public class MovementParkour extends Movement { return; } for (int i = 0; i < 5; i++) { - int againstX = destX + HORIZONTAL_AND_DOWN[i].getXOffset(); - int againstZ = destZ + HORIZONTAL_AND_DOWN[i].getZOffset(); + int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP [i].getXOffset(); + int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP [i].getZOffset(); if (againstX == x + xDiff * 3 && againstZ == z + zDiff * 3) { // we can't turn around that fast continue; } @@ -216,7 +216,7 @@ public class MovementParkour extends Movement { if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround) { BlockPos positionToPlace = dest.down(); for (int i = 0; i < 5; i++) { - BlockPos against1 = positionToPlace.offset(HORIZONTAL_AND_DOWN[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; } diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index e4e79867..4e422eda 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -35,7 +35,7 @@ import net.minecraft.world.chunk.Chunk; * * @author leijurv */ -public class BlockStateInterface implements Helper { +public class BlockStateInterface { private final World world; private final WorldData worldData; diff --git a/src/main/java/baritone/utils/player/AbstractPlayerContext.java b/src/main/java/baritone/utils/player/AbstractPlayerContext.java deleted file mode 100644 index 252c30a3..00000000 --- a/src/main/java/baritone/utils/player/AbstractPlayerContext.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package baritone.utils.player; - -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.IPlayerContext; -import net.minecraft.block.BlockSlab; - -/** - * @author Brady - * @since 11/12/2018 - */ -public abstract class AbstractPlayerContext implements IPlayerContext { - - @Override - public 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; - } -} diff --git a/src/main/java/baritone/utils/player/LocalPlayerContext.java b/src/main/java/baritone/utils/player/LocalPlayerContext.java index c95689bf..355c2497 100644 --- a/src/main/java/baritone/utils/player/LocalPlayerContext.java +++ b/src/main/java/baritone/utils/player/LocalPlayerContext.java @@ -31,7 +31,7 @@ import net.minecraft.world.World; * @author Brady * @since 11/12/2018 */ -public final class LocalPlayerContext extends AbstractPlayerContext { +public final class LocalPlayerContext implements IPlayerContext { private static final Minecraft mc = Minecraft.getMinecraft(); From 94bf8d4bbdf3c6116bdfc3fba6f6ab8f60599cef Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Nov 2018 16:53:13 -0600 Subject: [PATCH 09/77] More review things --- .../java/baritone/api/utils/input/Input.java | 8 ++++ .../movement/movements/MovementParkour.java | 2 +- src/main/java/baritone/utils/Helper.java | 44 ------------------- 3 files changed, 9 insertions(+), 45 deletions(-) diff --git a/src/api/java/baritone/api/utils/input/Input.java b/src/api/java/baritone/api/utils/input/Input.java index 4abc0544..1e8d44b5 100644 --- a/src/api/java/baritone/api/utils/input/Input.java +++ b/src/api/java/baritone/api/utils/input/Input.java @@ -89,6 +89,14 @@ public enum Input { 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); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 9859f9ad..71fba81a 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -45,7 +45,7 @@ import java.util.Objects; public class MovementParkour extends Movement { - private static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = { EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN }; + private static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = { EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN }; private static final BetterBlockPos[] EMPTY = new BetterBlockPos[]{}; private final EnumFacing direction; diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index 2429757a..196ede30 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -44,50 +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 * From d79d56c2f987bd11dd7982db3b5c37f0ae1e36ca Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Nov 2018 21:45:26 -0600 Subject: [PATCH 10/77] Expose all possible Baritone instances --- src/api/java/baritone/api/BaritoneAPI.java | 56 ++----------------- src/api/java/baritone/api/IBaritone.java | 6 -- .../java/baritone/api/IBaritoneProvider.java | 30 ++++++++++ src/main/java/baritone/Baritone.java | 24 +++----- src/main/java/baritone/BaritoneProvider.java | 23 +++++++- 5 files changed, 65 insertions(+), 74 deletions(-) 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 7646cb8f..b462c620 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -72,12 +72,6 @@ public interface IBaritone { */ IWorldProvider getWorldProvider(); - /** - * @return The {@link IWorldScanner} instance - * @see IWorldScanner - */ - IWorldScanner getWorldScanner(); - IInputOverrideHandler getInputOverrideHandler(); ICustomGoalProcess getCustomGoalProcess(); diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index 745842ce..b52e5603 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -17,13 +17,35 @@ 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()}. + * + * @see #getBaritoneForPlayer(EntityPlayerSP) + * + * @return All active {@link IBaritone} instances. + */ + 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. @@ -32,4 +54,12 @@ public interface IBaritoneProvider { * @return The {@link IBaritone} instance. */ IBaritone getBaritoneForPlayer(EntityPlayerSP 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/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index b752b63e..29cb2fb7 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -95,6 +95,7 @@ public enum Baritone implements IBaritone { private PathingControlManager pathingControlManager; + private IPlayerContext playerContext; private WorldProvider worldProvider; Baritone() { @@ -124,6 +125,7 @@ public enum Baritone implements IBaritone { getToBlockProcess = new GetToBlockProcess(this); } + this.playerContext = LocalPlayerContext.INSTANCE; this.worldProvider = new WorldProvider(); if (BaritoneAutoTest.ENABLE_AUTO_TEST) { @@ -141,11 +143,6 @@ public enum Baritone implements IBaritone { return this.gameEventHandler; } - @Override - public InputOverrideHandler getInputOverrideHandler() { - return this.inputOverrideHandler; - } - public List getBehaviors() { return this.behaviors; } @@ -155,6 +152,11 @@ public enum Baritone implements IBaritone { this.registerEventListener(behavior); } + @Override + public InputOverrideHandler getInputOverrideHandler() { + return this.inputOverrideHandler; + } + @Override public CustomGoalProcess getCustomGoalProcess() { // Iffy return customGoalProcess; @@ -167,7 +169,7 @@ public enum Baritone implements IBaritone { @Override public IPlayerContext getPlayerContext() { - return LocalPlayerContext.INSTANCE; + return playerContext; } @Override @@ -200,16 +202,6 @@ public enum Baritone implements IBaritone { return worldProvider; } - /** - * TODO-yeet This shouldn't be baritone-instance specific - * - * @return world scanner instance - */ - @Override - public WorldScanner getWorldScanner() { - return WorldScanner.INSTANCE; - } - @Override public void registerEventListener(IGameEventListener listener) { this.gameEventHandler.registerEventListener(listener); diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index a80dfe5e..aa7e08e4 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -19,15 +19,36 @@ package baritone; import baritone.api.IBaritone; import baritone.api.IBaritoneProvider; +import baritone.api.cache.IWorldScanner; +import baritone.cache.WorldScanner; import net.minecraft.client.entity.EntityPlayerSP; +import java.util.Collections; +import java.util.List; + /** * @author Brady * @since 9/29/2018 */ public final class BaritoneProvider implements IBaritoneProvider { + + @Override + public IBaritone getPrimaryBaritone() { + return Baritone.INSTANCE; + } + + @Override + public List getAllBaritones() { + return Collections.singletonList(Baritone.INSTANCE); + } + @Override public IBaritone getBaritoneForPlayer(EntityPlayerSP player) { - return Baritone.INSTANCE; // pwnage + return Baritone.INSTANCE; + } + + @Override + public IWorldScanner getWorldScanner() { + return WorldScanner.INSTANCE; } } From f9270a7ed04dc29fcdb14e3192a1b593d94bd800 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Nov 2018 21:47:40 -0600 Subject: [PATCH 11/77] my house --- src/main/java/baritone/Baritone.java | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 29cb2fb7..9f0ab9db 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -136,7 +136,7 @@ public enum Baritone implements IBaritone { } public PathingControlManager getPathingControlManager() { - return pathingControlManager; + return this.pathingControlManager; } public IGameEventListener getGameEventHandler() { @@ -159,47 +159,47 @@ public enum Baritone implements IBaritone { @Override public CustomGoalProcess getCustomGoalProcess() { // Iffy - return customGoalProcess; + return this.customGoalProcess; } @Override public GetToBlockProcess getGetToBlockProcess() { // Iffy - return getToBlockProcess; + return this.getToBlockProcess; } @Override public IPlayerContext getPlayerContext() { - return playerContext; + return this.playerContext; } @Override public FollowProcess getFollowProcess() { - return followProcess; + return this.followProcess; } @Override public LookBehavior getLookBehavior() { - return lookBehavior; + return this.lookBehavior; } @Override public MemoryBehavior getMemoryBehavior() { - return memoryBehavior; + return this.memoryBehavior; } @Override public MineProcess getMineProcess() { - return mineProcess; + return this.mineProcess; } @Override public PathingBehavior getPathingBehavior() { - return pathingBehavior; + return this.pathingBehavior; } @Override public WorldProvider getWorldProvider() { - return worldProvider; + return this.worldProvider; } @Override From 3ccb0c74c6e4d98c07be5cfface1b5013341cb99 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Nov 2018 21:53:27 -0600 Subject: [PATCH 12/77] Remove timestamps from since annotations --- src/api/java/baritone/api/cache/IBlockTypeAccess.java | 2 +- src/api/java/baritone/api/event/events/ChatEvent.java | 2 +- src/api/java/baritone/api/event/events/ChunkEvent.java | 2 +- src/api/java/baritone/api/event/events/PacketEvent.java | 2 +- src/api/java/baritone/api/event/events/RenderEvent.java | 2 +- src/api/java/baritone/api/event/events/WorldEvent.java | 2 +- src/api/java/baritone/api/event/events/type/Cancellable.java | 2 +- src/api/java/baritone/api/event/events/type/EventState.java | 2 +- .../baritone/api/event/listener/AbstractGameEventListener.java | 2 +- .../java/baritone/api/event/listener/IGameEventListener.java | 2 +- src/launch/java/baritone/launch/BaritoneTweaker.java | 2 +- src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java | 2 +- src/launch/java/baritone/launch/mixins/MixinKeyBinding.java | 2 +- src/launch/java/baritone/launch/mixins/MixinMinecraft.java | 2 +- .../java/baritone/launch/mixins/MixinNetHandlerPlayClient.java | 2 +- src/launch/java/baritone/launch/mixins/MixinNetworkManager.java | 2 +- src/launch/java/baritone/launch/mixins/MixinWorldClient.java | 2 +- src/main/java/baritone/Baritone.java | 2 +- src/main/java/baritone/behavior/Behavior.java | 2 +- src/main/java/baritone/behavior/MemoryBehavior.java | 2 +- src/main/java/baritone/cache/CachedChunk.java | 2 +- src/main/java/baritone/cache/CachedRegion.java | 2 +- src/main/java/baritone/cache/CachedWorld.java | 2 +- src/main/java/baritone/cache/ChunkPacker.java | 2 +- src/main/java/baritone/cache/WorldProvider.java | 2 +- src/main/java/baritone/event/GameEventHandler.java | 2 +- src/main/java/baritone/pathing/movement/CalculationContext.java | 2 +- src/main/java/baritone/utils/Helper.java | 2 +- src/main/java/baritone/utils/InputOverrideHandler.java | 2 +- src/main/java/baritone/utils/PathRenderer.java | 2 +- src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java | 2 +- src/main/java/baritone/utils/accessor/IChunkProviderServer.java | 2 +- src/main/java/baritone/utils/pathing/PathingBlockType.java | 2 +- 33 files changed, 33 insertions(+), 33 deletions(-) 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/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..1541b1f1 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 { 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/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/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/MixinEntityPlayerSP.java b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java index a180df5c..19e80b5e 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -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 { diff --git a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java index c776d228..03fe12df 100644 --- a/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java +++ b/src/launch/java/baritone/launch/mixins/MixinKeyBinding.java @@ -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 { diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index 3826f0d7..637cf4a9 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -42,7 +42,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 { diff --git a/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java b/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java index 498b5aff..1274f171 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java @@ -30,7 +30,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 { diff --git a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java index bf15bfc3..9576952e 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java @@ -36,7 +36,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 { diff --git a/src/launch/java/baritone/launch/mixins/MixinWorldClient.java b/src/launch/java/baritone/launch/mixins/MixinWorldClient.java index 322239b7..f9b4fd08 100644 --- a/src/launch/java/baritone/launch/mixins/MixinWorldClient.java +++ b/src/launch/java/baritone/launch/mixins/MixinWorldClient.java @@ -28,7 +28,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 { diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 9f0ab9db..4f24f6d0 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -52,7 +52,7 @@ import java.util.concurrent.TimeUnit; /** * @author Brady - * @since 7/31/2018 10:50 PM + * @since 7/31/2018 */ public enum Baritone implements IBaritone { diff --git a/src/main/java/baritone/behavior/Behavior.java b/src/main/java/baritone/behavior/Behavior.java index f1fe0d9f..36273c02 100644 --- a/src/main/java/baritone/behavior/Behavior.java +++ b/src/main/java/baritone/behavior/Behavior.java @@ -25,7 +25,7 @@ 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 { diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 59a3af44..84507367 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -42,7 +42,7 @@ import java.util.*; /** * @author Brady - * @since 8/6/2018 9:47 PM + * @since 8/6/2018 */ public final class MemoryBehavior extends Behavior implements IMemoryBehavior { diff --git a/src/main/java/baritone/cache/CachedChunk.java b/src/main/java/baritone/cache/CachedChunk.java index 406a9475..1e55cb64 100644 --- a/src/main/java/baritone/cache/CachedChunk.java +++ b/src/main/java/baritone/cache/CachedChunk.java @@ -27,7 +27,7 @@ import java.util.*; /** * @author Brady - * @since 8/3/2018 1:04 AM + * @since 8/3/2018 */ public final class CachedChunk { 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 9c73df70..a4884963 100644 --- a/src/main/java/baritone/cache/CachedWorld.java +++ b/src/main/java/baritone/cache/CachedWorld.java @@ -35,7 +35,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 { diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index be7655b4..44153fdc 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -35,7 +35,7 @@ import java.util.*; /** * @author Brady - * @since 8/3/2018 1:09 AM + * @since 8/3/2018 */ public final class ChunkPacker { diff --git a/src/main/java/baritone/cache/WorldProvider.java b/src/main/java/baritone/cache/WorldProvider.java index 1bd27a98..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 { diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 084b5562..431a1d24 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -30,7 +30,7 @@ import java.util.List; /** * @author Brady - * @since 7/31/2018 11:04 PM + * @since 7/31/2018 */ public final class GameEventHandler implements IGameEventListener, Helper { diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index d2398ae2..cb4727cc 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -36,7 +36,7 @@ import net.minecraft.world.World; /** * @author Brady - * @since 8/7/2018 4:30 PM + * @since 8/7/2018 */ public class CalculationContext { diff --git a/src/main/java/baritone/utils/Helper.java b/src/main/java/baritone/utils/Helper.java index 196ede30..0687d560 100755 --- a/src/main/java/baritone/utils/Helper.java +++ b/src/main/java/baritone/utils/Helper.java @@ -25,7 +25,7 @@ import net.minecraft.util.text.TextFormatting; /** * @author Brady - * @since 8/1/2018 12:18 AM + * @since 8/1/2018 */ public interface Helper { diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 2a125b54..228a3e86 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -34,7 +34,7 @@ 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 IInputOverrideHandler { diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 61783bd1..c1d228a4 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -51,7 +51,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 { diff --git a/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java index 73936deb..50582b8f 100644 --- a/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java +++ b/src/main/java/baritone/utils/accessor/IAnvilChunkLoader.java @@ -24,7 +24,7 @@ import java.io.File; /** * @author Brady * @see WorldProvider - * @since 8/4/2018 11:36 AM + * @since 8/4/2018 */ public interface IAnvilChunkLoader { diff --git a/src/main/java/baritone/utils/accessor/IChunkProviderServer.java b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java index b5512a1a..e3e412b5 100644 --- a/src/main/java/baritone/utils/accessor/IChunkProviderServer.java +++ b/src/main/java/baritone/utils/accessor/IChunkProviderServer.java @@ -23,7 +23,7 @@ import net.minecraft.world.chunk.storage.IChunkLoader; /** * @author Brady * @see WorldProvider - * @since 8/4/2018 11:33 AM + * @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 { From a0dd43244c3b4aa02c4dc399cf61fc7e28e80426 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 13 Nov 2018 19:54:19 -0800 Subject: [PATCH 13/77] immense iq --- src/api/java/baritone/api/IBaritoneProvider.java | 7 +++---- src/main/java/baritone/BaritoneProvider.java | 6 +++--- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index b52e5603..673a9857 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -20,7 +20,7 @@ package baritone.api; import baritone.api.cache.IWorldScanner; import net.minecraft.client.entity.EntityPlayerSP; -import java.util.List; +import java.util.Set; /** * @author Leijurv @@ -40,11 +40,10 @@ public interface IBaritoneProvider { * Returns all of the active {@link IBaritone} instances. This includes the local one * returned by {@link #getPrimaryBaritone()}. * - * @see #getBaritoneForPlayer(EntityPlayerSP) - * * @return All active {@link IBaritone} instances. + * @see #getBaritoneForPlayer(EntityPlayerSP) */ - List getAllBaritones(); + Set getAllBaritones(); /** * Provides the {@link IBaritone} instance for a given {@link EntityPlayerSP}. This will likely be diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index aa7e08e4..af1d0331 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -24,7 +24,7 @@ import baritone.cache.WorldScanner; import net.minecraft.client.entity.EntityPlayerSP; import java.util.Collections; -import java.util.List; +import java.util.Set; /** * @author Brady @@ -38,8 +38,8 @@ public final class BaritoneProvider implements IBaritoneProvider { } @Override - public List getAllBaritones() { - return Collections.singletonList(Baritone.INSTANCE); + public Set getAllBaritones() { + return Collections.singleton(Baritone.INSTANCE); } @Override From 0302c6f14b6b0abef95c281d69e7423c7345419b Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 13 Nov 2018 21:56:57 -0600 Subject: [PATCH 14/77] Fix really really bad error mega critical --- src/main/java/baritone/Baritone.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 4f24f6d0..ebedf46f 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -107,6 +107,9 @@ 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 = LocalPlayerContext.INSTANCE; + this.behaviors = new ArrayList<>(); { // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist @@ -125,7 +128,6 @@ public enum Baritone implements IBaritone { getToBlockProcess = new GetToBlockProcess(this); } - this.playerContext = LocalPlayerContext.INSTANCE; this.worldProvider = new WorldProvider(); if (BaritoneAutoTest.ENABLE_AUTO_TEST) { From 2675852dbe0171c80c3b729bb9061c5e0a640f90 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 13 Nov 2018 20:11:51 -0800 Subject: [PATCH 15/77] canc --- src/main/java/baritone/utils/BaritoneAutoTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index bf05e691..59ce91e5 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -42,7 +42,6 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { private static final Goal GOAL = new GoalBlock(69, 121, 420); private static final int MAX_TICKS = 3500; private static final Baritone baritone = Baritone.INSTANCE; - private static final IPlayerContext ctx = baritone.getPlayerContext(); /** * Called right after the {@link GameSettings} object is created in the {@link Minecraft} instance. @@ -72,7 +71,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { @Override public void onTick(TickEvent event) { - + IPlayerContext ctx = baritone.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"); From f6891feb64307511fe58de1e4b98d093b081f2f3 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 13 Nov 2018 21:26:27 -0800 Subject: [PATCH 16/77] removed all references to Baritone.INSTANCE --- .../baritone/launch/mixins/MixinEntity.java | 3 +- .../launch/mixins/MixinEntityLivingBase.java | 3 +- .../launch/mixins/MixinEntityPlayerSP.java | 11 ++-- .../launch/mixins/MixinEntityRenderer.java | 6 ++- .../launch/mixins/MixinKeyBinding.java | 5 +- .../launch/mixins/MixinMinecraft.java | 39 +++++++++----- .../mixins/MixinNetHandlerPlayClient.java | 48 +++++++++++------ .../launch/mixins/MixinNetworkManager.java | 40 +++++++++++--- .../launch/mixins/MixinWorldClient.java | 43 +++++++++------ src/main/java/baritone/cache/CachedWorld.java | 12 +++-- .../java/baritone/event/GameEventHandler.java | 11 ++-- .../java/baritone/utils/BaritoneAutoTest.java | 7 ++- .../java/baritone/utils/PathRenderer.java | 53 ++++++++++++------- .../utils/player/LocalPlayerContext.java | 4 +- 14 files changed, 188 insertions(+), 97 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinEntity.java b/src/launch/java/baritone/launch/mixins/MixinEntity.java index 8ca1743f..93b9d901 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntity.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntity.java @@ -18,6 +18,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 +54,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); + ((Baritone) 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..f640f349 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -18,6 +18,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 +57,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); + ((Baritone) 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 19e80b5e..5b908d8b 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -18,10 +18,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; @@ -44,7 +45,7 @@ public class MixinEntityPlayerSP { ) private void sendChatMessage(String msg, CallbackInfo ci) { ChatEvent event = new ChatEvent((EntityPlayerSP) (Object) this, msg); - Baritone.INSTANCE.getGameEventHandler().onSendChatMessage(event); + ((Baritone) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this)).getGameEventHandler().onSendChatMessage(event); if (event.isCancelled()) { ci.cancel(); } @@ -60,7 +61,7 @@ public class MixinEntityPlayerSP { ) ) private void onPreUpdate(CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.PRE)); + ((Baritone) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this)).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.PRE)); } @Inject( @@ -73,7 +74,7 @@ public class MixinEntityPlayerSP { ) ) private void onPostUpdate(CallbackInfo ci) { - Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST)); + ((Baritone) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this)).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST)); } @Redirect( @@ -84,7 +85,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..63c3c223 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.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.RenderEvent; import net.minecraft.client.renderer.EntityRenderer; import org.spongepowered.asm.mixin.Mixin; @@ -37,6 +39,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()) { + ((Baritone) 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 03fe12df..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; @@ -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 637cf4a9..50ba4178 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; @@ -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()) { + ((Baritone) ibaritone).getGameEventHandler().onTick(new TickEvent( + EventState.PRE, + (player != null && world != null) + ? TickEvent.Type.IN + : TickEvent.Type.OUT + )); + } + } @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 + ((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 + + ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getGameEventHandler().onWorldEvent( new WorldEvent( world, EventState.PRE @@ -124,7 +132,9 @@ 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 + + ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getGameEventHandler().onWorldEvent( new WorldEvent( world, EventState.POST @@ -141,7 +151,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 +164,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 + ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getGameEventHandler().onBlockInteract(new BlockInteractEvent(pos, BlockInteractEvent.Type.BREAK)); } @Inject( @@ -165,6 +177,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 + ((Baritone) 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 1274f171..fa5345d2 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.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.ChunkEvent; import baritone.api.event.events.type.EventState; import net.minecraft.client.network.NetHandlerPlayClient; @@ -43,14 +45,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) { + ((Baritone) ibaritone).getGameEventHandler().onChunkEvent( + new ChunkEvent( + EventState.PRE, + ChunkEvent.Type.POPULATE, + packetIn.getChunkX(), + packetIn.getChunkZ() + ) + ); + } + } } @Inject( @@ -58,14 +64,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) { + ((Baritone) ibaritone).getGameEventHandler().onChunkEvent( + new ChunkEvent( + EventState.POST, + ChunkEvent.Type.POPULATE, + packetIn.getChunkX(), + packetIn.getChunkZ() + ) + ); + } + } } @Inject( @@ -76,6 +86,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) { + ((Baritone) ibaritone).getGameEventHandler().onPlayerDeath(); + } + } } } diff --git a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java index 9576952e..4d20bb7b 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.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.PacketEvent; import baritone.api.event.events.type.EventState; import io.netty.channel.Channel; @@ -53,8 +55,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) { + ((Baritone) ibaritone).getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, inPacket)); + } } } @@ -63,8 +71,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) { + ((Baritone) ibaritone).getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, inPacket)); + } } } @@ -76,8 +90,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) { + ((Baritone) ibaritone).getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, packet)); + } } } @@ -86,8 +105,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) { + ((Baritone) 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 f9b4fd08..d76e6057 100644 --- a/src/launch/java/baritone/launch/mixins/MixinWorldClient.java +++ b/src/launch/java/baritone/launch/mixins/MixinWorldClient.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.ChunkEvent; import baritone.api.event.events.type.EventState; import net.minecraft.client.multiplayer.WorldClient; @@ -38,14 +40,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) { + ((Baritone) ibaritone).getGameEventHandler().onChunkEvent( + new ChunkEvent( + EventState.PRE, + loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD, + chunkX, + chunkZ + ) + ); + } + } + } @Inject( @@ -53,13 +60,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) { + ((Baritone) ibaritone).getGameEventHandler().onChunkEvent( + new ChunkEvent( + EventState.POST, + loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD, + chunkX, + chunkZ + ) + ); + } + } } } diff --git a/src/main/java/baritone/cache/CachedWorld.java b/src/main/java/baritone/cache/CachedWorld.java index a4884963..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; @@ -190,10 +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) { - // TODO-yeet fix - return Baritone.INSTANCE.getPlayerContext().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/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 431a1d24..d2739b38 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -23,6 +23,7 @@ import baritone.api.event.events.type.EventState; 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; @@ -70,17 +71,19 @@ public final class GameEventHandler implements IGameEventListener, Helper { boolean isPostPopulate = state == EventState.POST && type == ChunkEvent.Type.POPULATE; + 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); }); } diff --git a/src/main/java/baritone/utils/BaritoneAutoTest.java b/src/main/java/baritone/utils/BaritoneAutoTest.java index 59ce91e5..d86a36c4 100644 --- a/src/main/java/baritone/utils/BaritoneAutoTest.java +++ b/src/main/java/baritone/utils/BaritoneAutoTest.java @@ -17,7 +17,7 @@ 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; @@ -41,7 +41,6 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { private static final BlockPos STARTING_POSITION = new BlockPos(0, 65, 0); private static final Goal GOAL = new GoalBlock(69, 121, 420); private static final int MAX_TICKS = 3500; - private static final Baritone baritone = Baritone.INSTANCE; /** * Called right after the {@link GameSettings} object is created in the {@link Minecraft} instance. @@ -71,7 +70,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { @Override public void onTick(TickEvent event) { - IPlayerContext ctx = baritone.getPlayerContext(); + 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"); @@ -107,7 +106,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper { } // Setup Baritone's pathing goal and (if needed) begin pathing - baritone.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(ctx.playerFeet())) { diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index c1d228a4..da19e955 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; @@ -31,12 +32,11 @@ 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; @@ -65,9 +65,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 +96,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 -> { 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 +131,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 +190,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 +202,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,7 +221,7 @@ 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(Baritone.INSTANCE.getPlayerContext(), 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); @@ -249,7 +264,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/player/LocalPlayerContext.java b/src/main/java/baritone/utils/player/LocalPlayerContext.java index 355c2497..a818c2d9 100644 --- a/src/main/java/baritone/utils/player/LocalPlayerContext.java +++ b/src/main/java/baritone/utils/player/LocalPlayerContext.java @@ -17,7 +17,7 @@ package baritone.utils.player; -import baritone.Baritone; +import baritone.api.BaritoneAPI; import baritone.api.cache.IWorldData; import baritone.api.utils.IPlayerContext; import net.minecraft.client.Minecraft; @@ -56,6 +56,6 @@ public final class LocalPlayerContext implements IPlayerContext { @Override public IWorldData worldData() { - return Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); + return BaritoneAPI.getProvider().getPrimaryBaritone().getWorldProvider().getCurrentWorld(); } } From c74ccaafbf61dbeac007db4e9e7b62670133691d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 13 Nov 2018 21:34:11 -0800 Subject: [PATCH 17/77] remove Baritone.INSTANCE --- src/main/java/baritone/Baritone.java | 8 +------- src/main/java/baritone/BaritoneProvider.java | 9 ++++++--- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index ebedf46f..c5c1b3ed 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -27,7 +27,6 @@ import baritone.behavior.LookBehavior; import baritone.behavior.MemoryBehavior; import baritone.behavior.PathingBehavior; import baritone.cache.WorldProvider; -import baritone.cache.WorldScanner; import baritone.event.GameEventHandler; import baritone.process.CustomGoalProcess; import baritone.process.FollowProcess; @@ -54,12 +53,7 @@ import java.util.concurrent.TimeUnit; * @author Brady * @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; diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index af1d0331..93f8faed 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -32,19 +32,22 @@ import java.util.Set; */ public final class BaritoneProvider implements IBaritoneProvider { + private final Baritone primary = new Baritone(); + @Override public IBaritone getPrimaryBaritone() { - return Baritone.INSTANCE; + return primary; } @Override public Set getAllBaritones() { - return Collections.singleton(Baritone.INSTANCE); + return Collections.singleton(primary); } @Override public IBaritone getBaritoneForPlayer(EntityPlayerSP player) { - return Baritone.INSTANCE; + // TODO implement on bot-system branch + return primary; } @Override From 57b60c734bdb695f4315b2902bf2b84408115842 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 13 Nov 2018 22:15:01 -0800 Subject: [PATCH 18/77] fixes to BlockBreakHelper --- .../java/baritone/utils/BlockBreakHelper.java | 56 +++++++++++++------ .../baritone/utils/InputOverrideHandler.java | 9 +-- 2 files changed, 45 insertions(+), 20 deletions(-) diff --git a/src/main/java/baritone/utils/BlockBreakHelper.java b/src/main/java/baritone/utils/BlockBreakHelper.java index b1e9ae53..e384cf9c 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 = mc.objectMouseOver; // TODO per-player 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/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 228a3e86..3670a044 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -43,8 +43,11 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri */ private final Map inputForceStateMap = new HashMap<>(); + private final BlockBreakHelper blockBreakHelper; + public InputOverrideHandler(Baritone baritone) { super(baritone); + this.blockBreakHelper = new BlockBreakHelper(baritone.getPlayerContext()); } /** @@ -109,9 +112,7 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri if (event.getType() == TickEvent.Type.OUT) { return; } - if (Baritone.settings().leftClickWorkaround.get()) { - boolean stillClick = BlockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.getKeyBinding())); - setInputForceState(Input.CLICK_LEFT, stillClick); - } + boolean stillClick = blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.getKeyBinding())); + setInputForceState(Input.CLICK_LEFT, stillClick); } } From e93fd596ff64c6f9be3f64c09fc6e4d028af6fc1 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 13 Nov 2018 22:17:18 -0800 Subject: [PATCH 19/77] customized TickEvent Type based on player context status --- .../java/baritone/launch/mixins/MixinMinecraft.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index 50ba4178..303a53b1 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -86,12 +86,12 @@ public class MixinMinecraft { ) private void runTick(CallbackInfo ci) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { - ((Baritone) ibaritone).getGameEventHandler().onTick(new TickEvent( - EventState.PRE, - (player != null && world != null) - ? TickEvent.Type.IN - : TickEvent.Type.OUT - )); + + TickEvent.Type type = ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().world() != null + ? TickEvent.Type.IN + : TickEvent.Type.OUT; + + ((Baritone) ibaritone).getGameEventHandler().onTick(new TickEvent(EventState.PRE, type)); } } From b53f3925a402e9ff26d867932a6fd891dc1c7c43 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 13 Nov 2018 22:28:12 -0800 Subject: [PATCH 20/77] forgot to add these files lol --- src/main/java/baritone/behavior/PathingBehavior.java | 5 ++--- src/main/java/baritone/pathing/path/PathExecutor.java | 2 +- src/main/java/baritone/utils/InputOverrideHandler.java | 4 ++++ 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 7cba8d58..7be1d405 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -36,7 +36,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; @@ -101,7 +100,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) { @@ -296,7 +295,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, next = null; baritone.getInputOverrideHandler().clearAllKeys(); AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(AbstractNodeCostSearch::cancel); - BlockBreakHelper.stopBreakingBlock(); + baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); } public void forceCancel() { // NOT exposed on public api diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index fadc2f21..270bb0ca 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -452,7 +452,7 @@ public class PathExecutor implements IPathExecutor, Helper { private void cancel() { clearKeys(); - BlockBreakHelper.stopBreakingBlock(); + behavior.baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); pathPosition = path.length() + 3; failed = true; } diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 3670a044..191d145a 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -115,4 +115,8 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri boolean stillClick = blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.getKeyBinding())); setInputForceState(Input.CLICK_LEFT, stillClick); } + + public BlockBreakHelper getBlockBreakHelper() { + return blockBreakHelper; + } } From ce6ec00a89d02f66af65564c7c37c68f50f0055c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 13:24:44 -0800 Subject: [PATCH 21/77] get rid of the remaining references to mc.world --- src/api/java/baritone/api/utils/RayTraceUtils.java | 2 +- src/api/java/baritone/api/utils/RotationUtils.java | 2 +- src/api/java/baritone/api/utils/VecUtils.java | 14 +++++--------- .../baritone/pathing/movement/MovementHelper.java | 11 ++++++----- .../pathing/movement/movements/MovementAscend.java | 2 +- .../movement/movements/MovementParkour.java | 10 +++++----- .../movement/movements/MovementTraverse.java | 8 ++++---- .../java/baritone/utils/BlockStateInterface.java | 6 ++++-- 8 files changed, 27 insertions(+), 28 deletions(-) diff --git a/src/api/java/baritone/api/utils/RayTraceUtils.java b/src/api/java/baritone/api/utils/RayTraceUtils.java index 8b37ef9d..13f1081b 100644 --- a/src/api/java/baritone/api/utils/RayTraceUtils.java +++ b/src/api/java/baritone/api/utils/RayTraceUtils.java @@ -51,7 +51,7 @@ public final class RayTraceUtils { direction.y * blockReachDistance, direction.z * blockReachDistance ); - return mc.world.rayTraceBlocks(start, end, false, false, true); + 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..b527287e 100644 --- a/src/api/java/baritone/api/utils/RotationUtils.java +++ b/src/api/java/baritone/api/utils/RotationUtils.java @@ -203,6 +203,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/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index a715ff9f..15d79040 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -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; /** @@ -85,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.getWorld().getChunk(x >> 4, z >> 4) instanceof EmptyChunk) { return true; } if (snow) { @@ -150,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 @@ -164,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; @@ -439,7 +440,7 @@ public interface MovementHelper extends ActionCosts, Helper { * water, regardless of whether or not it is flowing. * * @param ctx The player context - * @param bp The block pos + * @param bp The block pos * @return Whether or not the block is water */ static boolean isWater(IPlayerContext ctx, BlockPos bp) { @@ -454,7 +455,7 @@ public interface MovementHelper extends ActionCosts, Helper { * Returns whether or not the specified pos has a liquid * * @param ctx The player context - * @param p The pos + * @param p The pos * @return Whether or not the block is a liquid */ static boolean isLiquid(IPlayerContext ctx, BlockPos p) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 5321e22e..3d737580 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -76,7 +76,7 @@ public class MovementAscend extends Movement { 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 diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 71fba81a..ede456b6 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -45,7 +45,7 @@ import java.util.Objects; public class MovementParkour extends Movement { - private static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = { EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN }; + private static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN}; private static final BetterBlockPos[] EMPTY = new BetterBlockPos[]{}; private final EnumFacing direction; @@ -135,12 +135,12 @@ 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++) { - int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP [i].getXOffset(); - int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP [i].getZOffset(); + int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); + int againstZ = destZ + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getZOffset(); if (againstX == x + xDiff * 3 && againstZ == z + zDiff * 3) { // we can't turn around that fast continue; } @@ -216,7 +216,7 @@ public class MovementParkour extends Movement { 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]); + 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; } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index ef7a9069..d80043af 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -101,7 +101,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; @@ -167,7 +167,7 @@ public class MovementTraverse extends Movement { // combine the yaw to the center of the destination, and the pitch to the specific block we're trying to break // it's safe to do this since the two blocks we break (in a traverse) are right on top of each other and so will have the same yaw - float yawToDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(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)); @@ -191,7 +191,7 @@ public class MovementTraverse extends Movement { isDoorActuallyBlockingUs = true; } if (isDoorActuallyBlockingUs && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { - return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(positionsToBreak[0])), true)) + return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), positionsToBreak[0])), true)) .setInput(Input.CLICK_RIGHT, true); } } @@ -205,7 +205,7 @@ public class MovementTraverse extends Movement { } if (blocked != null) { - return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(blocked)), true)) + return state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), blocked)), true)) .setInput(Input.CLICK_RIGHT, true); } } diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index 4e422eda..63ba8d83 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -18,11 +18,9 @@ package baritone.utils; import baritone.Baritone; -import baritone.api.IBaritone; import baritone.api.utils.IPlayerContext; import baritone.cache.CachedRegion; import baritone.cache.WorldData; -import baritone.pathing.movement.CalculationContext; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -54,6 +52,10 @@ public class BlockStateInterface { this.world = world; } + public World getWorld() { + return world; + } + 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(); } From 933b295c4062f6deba8d51ea3a35258674e8b50d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 13:46:16 -0800 Subject: [PATCH 22/77] context objectMouseOver --- .../baritone/api/utils/IPlayerContext.java | 31 +++++++++++++++++++ .../baritone/api/utils/RayTraceUtils.java | 30 ------------------ .../baritone/api/utils/RotationUtils.java | 8 +++-- .../baritone/pathing/movement/Movement.java | 2 +- .../movement/movements/MovementAscend.java | 6 ++-- .../movement/movements/MovementParkour.java | 5 ++- .../movement/movements/MovementTraverse.java | 12 ++++--- .../utils/ExampleBaritoneControl.java | 3 +- .../java/baritone/utils/PathRenderer.java | 5 ++- .../utils/player/LocalPlayerContext.java | 6 ++++ 10 files changed, 58 insertions(+), 50 deletions(-) diff --git a/src/api/java/baritone/api/utils/IPlayerContext.java b/src/api/java/baritone/api/utils/IPlayerContext.java index c7e7e24a..cd80a7d9 100644 --- a/src/api/java/baritone/api/utils/IPlayerContext.java +++ b/src/api/java/baritone/api/utils/IPlayerContext.java @@ -21,9 +21,14 @@ 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 @@ -38,6 +43,8 @@ public interface IPlayerContext { 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); @@ -58,4 +65,28 @@ public interface IPlayerContext { 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/RayTraceUtils.java b/src/api/java/baritone/api/utils/RayTraceUtils.java index 13f1081b..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() {} /** @@ -53,28 +47,4 @@ public final class RayTraceUtils { ); return entity.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(); - } } diff --git a/src/api/java/baritone/api/utils/RotationUtils.java b/src/api/java/baritone/api/utils/RotationUtils.java index b527287e..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 diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index c1b4e351..a3e841c6 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -153,7 +153,7 @@ public abstract class Movement implements IMovement, MovementHelper { if (reachable.isPresent()) { 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; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 3d737580..9c33742e 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -21,7 +21,6 @@ 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; @@ -31,7 +30,6 @@ import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; 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; @@ -181,9 +179,9 @@ public class MovementAscend extends Movement { 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(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true)); - EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; + 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(Input.SNEAK, true); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index ede456b6..44334569 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -34,7 +34,6 @@ import baritone.utils.Helper; import baritone.utils.pathing.MutableMoveResult; 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.EnumFacing; import net.minecraft.util.math.BlockPos; @@ -232,8 +231,8 @@ public class MovementParkour extends Movement { 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(Input.CLICK_RIGHT, true); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index d80043af..2dc0e0cf 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -20,7 +20,10 @@ 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; @@ -29,7 +32,6 @@ import baritone.pathing.movement.MovementState; import baritone.utils.BlockStateInterface; 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; @@ -265,8 +267,8 @@ public class MovementTraverse extends Movement { double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; 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) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) { + 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()); @@ -300,7 +302,7 @@ public class MovementTraverse extends Movement { state.setTarget(new MovementState.MovementTarget(backToFace, true)); } state.setInput(Input.SNEAK, true); - if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), goalLook)) { + 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()); diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 18e2f740..9808de6d 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -23,7 +23,6 @@ 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; @@ -270,7 +269,7 @@ 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 : ctx.world().playerEntities) { String theirName = pl.getName().trim().toLowerCase(); diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index da19e955..443cd035 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -31,7 +31,6 @@ 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.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; @@ -224,9 +223,9 @@ public final class PathRenderer implements Helper { 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); diff --git a/src/main/java/baritone/utils/player/LocalPlayerContext.java b/src/main/java/baritone/utils/player/LocalPlayerContext.java index a818c2d9..02c08c11 100644 --- a/src/main/java/baritone/utils/player/LocalPlayerContext.java +++ b/src/main/java/baritone/utils/player/LocalPlayerContext.java @@ -23,6 +23,7 @@ import baritone.api.utils.IPlayerContext; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.multiplayer.PlayerControllerMP; +import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; /** @@ -58,4 +59,9 @@ public final class LocalPlayerContext implements IPlayerContext { public IWorldData worldData() { return BaritoneAPI.getProvider().getPrimaryBaritone().getWorldProvider().getCurrentWorld(); } + + @Override + public RayTraceResult objectMouseOver() { + return mc.objectMouseOver; + } } From 5a52cea41559b168ebeb8f69e66416f57b46eb61 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 13:48:09 -0800 Subject: [PATCH 23/77] epic --- src/main/java/baritone/utils/BlockBreakHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/BlockBreakHelper.java b/src/main/java/baritone/utils/BlockBreakHelper.java index e384cf9c..d4d03f67 100644 --- a/src/main/java/baritone/utils/BlockBreakHelper.java +++ b/src/main/java/baritone/utils/BlockBreakHelper.java @@ -81,7 +81,7 @@ public final class BlockBreakHelper implements Helper { return isLeftClick; } - RayTraceResult trace = mc.objectMouseOver; // TODO per-player objectMouseOver + RayTraceResult trace = playerContext.objectMouseOver(); boolean isBlockTrace = trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK; if (isLeftClick && isBlockTrace) { From e4045e134330eb9e3e9e1e2e65507f45962685e9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 13:48:45 -0800 Subject: [PATCH 24/77] and another --- .../java/baritone/pathing/movement/movements/MovementFall.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementFall.java b/src/main/java/baritone/pathing/movement/movements/MovementFall.java index 11b3dfd7..ef89919b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementFall.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementFall.java @@ -77,7 +77,7 @@ public class MovementFall extends Movement { targetRotation = new Rotation(toDest.getYaw(), 90.0F); - RayTraceResult trace = mc.objectMouseOver; + RayTraceResult trace = ctx.objectMouseOver(); if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK && ctx.player().rotationPitch > 89.0F) { state.setInput(Input.CLICK_RIGHT, true); } From c3a367078504ca6c4f3f0a1783051c6d273ef75f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 13:57:37 -0800 Subject: [PATCH 25/77] unused imports --- src/api/java/baritone/api/IBaritone.java | 1 - src/api/java/baritone/api/pathing/movement/IMovement.java | 1 - src/main/java/baritone/pathing/path/PathExecutor.java | 1 - 3 files changed, 3 deletions(-) diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index b462c620..451e7990 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -21,7 +21,6 @@ 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; diff --git a/src/api/java/baritone/api/pathing/movement/IMovement.java b/src/api/java/baritone/api/pathing/movement/IMovement.java index 5c3eac14..7b3eca5f 100644 --- a/src/api/java/baritone/api/pathing/movement/IMovement.java +++ b/src/api/java/baritone/api/pathing/movement/IMovement.java @@ -18,7 +18,6 @@ package baritone.api.pathing.movement; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.IPlayerContext; import net.minecraft.util.math.BlockPos; import java.util.List; diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 270bb0ca..dca2a0e9 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -32,7 +32,6 @@ 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 net.minecraft.init.Blocks; From ea81cd76caef3ae3bd279cddfd0c681808768982 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 14:00:56 -0800 Subject: [PATCH 26/77] sigh --- src/api/java/baritone/api/IBaritoneProvider.java | 13 ++++++++++--- src/main/java/baritone/BaritoneProvider.java | 14 ++++---------- src/main/java/baritone/event/GameEventHandler.java | 4 ++-- 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/api/java/baritone/api/IBaritoneProvider.java b/src/api/java/baritone/api/IBaritoneProvider.java index 673a9857..d17e8e00 100644 --- a/src/api/java/baritone/api/IBaritoneProvider.java +++ b/src/api/java/baritone/api/IBaritoneProvider.java @@ -20,7 +20,7 @@ package baritone.api; import baritone.api.cache.IWorldScanner; import net.minecraft.client.entity.EntityPlayerSP; -import java.util.Set; +import java.util.List; /** * @author Leijurv @@ -43,7 +43,7 @@ public interface IBaritoneProvider { * @return All active {@link IBaritone} instances. * @see #getBaritoneForPlayer(EntityPlayerSP) */ - Set getAllBaritones(); + List getAllBaritones(); /** * Provides the {@link IBaritone} instance for a given {@link EntityPlayerSP}. This will likely be @@ -52,7 +52,14 @@ 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 diff --git a/src/main/java/baritone/BaritoneProvider.java b/src/main/java/baritone/BaritoneProvider.java index 93f8faed..73e5e6e5 100644 --- a/src/main/java/baritone/BaritoneProvider.java +++ b/src/main/java/baritone/BaritoneProvider.java @@ -21,10 +21,9 @@ import baritone.api.IBaritone; import baritone.api.IBaritoneProvider; import baritone.api.cache.IWorldScanner; import baritone.cache.WorldScanner; -import net.minecraft.client.entity.EntityPlayerSP; import java.util.Collections; -import java.util.Set; +import java.util.List; /** * @author Brady @@ -40,14 +39,9 @@ public final class BaritoneProvider implements IBaritoneProvider { } @Override - public Set getAllBaritones() { - return Collections.singleton(primary); - } - - @Override - public IBaritone getBaritoneForPlayer(EntityPlayerSP player) { - // TODO implement on bot-system branch - return primary; + public List getAllBaritones() { + // TODO return a CopyOnWriteArrayList + return Collections.singletonList(primary); } @Override diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index d2739b38..6fd4665b 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -26,8 +26,8 @@ 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 @@ -37,7 +37,7 @@ public final class GameEventHandler implements IGameEventListener, Helper { private final Baritone baritone; - private final List listeners = new ArrayList<>(); + private final List listeners = new CopyOnWriteArrayList<>(); public GameEventHandler(Baritone baritone) { this.baritone = baritone; From b56cdcda523a26513612c6236614b5daf2a34d42 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 14:19:24 -0800 Subject: [PATCH 27/77] remove that toxic cloud --- .../api/behavior/IPathingBehavior.java | 2 +- .../baritone/behavior/PathingBehavior.java | 80 +++++++++---------- .../pathing/calc/AbstractNodeCostSearch.java | 13 ++- .../baritone/pathing/path/PathExecutor.java | 2 +- .../java/baritone/utils/PathRenderer.java | 3 +- .../baritone/utils/PathingControlManager.java | 5 +- 6 files changed, 46 insertions(+), 59 deletions(-) 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/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 7be1d405..14f1694e 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; @@ -57,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(); @@ -141,7 +140,7 @@ 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; @@ -166,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; } @@ -238,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 @@ -284,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 } @@ -294,14 +293,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, current = null; next = null; baritone.getInputOverrideHandler().clearAllKeys(); - AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(AbstractNodeCostSearch::cancel); + getInProgress().ifPresent(AbstractNodeCostSearch::cancel); baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); } public void forceCancel() { // NOT exposed on public api cancelEverything(); secretInternalSegmentCancel(); - isPathCalcInProgress = false; + inProgress = null; } /** @@ -321,7 +320,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return false; } synchronized (pathCalcLock) { - if (isPathCalcInProgress) { + if (inProgress != null) { return false; } queuePathEvent(PathEvent.CALC_STARTED); @@ -383,19 +382,35 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * @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; + // 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 + } + 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 timeout; + if (current == null) { + timeout = Baritone.settings().pathTimeoutMS.get(); + } else { + timeout = Baritone.settings().planAheadTimeoutMS.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, previous, context); + inProgress = pathfinder; Baritone.getExecutor().execute(() -> { if (talkAboutIt) { logDebug("Starting to search for path from " + start + " to " + goal); } - PathCalculationResult calcResult = findPath(start, previous, context); + PathCalculationResult calcResult = pathfinder.calculate(timeout); Optional path = calcResult.path; if (Baritone.settings().cutoffAtLoadBoundary.get()) { path = path.map(p -> { @@ -453,51 +468,28 @@ 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()); - } + private AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, Optional 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()); - } + return new AStarPathFinder(start.getX(), start.getY(), start.getZ(), transformed, favoredPositions, context); } @Override diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 79a56037..a0f4f6e4 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; @@ -107,6 +108,10 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { } 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, Optional.empty()); } finally { // this is run regardless of what exception may or may not be raised by calculate0 currentlyRunning = null; @@ -218,12 +223,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/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index dca2a0e9..5dfc420d 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -295,7 +295,7 @@ public class PathExecutor implements IPathExecutor, Helper { } private boolean shouldPause() { - Optional current = AbstractNodeCostSearch.getCurrentlyRunning(); + Optional current = behavior.getInProgress(); if (!current.isPresent()) { return false; } diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 443cd035..e14c14da 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -28,7 +28,6 @@ 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.renderer.BufferBuilder; @@ -113,7 +112,7 @@ public final class PathRenderer implements Helper { } // 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, renderView, partialTicks, Baritone.settings().colorBestPathSoFar.get(), Baritone.settings().fadePath.get(), 10, 20); }); diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 9ea193a1..a818b7c5 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -24,7 +24,6 @@ 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; @@ -90,12 +89,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; From 80d6d7fd5892129fb87abc9dba0e39622bc41fd8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 14:21:36 -0800 Subject: [PATCH 28/77] simplify --- src/main/java/baritone/behavior/PathingBehavior.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 14f1694e..b2132910 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -146,7 +146,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return; } queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true, Optional.empty()); + findPathInNewThread(pathStart(), true); } return; } @@ -181,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); } } } @@ -324,7 +324,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return false; } queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true, Optional.empty()); + findPathInNewThread(pathStart(), true); return true; } } @@ -381,7 +381,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * @param start * @param talkAboutIt */ - private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt, final Optional previous) { + 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)) { @@ -403,7 +403,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, timeout = Baritone.settings().planAheadTimeoutMS.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, previous, context); + AbstractNodeCostSearch pathfinder = createPathfinder(start, goal, Optional.ofNullable(current).map(PathExecutor::getPath), context); inProgress = pathfinder; Baritone.getExecutor().execute(() -> { if (talkAboutIt) { From 8385bc35ed9539fabcdd4711b043ba647792e7b6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 14:26:35 -0800 Subject: [PATCH 29/77] wow thats a rare bug --- src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index a0f4f6e4..3285a5ce 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -193,7 +193,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { @Override public Optional bestPathSoFar() { - if (startNode == null || bestSoFar[0] == null) { + if (startNode == null || bestSoFar == null || bestSoFar[0] == null) { return Optional.empty(); } for (int i = 0; i < bestSoFar.length; i++) { From f808fc98020c04ad0a0c61d31e1f4acd79d0a707 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 14:27:30 -0800 Subject: [PATCH 30/77] general cleanup --- .../pathing/calc/AbstractNodeCostSearch.java | 30 ------------------- 1 file changed, 30 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index 3285a5ce..fa55a998 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -35,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; @@ -114,19 +109,10 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { return new PathCalculationResult(PathCalculationResult.Type.EXCEPTION, Optional.empty()); } 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); /** @@ -161,22 +147,6 @@ 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 { From f6dee1ecb7c2792f23926ab4a08d930669826928 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 14:29:33 -0800 Subject: [PATCH 31/77] add todo --- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index b2132910..78cd0913 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -335,7 +335,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * * @return The starting {@link BlockPos} for a new path */ - public BlockPos pathStart() { + 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) { From 237f1846d384f21277f331af625f8b74eb74f8f2 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 14 Nov 2018 16:29:15 -0600 Subject: [PATCH 32/77] Remove Baritone casts --- src/api/java/baritone/api/IBaritone.java | 9 ++--- .../api/event/listener/IEventBus.java | 36 +++++++++++++++++++ .../baritone/launch/mixins/MixinEntity.java | 3 +- .../launch/mixins/MixinEntityLivingBase.java | 3 +- .../launch/mixins/MixinEntityPlayerSP.java | 7 ++-- .../launch/mixins/MixinEntityRenderer.java | 3 +- .../launch/mixins/MixinMinecraft.java | 13 ++++--- .../mixins/MixinNetHandlerPlayClient.java | 7 ++-- .../launch/mixins/MixinNetworkManager.java | 9 +++-- .../launch/mixins/MixinWorldClient.java | 5 ++- src/main/java/baritone/Baritone.java | 14 +++----- .../java/baritone/event/GameEventHandler.java | 5 +-- .../baritone/utils/PathingControlManager.java | 2 +- 13 files changed, 68 insertions(+), 48 deletions(-) create mode 100644 src/api/java/baritone/api/event/listener/IEventBus.java diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index 451e7990..5ca54a25 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -21,7 +21,7 @@ import baritone.api.behavior.ILookBehavior; import baritone.api.behavior.IMemoryBehavior; import baritone.api.behavior.IPathingBehavior; import baritone.api.cache.IWorldProvider; -import baritone.api.event.listener.IGameEventListener; +import baritone.api.event.listener.IEventBus; import baritone.api.process.ICustomGoalProcess; import baritone.api.process.IFollowProcess; import baritone.api.process.IGetToBlockProcess; @@ -79,10 +79,5 @@ public interface IBaritone { IPlayerContext getPlayerContext(); - /** - * Registers a {@link IGameEventListener} with Baritone's "event bus". - * - * @param listener The listener - */ - void registerEventListener(IGameEventListener listener); + IEventBus getGameEventHandler(); } 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/launch/java/baritone/launch/mixins/MixinEntity.java b/src/launch/java/baritone/launch/mixins/MixinEntity.java index 93b9d901..fe498202 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntity.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntity.java @@ -17,7 +17,6 @@ package baritone.launch.mixins; -import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.event.events.RotationMoveEvent; import net.minecraft.client.entity.EntityPlayerSP; @@ -54,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) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this)).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 f640f349..1a7d298f 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityLivingBase.java @@ -17,7 +17,6 @@ package baritone.launch.mixins; -import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.event.events.RotationMoveEvent; import net.minecraft.client.entity.EntityPlayerSP; @@ -57,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) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this)).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 5b908d8b..9c9509f0 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityPlayerSP.java @@ -17,7 +17,6 @@ package baritone.launch.mixins; -import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.behavior.IPathingBehavior; import baritone.api.event.events.ChatEvent; @@ -45,7 +44,7 @@ public class MixinEntityPlayerSP { ) private void sendChatMessage(String msg, CallbackInfo ci) { ChatEvent event = new ChatEvent((EntityPlayerSP) (Object) this, msg); - ((Baritone) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this)).getGameEventHandler().onSendChatMessage(event); + BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onSendChatMessage(event); if (event.isCancelled()) { ci.cancel(); } @@ -61,7 +60,7 @@ public class MixinEntityPlayerSP { ) ) private void onPreUpdate(CallbackInfo ci) { - ((Baritone) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this)).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( @@ -74,7 +73,7 @@ public class MixinEntityPlayerSP { ) ) private void onPostUpdate(CallbackInfo ci) { - ((Baritone) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this)).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( diff --git a/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java b/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java index 63c3c223..dfd01e46 100644 --- a/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java +++ b/src/launch/java/baritone/launch/mixins/MixinEntityRenderer.java @@ -17,7 +17,6 @@ package baritone.launch.mixins; -import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.event.events.RenderEvent; @@ -40,7 +39,7 @@ public class MixinEntityRenderer { ) private void renderWorldPass(int pass, float partialTicks, long finishTimeNano, CallbackInfo ci) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { - ((Baritone) ibaritone).getGameEventHandler().onRenderPass(new RenderEvent(partialTicks)); + ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks)); } } } diff --git a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java index 303a53b1..12e91574 100644 --- a/src/launch/java/baritone/launch/mixins/MixinMinecraft.java +++ b/src/launch/java/baritone/launch/mixins/MixinMinecraft.java @@ -91,7 +91,7 @@ public class MixinMinecraft { ? TickEvent.Type.IN : TickEvent.Type.OUT; - ((Baritone) ibaritone).getGameEventHandler().onTick(new TickEvent(EventState.PRE, type)); + ibaritone.getGameEventHandler().onTick(new TickEvent(EventState.PRE, type)); } } @@ -102,7 +102,7 @@ public class MixinMinecraft { ) private void runTickKeyboard(CallbackInfo ci) { // keyboard input is only the primary baritone - ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getGameEventHandler().onProcessKeyBinds(); + BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onProcessKeyBinds(); } @Inject( @@ -117,7 +117,7 @@ public class MixinMinecraft { // mc.world changing is only the primary baritone - ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getGameEventHandler().onWorldEvent( + BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onWorldEvent( new WorldEvent( world, EventState.PRE @@ -133,8 +133,7 @@ public class MixinMinecraft { // still fire event for both null, as that means we've just finished exiting a world // mc.world changing is only the primary baritone - - ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getGameEventHandler().onWorldEvent( + BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onWorldEvent( new WorldEvent( world, EventState.POST @@ -165,7 +164,7 @@ public class MixinMinecraft { ) private void onBlockBreak(CallbackInfo ci, BlockPos pos) { // clickMouse is only for the main player - ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getGameEventHandler().onBlockInteract(new BlockInteractEvent(pos, BlockInteractEvent.Type.BREAK)); + BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(pos, BlockInteractEvent.Type.BREAK)); } @Inject( @@ -178,6 +177,6 @@ public class MixinMinecraft { ) private void onBlockUse(CallbackInfo ci, EnumHand var1[], int var2, int var3, EnumHand enumhand, ItemStack itemstack, BlockPos blockpos, int i, EnumActionResult enumactionresult) { // rightClickMouse is only for the main player - ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getGameEventHandler().onBlockInteract(new BlockInteractEvent(blockpos, BlockInteractEvent.Type.USE)); + 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 fa5345d2..9fc1bd6f 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java @@ -17,7 +17,6 @@ package baritone.launch.mixins; -import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.event.events.ChunkEvent; @@ -47,7 +46,7 @@ public class MixinNetHandlerPlayClient { private void preRead(SPacketChunkData packetIn, CallbackInfo ci) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) { - ((Baritone) ibaritone).getGameEventHandler().onChunkEvent( + ibaritone.getGameEventHandler().onChunkEvent( new ChunkEvent( EventState.PRE, ChunkEvent.Type.POPULATE, @@ -66,7 +65,7 @@ public class MixinNetHandlerPlayClient { private void postHandleChunkData(SPacketChunkData packetIn, CallbackInfo ci) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) { - ((Baritone) ibaritone).getGameEventHandler().onChunkEvent( + ibaritone.getGameEventHandler().onChunkEvent( new ChunkEvent( EventState.POST, ChunkEvent.Type.POPULATE, @@ -88,7 +87,7 @@ public class MixinNetHandlerPlayClient { private void onPlayerDeath(SPacketCombatEvent packetIn, CallbackInfo ci) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) { - ((Baritone) ibaritone).getGameEventHandler().onPlayerDeath(); + ibaritone.getGameEventHandler().onPlayerDeath(); } } } diff --git a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java index 4d20bb7b..577be96d 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetworkManager.java @@ -17,7 +17,6 @@ package baritone.launch.mixins; -import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.event.events.PacketEvent; @@ -61,7 +60,7 @@ public class MixinNetworkManager { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) { - ((Baritone) ibaritone).getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, inPacket)); + ibaritone.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, inPacket)); } } } @@ -77,7 +76,7 @@ public class MixinNetworkManager { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) { - ((Baritone) ibaritone).getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, inPacket)); + ibaritone.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, inPacket)); } } } @@ -95,7 +94,7 @@ public class MixinNetworkManager { } for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) { - ((Baritone) ibaritone).getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, packet)); + ibaritone.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, packet)); } } } @@ -110,7 +109,7 @@ public class MixinNetworkManager { } for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) { - ((Baritone) ibaritone).getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, packet)); + 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 d76e6057..7c156163 100644 --- a/src/launch/java/baritone/launch/mixins/MixinWorldClient.java +++ b/src/launch/java/baritone/launch/mixins/MixinWorldClient.java @@ -17,7 +17,6 @@ package baritone.launch.mixins; -import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.event.events.ChunkEvent; @@ -42,7 +41,7 @@ public class MixinWorldClient { private void preDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { if (ibaritone.getPlayerContext().world() == (WorldClient) (Object) this) { - ((Baritone) ibaritone).getGameEventHandler().onChunkEvent( + ibaritone.getGameEventHandler().onChunkEvent( new ChunkEvent( EventState.PRE, loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD, @@ -62,7 +61,7 @@ public class MixinWorldClient { private void postDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { if (ibaritone.getPlayerContext().world() == (WorldClient) (Object) this) { - ((Baritone) ibaritone).getGameEventHandler().onChunkEvent( + ibaritone.getGameEventHandler().onChunkEvent( new ChunkEvent( EventState.POST, loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD, diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index c5c1b3ed..bd5b97e8 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -20,7 +20,7 @@ package baritone; import baritone.api.BaritoneAPI; import baritone.api.IBaritone; import baritone.api.Settings; -import baritone.api.event.listener.IGameEventListener; +import baritone.api.event.listener.IEventBus; import baritone.api.utils.IPlayerContext; import baritone.behavior.Behavior; import baritone.behavior.LookBehavior; @@ -125,7 +125,7 @@ public class Baritone implements IBaritone { this.worldProvider = new WorldProvider(); if (BaritoneAutoTest.ENABLE_AUTO_TEST) { - registerEventListener(BaritoneAutoTest.INSTANCE); + this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE); } this.initialized = true; @@ -135,17 +135,13 @@ public class Baritone implements IBaritone { return this.pathingControlManager; } - public IGameEventListener getGameEventHandler() { - return this.gameEventHandler; - } - public List getBehaviors() { return this.behaviors; } public void registerBehavior(Behavior behavior) { this.behaviors.add(behavior); - this.registerEventListener(behavior); + this.gameEventHandler.registerEventListener(behavior); } @Override @@ -199,8 +195,8 @@ public class Baritone implements IBaritone { } @Override - public void registerEventListener(IGameEventListener listener) { - this.gameEventHandler.registerEventListener(listener); + public IEventBus getGameEventHandler() { + return this.gameEventHandler; } public static Settings settings() { diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 6fd4665b..7ac04643 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -20,6 +20,7 @@ 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; @@ -33,7 +34,7 @@ import java.util.concurrent.CopyOnWriteArrayList; * @author Brady * @since 7/31/2018 */ -public final class GameEventHandler implements IGameEventListener, Helper { +public final class GameEventHandler implements IEventBus, Helper { private final Baritone baritone; @@ -140,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/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index a818b7c5..fa58a069 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -43,7 +43,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) { From f5d0143b09bc12baca994c5a20733a81fa4440aa Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 14:37:41 -0800 Subject: [PATCH 33/77] im dumb --- src/main/java/baritone/pathing/calc/AStarPathFinder.java | 1 - src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 -- 2 files changed, 3 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index b9babdda..c9b7a11e 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -79,7 +79,6 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel 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) { if (slowPath) { try { diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 9808de6d..841349e4 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -28,7 +28,6 @@ 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.Movement; import baritone.pathing.movement.Moves; import baritone.process.CustomGoalProcess; @@ -230,7 +229,6 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } if (msg.equals("forcecancel")) { pathingBehavior.cancelEverything(); - AbstractNodeCostSearch.forceCancel(); pathingBehavior.forceCancel(); logDirect("ok force canceled"); return true; From 57c0613843af34306463c78f3c184e2481f65dbd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 14 Nov 2018 16:39:04 -0800 Subject: [PATCH 34/77] rename --- src/main/java/baritone/Baritone.java | 4 ++-- ...calPlayerContext.java => PrimaryPlayerContext.java} | 10 +++------- 2 files changed, 5 insertions(+), 9 deletions(-) rename src/main/java/baritone/utils/player/{LocalPlayerContext.java => PrimaryPlayerContext.java} (85%) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index bd5b97e8..42403e84 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -36,7 +36,7 @@ import baritone.utils.BaritoneAutoTest; import baritone.utils.ExampleBaritoneControl; import baritone.utils.InputOverrideHandler; import baritone.utils.PathingControlManager; -import baritone.utils.player.LocalPlayerContext; +import baritone.utils.player.PrimaryPlayerContext; import net.minecraft.client.Minecraft; import java.io.File; @@ -102,7 +102,7 @@ public class Baritone implements IBaritone { } // Define this before behaviors try and get it, or else it will be null and the builds will fail! - this.playerContext = LocalPlayerContext.INSTANCE; + this.playerContext = PrimaryPlayerContext.INSTANCE; this.behaviors = new ArrayList<>(); { diff --git a/src/main/java/baritone/utils/player/LocalPlayerContext.java b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java similarity index 85% rename from src/main/java/baritone/utils/player/LocalPlayerContext.java rename to src/main/java/baritone/utils/player/PrimaryPlayerContext.java index 02c08c11..4247e92b 100644 --- a/src/main/java/baritone/utils/player/LocalPlayerContext.java +++ b/src/main/java/baritone/utils/player/PrimaryPlayerContext.java @@ -20,7 +20,7 @@ package baritone.utils.player; import baritone.api.BaritoneAPI; import baritone.api.cache.IWorldData; import baritone.api.utils.IPlayerContext; -import net.minecraft.client.Minecraft; +import baritone.utils.Helper; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.multiplayer.PlayerControllerMP; import net.minecraft.util.math.RayTraceResult; @@ -32,13 +32,9 @@ import net.minecraft.world.World; * @author Brady * @since 11/12/2018 */ -public final class LocalPlayerContext implements IPlayerContext { +public enum PrimaryPlayerContext implements IPlayerContext, Helper { - private static final Minecraft mc = Minecraft.getMinecraft(); - - public static final LocalPlayerContext INSTANCE = new LocalPlayerContext(); - - private LocalPlayerContext() {} + INSTANCE; @Override public EntityPlayerSP player() { From 04e87c981096c35aa494c67c06766c931edcd21f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 15 Nov 2018 16:03:20 -0800 Subject: [PATCH 35/77] cleaner --- src/main/java/baritone/utils/InputOverrideHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 191d145a..c6e19c15 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -112,7 +112,7 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri if (event.getType() == TickEvent.Type.OUT) { return; } - boolean stillClick = blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.getKeyBinding())); + boolean stillClick = blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT)); setInputForceState(Input.CLICK_LEFT, stillClick); } From 737c632227b7ab435d74ce2ca266c3327d9ad42a Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 16 Nov 2018 16:28:20 -0800 Subject: [PATCH 36/77] path creation no longer throws this --- .../java/baritone/pathing/calc/AbstractNodeCostSearch.java | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index fa55a998..c2ce36e2 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -149,12 +149,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { @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() { From ce0e8b4cd1caf77dada7a69197992983c5bfabfe Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 17 Nov 2018 11:18:55 -0600 Subject: [PATCH 37/77] Clean up some bad Optional practices --- .../api/pathing/goals/GoalRunAway.java | 17 ++++++++--------- .../api/utils/PathCalculationResult.java | 18 +++++++++++++++--- .../baritone/behavior/PathingBehavior.java | 4 ++-- .../pathing/calc/AbstractNodeCostSearch.java | 11 +++++------ .../java/baritone/process/MineProcess.java | 2 +- 5 files changed, 31 insertions(+), 21 deletions(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalRunAway.java b/src/api/java/baritone/api/pathing/goals/GoalRunAway.java index 44c5fa80..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.6 + GoalYLevel.calculate(maintainY.get(), y) * 1.5; + 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/PathCalculationResult.java b/src/api/java/baritone/api/utils/PathCalculationResult.java index 69d2a9b3..df009952 100644 --- a/src/api/java/baritone/api/utils/PathCalculationResult.java +++ b/src/api/java/baritone/api/utils/PathCalculationResult.java @@ -23,14 +23,26 @@ 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; } + public final Optional getPath() { + return Optional.ofNullable(this.path); + } + + public final Type getType() { + return this.type; + } + public enum Type { SUCCESS_TO_GOAL, SUCCESS_SEGMENT, diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 78cd0913..31f6721f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -411,7 +411,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } PathCalculationResult calcResult = pathfinder.calculate(timeout); - Optional path = calcResult.path; + Optional path = calcResult.getPath(); if (Baritone.settings().cutoffAtLoadBoundary.get()) { path = path.map(p -> { IPath result = p.cutoffAtLoadedChunks(context.world()); @@ -443,7 +443,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); } diff --git a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java index c2ce36e2..ac4efa4d 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -89,16 +89,15 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { } this.cancelRequested = false; try { - Optional path = calculate0(timeout); - path = path.map(IPath::postProcess); + IPath path = calculate0(timeout).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); @@ -106,7 +105,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { } catch (Exception e) { Helper.HELPER.logDebug("Pathing exception: " + e); e.printStackTrace(); - return new PathCalculationResult(PathCalculationResult.Type.EXCEPTION, Optional.empty()); + return new PathCalculationResult(PathCalculationResult.Type.EXCEPTION); } finally { // this is run regardless of what exception may or may not be raised by calculate0 isFinished = true; diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 60b36ea1..204e11c5 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -141,7 +141,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro // 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; From 6caae889b7c578ae359daf9ff2d6db5a886ac293 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 17 Nov 2018 11:26:46 -0600 Subject: [PATCH 38/77] Fix AStarPathFinder Optional usage that's icky --- src/main/java/baritone/behavior/PathingBehavior.java | 10 +++++----- .../java/baritone/pathing/calc/AStarPathFinder.java | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 31f6721f..884fe75b 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -403,7 +403,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, timeout = Baritone.settings().planAheadTimeoutMS.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, Optional.ofNullable(current).map(PathExecutor::getPath), context); + AbstractNodeCostSearch pathfinder = createPathfinder(start, goal, current == null ? null : current.getPath(), context); inProgress = pathfinder; Baritone.getExecutor().execute(() -> { if (talkAboutIt) { @@ -474,7 +474,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, }); } - private AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, Optional previous, CalculationContext context) { + private 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(); @@ -483,11 +483,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, transformed = new GoalXZ(pos.getX(), pos.getZ()); } } - Optional> favoredPositions; + HashSet favoredPositions; if (Baritone.settings().backtrackCostFavoringCoefficient.get() == 1D) { - favoredPositions = Optional.empty(); + favoredPositions = null; } 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 + favoredPositions = previous.positions().stream().map(BetterBlockPos::longHash).collect(Collectors.toCollection(HashSet::new)); } return new AStarPathFinder(start.getX(), start.getY(), start.getZ(), transformed, favoredPositions, context); } diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index c9b7a11e..f6592094 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -39,10 +39,10 @@ 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; @@ -63,7 +63,7 @@ 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(); @@ -75,7 +75,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel 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(); From 689dc743301a97b3130adfc7249efc8248ca5a05 Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 17 Nov 2018 11:41:16 -0600 Subject: [PATCH 39/77] Whoops --- src/main/java/baritone/behavior/PathingBehavior.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 884fe75b..1943b215 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -483,10 +483,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, transformed = new GoalXZ(pos.getX(), pos.getZ()); } } - HashSet favoredPositions; - if (Baritone.settings().backtrackCostFavoringCoefficient.get() == 1D) { - favoredPositions = null; - } else { + 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); From 46de72e28c503330e5d7145ac9c99ee2dafc3c8d Mon Sep 17 00:00:00 2001 From: Brady Date: Sat, 17 Nov 2018 18:07:16 -0600 Subject: [PATCH 40/77] Comms Sourceset --- build.gradle | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/build.gradle b/build.gradle index e0b556a2..1c6f5b9e 100755 --- a/build.gradle +++ b/build.gradle @@ -54,6 +54,10 @@ sourceSets { launch { compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output } + comms {} + main { + compileClasspath += comms.compileClasspath + } } minecraft { From 12bbd57a247d2323f7d3c8cb7b2ba6b363f4470c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 17 Nov 2018 16:09:03 -0800 Subject: [PATCH 41/77] standalone build shouldn't keep ExampleBaritoneControl --- scripts/proguard.pro | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 { From f014e42aa4b6c4b47680803180ff4fe81b1e8f9e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 18 Nov 2018 11:01:39 -0800 Subject: [PATCH 42/77] initial comms --- src/comms/java/comms/BufferedConnection.java | 86 ++++++++++++++++ .../java/comms/ConstructingDeserializer.java | 52 ++++++++++ src/comms/java/comms/FilteredConnection.java | 55 +++++++++++ src/comms/java/comms/HandlableMessage.java | 22 +++++ src/comms/java/comms/IConnection.java | 28 ++++++ src/comms/java/comms/IMessageListener.java | 36 +++++++ src/comms/java/comms/MessageDeserializer.java | 25 +++++ src/comms/java/comms/Pipe.java | 99 +++++++++++++++++++ src/comms/java/comms/SerializableMessage.java | 33 +++++++ .../java/comms/SerializedConnection.java | 59 +++++++++++ src/comms/java/comms/SocketConnection.java | 27 +++++ .../java/comms/downward/MessageChat.java | 49 +++++++++ src/comms/java/comms/iMessage.java | 30 ++++++ .../java/comms/upward/MessageStatus.java | 57 +++++++++++ src/main/java/baritone/Baritone.java | 59 +++++------ .../baritone/behavior/ControllerBehavior.java | 99 +++++++++++++++++++ .../utils/ExampleBaritoneControl.java | 20 ++++ 17 files changed, 808 insertions(+), 28 deletions(-) create mode 100644 src/comms/java/comms/BufferedConnection.java create mode 100644 src/comms/java/comms/ConstructingDeserializer.java create mode 100644 src/comms/java/comms/FilteredConnection.java create mode 100644 src/comms/java/comms/HandlableMessage.java create mode 100644 src/comms/java/comms/IConnection.java create mode 100644 src/comms/java/comms/IMessageListener.java create mode 100644 src/comms/java/comms/MessageDeserializer.java create mode 100644 src/comms/java/comms/Pipe.java create mode 100644 src/comms/java/comms/SerializableMessage.java create mode 100644 src/comms/java/comms/SerializedConnection.java create mode 100644 src/comms/java/comms/SocketConnection.java create mode 100644 src/comms/java/comms/downward/MessageChat.java create mode 100644 src/comms/java/comms/iMessage.java create mode 100644 src/comms/java/comms/upward/MessageStatus.java create mode 100644 src/main/java/baritone/behavior/ControllerBehavior.java diff --git a/src/comms/java/comms/BufferedConnection.java b/src/comms/java/comms/BufferedConnection.java new file mode 100644 index 00000000..13fef7f5 --- /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(T message) throws IOException { + wrapped.sendMessage(message); + } + + @Override + public T 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..4048a7be --- /dev/null +++ b/src/comms/java/comms/ConstructingDeserializer.java @@ -0,0 +1,52 @@ +/* + * 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()) { + MSGS.add((Class) m.getParameterTypes()[0]); + } + } + + @Override + public SerializableMessage 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/FilteredConnection.java b/src/comms/java/comms/FilteredConnection.java new file mode 100644 index 00000000..2d740fcd --- /dev/null +++ b/src/comms/java/comms/FilteredConnection.java @@ -0,0 +1,55 @@ +/* + * 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; + +/** + * This is just a meme idk if this is actually useful + * + * @param + */ +public class FilteredConnection implements IConnection { + private final Class klass; + private final IConnection wrapped; + + public FilteredConnection(IConnection wrapped, Class klass) { + this.klass = klass; + this.wrapped = wrapped; + } + + @Override + public void sendMessage(T message) throws IOException { + wrapped.sendMessage(message); + } + + @Override + public T receiveMessage() throws IOException { + while (true) { + iMessage msg = wrapped.receiveMessage(); + if (klass.isInstance(msg)) { + return klass.cast(msg); + } + } + } + + @Override + public void close() { + wrapped.close(); + } +} diff --git a/src/comms/java/comms/HandlableMessage.java b/src/comms/java/comms/HandlableMessage.java new file mode 100644 index 00000000..dce1d3de --- /dev/null +++ b/src/comms/java/comms/HandlableMessage.java @@ -0,0 +1,22 @@ +/* + * 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; + +public interface HandlableMessage { + void handle(IMessageListener listener); +} diff --git a/src/comms/java/comms/IConnection.java b/src/comms/java/comms/IConnection.java new file mode 100644 index 00000000..05cef73d --- /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(T message) throws IOException; + + T 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..afed4cfe --- /dev/null +++ b/src/comms/java/comms/IMessageListener.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 comms; + +import comms.downward.MessageChat; +import comms.upward.MessageStatus; + +public interface IMessageListener { + default void handle(MessageStatus message) { + unhandled(message); + } + + default void handle(MessageChat 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..ed18bf1a --- /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 { + SerializableMessage 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..a8cad44f --- /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(T 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 T 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/SerializableMessage.java b/src/comms/java/comms/SerializableMessage.java new file mode 100644 index 00000000..90187446 --- /dev/null +++ b/src/comms/java/comms/SerializableMessage.java @@ -0,0 +1,33 @@ +/* + * 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; + +public interface SerializableMessage extends 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()); + } +} diff --git a/src/comms/java/comms/SerializedConnection.java b/src/comms/java/comms/SerializedConnection.java new file mode 100644 index 00000000..9e8af84c --- /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 void sendMessage(SerializableMessage message) throws IOException { + message.writeHeader(out); + message.write(out); + } + + @Override + public SerializableMessage 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..35b63ee5 --- /dev/null +++ b/src/comms/java/comms/downward/MessageChat.java @@ -0,0 +1,49 @@ +/* + * 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.HandlableMessage; +import comms.IMessageListener; +import comms.SerializableMessage; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +public class MessageChat implements SerializableMessage, HandlableMessage { + + 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/iMessage.java b/src/comms/java/comms/iMessage.java new file mode 100644 index 00000000..5a4ebd29 --- /dev/null +++ b/src/comms/java/comms/iMessage.java @@ -0,0 +1,30 @@ +/* + * 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; + +/** + * hell yeah + *

+ *

+ * dumb android users cant read this file + *

+ * + * @author leijurv + */ +public interface iMessage { +} diff --git a/src/comms/java/comms/upward/MessageStatus.java b/src/comms/java/comms/upward/MessageStatus.java new file mode 100644 index 00000000..fe0a6489 --- /dev/null +++ b/src/comms/java/comms/upward/MessageStatus.java @@ -0,0 +1,57 @@ +/* + * 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.HandlableMessage; +import comms.IMessageListener; +import comms.SerializableMessage; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +public class MessageStatus implements SerializableMessage, HandlableMessage { + + public final double x; + public final double y; + public final double z; + + public MessageStatus(DataInputStream in) throws IOException { + this.x = in.readDouble(); + this.y = in.readDouble(); + this.z = in.readDouble(); + } + + public MessageStatus(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + @Override + public void write(DataOutputStream out) throws IOException { + out.writeDouble(x); + out.writeDouble(y); + out.writeDouble(z); + } + + @Override + public void handle(IMessageListener listener) { + listener.handle(this); + } +} diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 42403e84..0b42e112 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -22,10 +22,7 @@ import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.event.listener.IEventBus; import baritone.api.utils.IPlayerContext; -import baritone.behavior.Behavior; -import baritone.behavior.LookBehavior; -import baritone.behavior.MemoryBehavior; -import baritone.behavior.PathingBehavior; +import baritone.behavior.*; import baritone.cache.WorldProvider; import baritone.event.GameEventHandler; import baritone.process.CustomGoalProcess; @@ -77,6 +74,7 @@ public class Baritone implements IBaritone { private GameEventHandler gameEventHandler; private List behaviors; + private ControllerBehavior controllerBehavior; private PathingBehavior pathingBehavior; private LookBehavior lookBehavior; private MemoryBehavior memoryBehavior; @@ -107,6 +105,7 @@ public class Baritone implements IBaritone { 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); @@ -131,10 +130,6 @@ public class Baritone implements IBaritone { this.initialized = true; } - public PathingControlManager getPathingControlManager() { - return this.pathingControlManager; - } - public List getBehaviors() { return this.behaviors; } @@ -144,11 +139,19 @@ public class Baritone implements IBaritone { this.gameEventHandler.registerEventListener(behavior); } + 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 this.customGoalProcess; @@ -160,18 +163,8 @@ public class Baritone implements IBaritone { } @Override - public IPlayerContext getPlayerContext() { - return this.playerContext; - } - - @Override - public FollowProcess getFollowProcess() { - return this.followProcess; - } - - @Override - public LookBehavior getLookBehavior() { - return this.lookBehavior; + public PathingBehavior getPathingBehavior() { + return this.pathingBehavior; } @Override @@ -180,13 +173,13 @@ public class Baritone implements IBaritone { } @Override - public MineProcess getMineProcess() { - return this.mineProcess; + public IPlayerContext getPlayerContext() { + return this.playerContext; } @Override - public PathingBehavior getPathingBehavior() { - return this.pathingBehavior; + public FollowProcess getFollowProcess() { + return this.followProcess; } @Override @@ -199,6 +192,20 @@ public class Baritone implements IBaritone { return this.gameEventHandler; } + @Override + public LookBehavior getLookBehavior() { + return this.lookBehavior; + } + + @Override + public MineProcess getMineProcess() { + return this.mineProcess; + } + + public static Executor getExecutor() { + return threadPool; + } + public static Settings settings() { return BaritoneAPI.getSettings(); } @@ -206,8 +213,4 @@ public class Baritone implements IBaritone { public static File getDir() { return dir; } - - public static Executor getExecutor() { - return threadPool; - } } diff --git a/src/main/java/baritone/behavior/ControllerBehavior.java b/src/main/java/baritone/behavior/ControllerBehavior.java new file mode 100644 index 00000000..25a128a1 --- /dev/null +++ b/src/main/java/baritone/behavior/ControllerBehavior.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 baritone.behavior; + +import baritone.Baritone; +import baritone.api.event.events.ChatEvent; +import baritone.api.event.events.TickEvent; +import baritone.utils.Helper; +import comms.*; +import comms.downward.MessageChat; +import comms.upward.MessageStatus; + +import java.io.IOException; +import java.util.List; + +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(new MessageStatus(ctx.player().posX, ctx.player().posY, ctx.player().posZ)); + } + + private void readAndHandle() { + if (conn == null) { + return; + } + try { + List msgs = conn.receiveMessagesNonBlocking(); + msgs.forEach(msg -> ((HandlableMessage) msg).handle(this)); + } catch (IOException e) { + e.printStackTrace(); + disconnect(); + } + } + + public boolean trySend(SerializableMessage 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 unhandled(iMessage msg) { + Helper.HELPER.logDebug("Unhandled message received by ControllerBehavior " + msg); + } +} diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 841349e4..03f1079f 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -31,6 +31,7 @@ import baritone.cache.Waypoint; 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; @@ -38,6 +39,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; @@ -462,6 +465,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"); } From 2d87033f491c53f6cb9f5443e24aac304025a78e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 18 Nov 2018 11:06:11 -0800 Subject: [PATCH 43/77] f --- build.gradle | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index 1c6f5b9e..f38b6c85 100755 --- a/build.gradle +++ b/build.gradle @@ -51,13 +51,13 @@ compileJava { } sourceSets { - launch { - compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output - } comms {} main { compileClasspath += comms.compileClasspath } + launch { + compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output + } } minecraft { From f01cf669e80d921e168bf4e6f53e5c7aa0501a59 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 18 Nov 2018 11:06:40 -0800 Subject: [PATCH 44/77] wtf --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index f38b6c85..86638f2f 100755 --- a/build.gradle +++ b/build.gradle @@ -53,7 +53,7 @@ compileJava { sourceSets { comms {} main { - compileClasspath += comms.compileClasspath + compileClasspath += comms.compileClasspath + comms.runtimeClasspath + comms.output } launch { compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output From 3c913a7b85dc9a37b3c976cc52af42d2b3e1c116 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 18 Nov 2018 13:27:25 -0600 Subject: [PATCH 45/77] Fix jar export --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 86638f2f..6120aa47 100755 --- a/build.gradle +++ b/build.gradle @@ -53,7 +53,7 @@ compileJava { sourceSets { comms {} main { - compileClasspath += comms.compileClasspath + comms.runtimeClasspath + comms.output + compileClasspath += comms.compileClasspath + comms.output } launch { compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output @@ -103,7 +103,7 @@ mixin { } jar { - from sourceSets.launch.output, sourceSets.api.output + from sourceSets.comms.output, sourceSets.launch.output, sourceSets.api.output preserveFileTimestamps = false reproducibleFileOrder = true } From dfb49179c5fd7bedaf6e25a438ee506affe978cf Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 18 Nov 2018 11:27:38 -0800 Subject: [PATCH 46/77] not a handler lol --- src/comms/java/comms/ConstructingDeserializer.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/comms/java/comms/ConstructingDeserializer.java b/src/comms/java/comms/ConstructingDeserializer.java index 4048a7be..3879204a 100644 --- a/src/comms/java/comms/ConstructingDeserializer.java +++ b/src/comms/java/comms/ConstructingDeserializer.java @@ -32,7 +32,9 @@ public enum ConstructingDeserializer implements MessageDeserializer { 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()) { - MSGS.add((Class) m.getParameterTypes()[0]); + if (m.getName().equals("handle")) { + MSGS.add((Class) m.getParameterTypes()[0]); + } } } From 9ad35dbf28f1a5c6f3ae4c74263fec4ec888e8b6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 18 Nov 2018 11:35:54 -0800 Subject: [PATCH 47/77] remove the useless stuff --- src/comms/java/comms/BufferedConnection.java | 16 +++--- .../java/comms/ConstructingDeserializer.java | 8 +-- src/comms/java/comms/FilteredConnection.java | 55 ------------------- src/comms/java/comms/HandlableMessage.java | 22 -------- src/comms/java/comms/IConnection.java | 6 +- src/comms/java/comms/MessageDeserializer.java | 2 +- src/comms/java/comms/Pipe.java | 18 +++--- src/comms/java/comms/SerializableMessage.java | 33 ----------- .../java/comms/SerializedConnection.java | 6 +- .../java/comms/downward/MessageChat.java | 5 +- src/comms/java/comms/iMessage.java | 14 +++++ .../java/comms/upward/MessageStatus.java | 5 +- .../baritone/behavior/ControllerBehavior.java | 13 +++-- 13 files changed, 54 insertions(+), 149 deletions(-) delete mode 100644 src/comms/java/comms/FilteredConnection.java delete mode 100644 src/comms/java/comms/HandlableMessage.java delete mode 100644 src/comms/java/comms/SerializableMessage.java diff --git a/src/comms/java/comms/BufferedConnection.java b/src/comms/java/comms/BufferedConnection.java index 13fef7f5..450010e7 100644 --- a/src/comms/java/comms/BufferedConnection.java +++ b/src/comms/java/comms/BufferedConnection.java @@ -32,16 +32,16 @@ import java.util.concurrent.LinkedBlockingQueue; * * @author leijurv */ -public class BufferedConnection implements IConnection { +public class BufferedConnection implements IConnection { private final IConnection wrapped; - private final LinkedBlockingQueue queue; + private final LinkedBlockingQueue queue; private volatile transient IOException thrownOnRead; - public BufferedConnection(IConnection wrapped) { + public BufferedConnection(IConnection wrapped) { this(wrapped, Integer.MAX_VALUE); // LinkedBlockingQueue accepts this as "no limit" } - public BufferedConnection(IConnection wrapped, int maxInternalQueueSize) { + public BufferedConnection(IConnection wrapped, int maxInternalQueueSize) { this.wrapped = wrapped; this.queue = new LinkedBlockingQueue<>(); this.thrownOnRead = null; @@ -59,12 +59,12 @@ public class BufferedConnection implements IConnection { } @Override - public void sendMessage(T message) throws IOException { + public void sendMessage(iMessage message) throws IOException { wrapped.sendMessage(message); } @Override - public T receiveMessage() { + public iMessage receiveMessage() { throw new UnsupportedOperationException("BufferedConnection can only be read from non-blockingly"); } @@ -74,8 +74,8 @@ public class BufferedConnection implements IConnection { thrownOnRead = new EOFException("Closed"); } - public List receiveMessagesNonBlocking() throws IOException { - ArrayList msgs = new ArrayList<>(); + 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); diff --git a/src/comms/java/comms/ConstructingDeserializer.java b/src/comms/java/comms/ConstructingDeserializer.java index 3879204a..c6407976 100644 --- a/src/comms/java/comms/ConstructingDeserializer.java +++ b/src/comms/java/comms/ConstructingDeserializer.java @@ -26,20 +26,20 @@ import java.util.List; public enum ConstructingDeserializer implements MessageDeserializer { INSTANCE; - private final List> MSGS; + 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]); + MSGS.add((Class) m.getParameterTypes()[0]); } } } @Override - public SerializableMessage deserialize(DataInputStream in) throws IOException { + public iMessage deserialize(DataInputStream in) throws IOException { int type = ((int) in.readByte()) & 0xff; try { return MSGS.get(type).getConstructor(DataInputStream.class).newInstance(in); @@ -48,7 +48,7 @@ public enum ConstructingDeserializer implements MessageDeserializer { } } - public byte getHeader(Class klass) { + public byte getHeader(Class klass) { return (byte) MSGS.indexOf(klass); } } diff --git a/src/comms/java/comms/FilteredConnection.java b/src/comms/java/comms/FilteredConnection.java deleted file mode 100644 index 2d740fcd..00000000 --- a/src/comms/java/comms/FilteredConnection.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package comms; - -import java.io.IOException; - -/** - * This is just a meme idk if this is actually useful - * - * @param - */ -public class FilteredConnection implements IConnection { - private final Class klass; - private final IConnection wrapped; - - public FilteredConnection(IConnection wrapped, Class klass) { - this.klass = klass; - this.wrapped = wrapped; - } - - @Override - public void sendMessage(T message) throws IOException { - wrapped.sendMessage(message); - } - - @Override - public T receiveMessage() throws IOException { - while (true) { - iMessage msg = wrapped.receiveMessage(); - if (klass.isInstance(msg)) { - return klass.cast(msg); - } - } - } - - @Override - public void close() { - wrapped.close(); - } -} diff --git a/src/comms/java/comms/HandlableMessage.java b/src/comms/java/comms/HandlableMessage.java deleted file mode 100644 index dce1d3de..00000000 --- a/src/comms/java/comms/HandlableMessage.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package comms; - -public interface HandlableMessage { - void handle(IMessageListener listener); -} diff --git a/src/comms/java/comms/IConnection.java b/src/comms/java/comms/IConnection.java index 05cef73d..dc54beb0 100644 --- a/src/comms/java/comms/IConnection.java +++ b/src/comms/java/comms/IConnection.java @@ -19,10 +19,10 @@ package comms; import java.io.IOException; -public interface IConnection { - void sendMessage(T message) throws IOException; +public interface IConnection { + void sendMessage(iMessage message) throws IOException; - T receiveMessage() throws IOException; + iMessage receiveMessage() throws IOException; void close(); } diff --git a/src/comms/java/comms/MessageDeserializer.java b/src/comms/java/comms/MessageDeserializer.java index ed18bf1a..aece828d 100644 --- a/src/comms/java/comms/MessageDeserializer.java +++ b/src/comms/java/comms/MessageDeserializer.java @@ -21,5 +21,5 @@ import java.io.DataInputStream; import java.io.IOException; public interface MessageDeserializer { - SerializableMessage deserialize(DataInputStream in) throws IOException; + iMessage deserialize(DataInputStream in) throws IOException; } diff --git a/src/comms/java/comms/Pipe.java b/src/comms/java/comms/Pipe.java index a8cad44f..c189af60 100644 --- a/src/comms/java/comms/Pipe.java +++ b/src/comms/java/comms/Pipe.java @@ -26,8 +26,8 @@ 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 LinkedBlockingQueue> AtoB; + private final LinkedBlockingQueue> BtoA; private final PipedConnection A; private final PipedConnection B; private volatile boolean closed; @@ -47,17 +47,17 @@ public class Pipe { return B; } - public class PipedConnection implements IConnection { - private final LinkedBlockingQueue> in; - private final LinkedBlockingQueue> out; + public class PipedConnection implements IConnection { + private final LinkedBlockingQueue> in; + private final LinkedBlockingQueue> out; - private PipedConnection(LinkedBlockingQueue> in, LinkedBlockingQueue> out) { + private PipedConnection(LinkedBlockingQueue> in, LinkedBlockingQueue> out) { this.in = in; this.out = out; } @Override - public void sendMessage(T message) throws IOException { + public void sendMessage(iMessage message) throws IOException { if (closed) { throw new EOFException("Closed"); } @@ -69,12 +69,12 @@ public class Pipe { } @Override - public T receiveMessage() throws IOException { + public iMessage receiveMessage() throws IOException { if (closed) { throw new EOFException("Closed"); } try { - Optional t = in.take(); + Optional t = in.take(); if (!t.isPresent()) { throw new EOFException("Closed"); } diff --git a/src/comms/java/comms/SerializableMessage.java b/src/comms/java/comms/SerializableMessage.java deleted file mode 100644 index 90187446..00000000 --- a/src/comms/java/comms/SerializableMessage.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * This file is part of Baritone. - * - * Baritone is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Baritone is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Baritone. If not, see . - */ - -package comms; - -import java.io.DataOutputStream; -import java.io.IOException; - -public interface SerializableMessage extends 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()); - } -} diff --git a/src/comms/java/comms/SerializedConnection.java b/src/comms/java/comms/SerializedConnection.java index 9e8af84c..0952854d 100644 --- a/src/comms/java/comms/SerializedConnection.java +++ b/src/comms/java/comms/SerializedConnection.java @@ -19,7 +19,7 @@ package comms; import java.io.*; -public class SerializedConnection implements IConnection { +public class SerializedConnection implements IConnection { private final DataInputStream in; private final DataOutputStream out; private final MessageDeserializer deserializer; @@ -35,13 +35,13 @@ public class SerializedConnection implements IConnection { } @Override - public void sendMessage(SerializableMessage message) throws IOException { + public void sendMessage(iMessage message) throws IOException { message.writeHeader(out); message.write(out); } @Override - public SerializableMessage receiveMessage() throws IOException { + public iMessage receiveMessage() throws IOException { return deserializer.deserialize(in); } diff --git a/src/comms/java/comms/downward/MessageChat.java b/src/comms/java/comms/downward/MessageChat.java index 35b63ee5..b04d2a31 100644 --- a/src/comms/java/comms/downward/MessageChat.java +++ b/src/comms/java/comms/downward/MessageChat.java @@ -17,15 +17,14 @@ package comms.downward; -import comms.HandlableMessage; import comms.IMessageListener; -import comms.SerializableMessage; +import comms.iMessage; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; -public class MessageChat implements SerializableMessage, HandlableMessage { +public class MessageChat implements iMessage { public final String msg; diff --git a/src/comms/java/comms/iMessage.java b/src/comms/java/comms/iMessage.java index 5a4ebd29..67ec2965 100644 --- a/src/comms/java/comms/iMessage.java +++ b/src/comms/java/comms/iMessage.java @@ -17,6 +17,9 @@ package comms; +import java.io.DataOutputStream; +import java.io.IOException; + /** * hell yeah *

@@ -27,4 +30,15 @@ package comms; * @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/MessageStatus.java b/src/comms/java/comms/upward/MessageStatus.java index fe0a6489..55a29828 100644 --- a/src/comms/java/comms/upward/MessageStatus.java +++ b/src/comms/java/comms/upward/MessageStatus.java @@ -17,15 +17,14 @@ package comms.upward; -import comms.HandlableMessage; import comms.IMessageListener; -import comms.SerializableMessage; +import comms.iMessage; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; -public class MessageStatus implements SerializableMessage, HandlableMessage { +public class MessageStatus implements iMessage { public final double x; public final double y; diff --git a/src/main/java/baritone/behavior/ControllerBehavior.java b/src/main/java/baritone/behavior/ControllerBehavior.java index 25a128a1..dd8594df 100644 --- a/src/main/java/baritone/behavior/ControllerBehavior.java +++ b/src/main/java/baritone/behavior/ControllerBehavior.java @@ -21,8 +21,11 @@ import baritone.Baritone; import baritone.api.event.events.ChatEvent; import baritone.api.event.events.TickEvent; import baritone.utils.Helper; -import comms.*; +import comms.BufferedConnection; +import comms.IConnection; +import comms.IMessageListener; import comms.downward.MessageChat; +import comms.iMessage; import comms.upward.MessageStatus; import java.io.IOException; @@ -33,7 +36,7 @@ public class ControllerBehavior extends Behavior implements IMessageListener { super(baritone); } - private BufferedConnection conn; + private BufferedConnection conn; @Override public void onTick(TickEvent event) { @@ -48,15 +51,15 @@ public class ControllerBehavior extends Behavior implements IMessageListener { return; } try { - List msgs = conn.receiveMessagesNonBlocking(); - msgs.forEach(msg -> ((HandlableMessage) msg).handle(this)); + List msgs = conn.receiveMessagesNonBlocking(); + msgs.forEach(msg -> msg.handle(this)); } catch (IOException e) { e.printStackTrace(); disconnect(); } } - public boolean trySend(SerializableMessage msg) { + public boolean trySend(iMessage msg) { if (conn == null) { return false; } From f99befd30703872a0e74983a7738ce25c7618f21 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 18 Nov 2018 12:04:37 -0800 Subject: [PATCH 48/77] oh thats important --- src/main/java/baritone/behavior/ControllerBehavior.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/behavior/ControllerBehavior.java b/src/main/java/baritone/behavior/ControllerBehavior.java index dd8594df..f1deb618 100644 --- a/src/main/java/baritone/behavior/ControllerBehavior.java +++ b/src/main/java/baritone/behavior/ControllerBehavior.java @@ -44,6 +44,7 @@ public class ControllerBehavior extends Behavior implements IMessageListener { return; } trySend(new MessageStatus(ctx.player().posX, ctx.player().posY, ctx.player().posZ)); + readAndHandle(); } private void readAndHandle() { From 4fb6c71174e49211d35c54df793819a04aa70d1c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 18 Nov 2018 17:32:16 -0800 Subject: [PATCH 49/77] lol --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 445d34bb..e458484a 100644 --- a/README.md +++ b/README.md @@ -58,8 +58,7 @@ 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 From 186652a8d8a213d6be2b10d8b6a20ee0f3839508 Mon Sep 17 00:00:00 2001 From: Brady Date: Sun, 18 Nov 2018 19:52:11 -0600 Subject: [PATCH 50/77] Protocol lol --- PROTOCOL.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 PROTOCOL.md 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 From 16e3fd93051484aa0ac1c2eff46ca1638d31a326 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 18 Nov 2018 21:41:42 -0800 Subject: [PATCH 51/77] IPathingControlManager --- .../pathing/calc/IPathingControlManager.java | 31 +++++++++++++++++++ .../baritone/utils/PathingControlManager.java | 24 +++++++++----- 2 files changed, 47 insertions(+), 8 deletions(-) create mode 100644 src/api/java/baritone/api/pathing/calc/IPathingControlManager.java 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/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index fa58a069..f5fff546 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -20,6 +20,7 @@ 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; @@ -27,13 +28,10 @@ import baritone.behavior.PathingBehavior; 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; @@ -54,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 @@ -69,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() { From 0dc67593bb97a052737b81e056499525f6f07824 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sun, 18 Nov 2018 21:56:46 -0800 Subject: [PATCH 52/77] lots more status --- src/api/java/baritone/api/IBaritone.java | 3 + .../java/comms/upward/MessageStatus.java | 58 ++++++++++++++++++- src/main/java/baritone/Baritone.java | 1 + .../baritone/behavior/ControllerBehavior.java | 26 ++++++++- 4 files changed, 86 insertions(+), 2 deletions(-) diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index 5ca54a25..14805375 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -22,6 +22,7 @@ import baritone.api.behavior.IMemoryBehavior; import baritone.api.behavior.IPathingBehavior; import baritone.api.cache.IWorldProvider; import baritone.api.event.listener.IEventBus; +import baritone.api.pathing.calc.IPathingControlManager; import baritone.api.process.ICustomGoalProcess; import baritone.api.process.IFollowProcess; import baritone.api.process.IGetToBlockProcess; @@ -59,6 +60,8 @@ public interface IBaritone { */ IMineProcess getMineProcess(); + IPathingControlManager getPathingControlManager(); + /** * @return The {@link IPathingBehavior} instance * @see IPathingBehavior diff --git a/src/comms/java/comms/upward/MessageStatus.java b/src/comms/java/comms/upward/MessageStatus.java index 55a29828..7a5e74af 100644 --- a/src/comms/java/comms/upward/MessageStatus.java +++ b/src/comms/java/comms/upward/MessageStatus.java @@ -29,17 +29,59 @@ 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 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.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) { + public MessageStatus(double x, double y, double z, float yaw, float pitch, boolean onGround, float health, float saturation, int foodLevel, 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.hasCurrentSegment = hasCurrentSegment; + this.hasNextSegment = hasNextSegment; + this.calcInProgress = calcInProgress; + this.ticksRemainingInCurrent = ticksRemainingInCurrent; + this.calcFailedLastTick = calcFailedLastTick; + this.safeToCancel = safeToCancel; + this.currentGoal = currentGoal; + this.currentProcess = currentProcess; } @Override @@ -47,6 +89,20 @@ public class MessageStatus implements iMessage { 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.writeBoolean(hasCurrentSegment); + out.writeBoolean(hasNextSegment); + out.writeBoolean(calcInProgress); + out.writeDouble(ticksRemainingInCurrent); + out.writeBoolean(calcFailedLastTick); + out.writeBoolean(safeToCancel); + out.writeUTF(currentGoal); + out.writeUTF(currentProcess); } @Override diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 0b42e112..7ee40e55 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -139,6 +139,7 @@ public class Baritone implements IBaritone { this.gameEventHandler.registerEventListener(behavior); } + @Override public PathingControlManager getPathingControlManager() { return this.pathingControlManager; } diff --git a/src/main/java/baritone/behavior/ControllerBehavior.java b/src/main/java/baritone/behavior/ControllerBehavior.java index f1deb618..3f8329bd 100644 --- a/src/main/java/baritone/behavior/ControllerBehavior.java +++ b/src/main/java/baritone/behavior/ControllerBehavior.java @@ -20,6 +20,7 @@ package baritone.behavior; import baritone.Baritone; import baritone.api.event.events.ChatEvent; import baritone.api.event.events.TickEvent; +import baritone.api.process.IBaritoneProcess; import baritone.utils.Helper; import comms.BufferedConnection; import comms.IConnection; @@ -43,10 +44,33 @@ public class ControllerBehavior extends Behavior implements IMessageListener { if (event.getType() == TickEvent.Type.OUT) { return; } - trySend(new MessageStatus(ctx.player().posX, ctx.player().posY, ctx.player().posZ)); + trySend(buildStatus()); readAndHandle(); } + public MessageStatus buildStatus() { + // TODO inventory + 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(), + 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; From d95a72f2cc3a525bccf6eb5e3c7ff669e8f86feb Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 19 Nov 2018 17:14:54 -0800 Subject: [PATCH 53/77] correct wording --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e458484a..9fa8a2c9 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAnd # 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) From e5184efdaa3b5b6d102765d1cba225bf6f91a3d9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 20 Nov 2018 08:00:11 -0800 Subject: [PATCH 54/77] fix cached path loop --- src/main/java/baritone/cache/ChunkPacker.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index 44153fdc..0627ebb4 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -124,7 +124,7 @@ public final class ChunkPacker { 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; } From 14650f93c5af19148bf41e962c50b8d27b646f7f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 20 Nov 2018 08:19:27 -0800 Subject: [PATCH 55/77] walk into lava less --- .../movement/movements/MovementDescend.java | 29 +++++++++++++++++++ .../baritone/pathing/path/PathExecutor.java | 14 +++------ 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index 05c140e4..ea7177b4 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -21,17 +21,22 @@ 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.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 { @@ -190,6 +195,18 @@ public class MovementDescend extends Movement { // System.out.println(player().posY + " " + playerFeet.getY() + " " + (player().posY - playerFeet.getY())); }*/ } + if (safeMode()) { + double destX = (src.getX() + 0.5) * 0.25 + (dest.getX() + 0.5) * 0.75; + double destZ = (src.getZ() + 0.5) * 0.25 + (dest.getZ() + 0.5) * 0.75; + 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); @@ -210,4 +227,16 @@ public class MovementDescend extends Movement { } 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/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index 5dfc420d..af0fe142 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -378,16 +378,10 @@ public class PathExecutor implements IPathExecutor, Helper { 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(ctx, into.up(y)))) { - logDebug("Sprinting would be unsafe"); - ctx.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); From 033da7e73770842cffdffbb7639bdcff64ae11c8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 20 Nov 2018 13:22:33 -0800 Subject: [PATCH 56/77] fix coefficient --- .../baritone/pathing/movement/movements/MovementDescend.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index ea7177b4..d868c5fc 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -196,8 +196,8 @@ public class MovementDescend extends Movement { }*/ } if (safeMode()) { - double destX = (src.getX() + 0.5) * 0.25 + (dest.getX() + 0.5) * 0.75; - double destZ = (src.getZ() + 0.5) * 0.25 + (dest.getZ() + 0.5) * 0.75; + 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), From 3bb16de67e3fef08aed510a6c03beabba1a2130d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 20 Nov 2018 16:32:44 -0800 Subject: [PATCH 57/77] greatly increase mining visual scan range --- src/main/java/baritone/process/MineProcess.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 204e11c5..a0495ade 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -205,7 +205,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro /*public static List searchWorld(List mining, int max, World world) { }*/ - public static List searchWorld(IPlayerContext ctx, List mining, int max, List alreadyKnown) { + public static List searchWorld(IPlayerContext ctx, List mining, int max, List alreadyKnown) { List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); //long b = System.currentTimeMillis(); @@ -232,15 +232,16 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro public void addNearby() { knownOreLocations.addAll(droppedItemsScan(mining, ctx.world())); BlockPos playerFeet = ctx.playerFeet(); - int searchDist = 4; // why four? idk + 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); // crucial to only add blocks we can see because otherwise this // is an x-ray and it'll get caught - if (mining.contains(BlockStateInterface.getBlock(ctx, pos)) && RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()).isPresent()) { - knownOreLocations.add(pos); + 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)); } } } From fb971301a423187259086b5bb26ad55422be5e49 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 20 Nov 2018 16:32:55 -0800 Subject: [PATCH 58/77] fix getting permanently stuck on sideways fence gates in our way --- src/main/java/baritone/pathing/movement/MovementHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 15d79040..72177669 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -200,7 +200,7 @@ public interface MovementHelper extends ActionCosts, Helper { 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) { From 2a674cb869b3bb47f3d08132c9c186a2ee573866 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 20 Nov 2018 18:58:41 -0800 Subject: [PATCH 59/77] don't sprint straight into danger --- .../pathing/movement/movements/MovementTraverse.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 2dc0e0cf..aa25b5b6 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -226,7 +226,10 @@ public class MovementTraverse extends Movement { if (ctx.playerFeet().equals(dest)) { return state.setStatus(MovementStatus.SUCCESS); } - if (wasTheBridgeBlockAlwaysThere && !MovementHelper.isLiquid(ctx, ctx.playerFeet())) { + 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(ctx, dest.down()).getBlock(); From cfa874982c855865475fab3e984b2e4caccf5519 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 21 Nov 2018 11:00:46 -0800 Subject: [PATCH 60/77] fix a bunch of stuff in pillar, fixes #266 --- .../baritone/pathing/movement/movements/MovementPillar.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 9c2c58e1..2898c426 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -194,12 +194,13 @@ public class MovementPillar extends Movement { } - state.setInput(Input.SNEAK, ctx.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.5D); // 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 = 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 @@ -209,7 +210,7 @@ public class MovementPillar extends Movement { // revise our target to both yaw and pitch if we're going to be moving forward state.setTarget(new MovementState.MovementTarget(rotation, true)); - } else { + } else if (flatMotion < 0.05) { // If our Y coordinate is above our goal, stop jumping state.setInput(Input.JUMP, ctx.player().posY < dest.getY()); } From 8db26af36cfb09dd577c7081aefc13d911a0802d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 21 Nov 2018 11:02:12 -0800 Subject: [PATCH 61/77] tweak sneak range for ncp compatibility --- .../baritone/pathing/movement/movements/MovementPillar.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 2898c426..78a62628 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -194,7 +194,7 @@ public class MovementPillar extends Movement { } - state.setInput(Input.SNEAK, ctx.player().posY > dest.getY() || ctx.player().posY < src.getY() + 0.5D); // 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 = ctx.player().posX - (dest.getX() + 0.5); From aed8dae175f298cfd588ee226494c9cf6912800c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 21 Nov 2018 17:03:24 -0800 Subject: [PATCH 62/77] hehe --- .../java/baritone/api/event/events/ChunkEvent.java | 11 ++++++++++- .../launch/mixins/MixinNetHandlerPlayClient.java | 5 +++-- src/main/java/baritone/event/GameEventHandler.java | 2 +- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/api/java/baritone/api/event/events/ChunkEvent.java b/src/api/java/baritone/api/event/events/ChunkEvent.java index 1541b1f1..a74bed17 100644 --- a/src/api/java/baritone/api/event/events/ChunkEvent.java +++ b/src/api/java/baritone/api/event/events/ChunkEvent.java @@ -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/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java b/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java index 9fc1bd6f..a716cb87 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java @@ -44,12 +44,13 @@ public class MixinNetHandlerPlayClient { ) ) private void preRead(SPacketChunkData packetIn, CallbackInfo ci) { + packetIn.isFullChunk(); for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) { ibaritone.getGameEventHandler().onChunkEvent( new ChunkEvent( EventState.PRE, - ChunkEvent.Type.POPULATE, + packetIn.isFullChunk() ? ChunkEvent.Type.POPULATE_FULL : ChunkEvent.Type.POPULATE_PARTIAL, packetIn.getChunkX(), packetIn.getChunkZ() ) @@ -68,7 +69,7 @@ public class MixinNetHandlerPlayClient { ibaritone.getGameEventHandler().onChunkEvent( new ChunkEvent( EventState.POST, - ChunkEvent.Type.POPULATE, + packetIn.isFullChunk() ? ChunkEvent.Type.POPULATE_FULL : ChunkEvent.Type.POPULATE_PARTIAL, packetIn.getChunkX(), packetIn.getChunkZ() ) diff --git a/src/main/java/baritone/event/GameEventHandler.java b/src/main/java/baritone/event/GameEventHandler.java index 7ac04643..9f16283e 100644 --- a/src/main/java/baritone/event/GameEventHandler.java +++ b/src/main/java/baritone/event/GameEventHandler.java @@ -70,7 +70,7 @@ public final class GameEventHandler implements IEventBus, 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(); From 4b8c85f8a630db97bc23c503fbbb38c6526bd407 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 22 Nov 2018 08:57:27 -0800 Subject: [PATCH 63/77] whoops --- .../java/baritone/launch/mixins/MixinNetHandlerPlayClient.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java b/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java index a716cb87..e2cc9842 100644 --- a/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java +++ b/src/launch/java/baritone/launch/mixins/MixinNetHandlerPlayClient.java @@ -44,7 +44,6 @@ public class MixinNetHandlerPlayClient { ) ) private void preRead(SPacketChunkData packetIn, CallbackInfo ci) { - packetIn.isFullChunk(); for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) { ibaritone.getGameEventHandler().onChunkEvent( From 1e9786d5b923bffd8f02ef1964a6672540183aed Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 22 Nov 2018 09:39:54 -0800 Subject: [PATCH 64/77] add a secondary failure cutoff --- src/api/java/baritone/api/Settings.java | 18 ++++++++++++---- .../api/pathing/calc/IPathFinder.java | 2 +- .../baritone/behavior/PathingBehavior.java | 16 +++++++++----- .../pathing/calc/AStarPathFinder.java | 21 ++++++++++++++----- .../pathing/calc/AbstractNodeCostSearch.java | 16 ++++++-------- 5 files changed, 48 insertions(+), 25 deletions(-) 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/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/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 1943b215..f2017eef 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -40,7 +40,10 @@ import baritone.utils.PathRenderer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; -import java.util.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Optional; import java.util.concurrent.LinkedBlockingQueue; import java.util.stream.Collectors; @@ -396,11 +399,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, logDebug("no goal"); // TODO should this be an exception too? definitely should be checked by caller return; } - long timeout; + long primaryTimeout; + long failureTimeout; if (current == null) { - timeout = Baritone.settings().pathTimeoutMS.get(); + primaryTimeout = Baritone.settings().primaryTimeoutMS.get(); + failureTimeout = Baritone.settings().failureTimeoutMS.get(); } else { - timeout = Baritone.settings().planAheadTimeoutMS.get(); + 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); @@ -410,7 +416,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, logDebug("Starting to search for path from " + start + " to " + goal); } - PathCalculationResult calcResult = pathfinder.calculate(timeout); + PathCalculationResult calcResult = pathfinder.calculate(primaryTimeout, failureTimeout); Optional path = calcResult.getPath(); if (Baritone.settings().cutoffAtLoadBoundary.get()) { path = path.map(p -> { diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index f6592094..aa83bc44 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -49,7 +49,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel } @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; @@ -68,10 +68,11 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel 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; @@ -79,7 +80,14 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel 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(); - 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 (failing == bestPathSoFar().isPresent()) { + throw new IllegalStateException(); + } if (slowPath) { try { Thread.sleep(Baritone.settings().slowPathTimeDelayMS.get()); @@ -166,6 +174,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 ac4efa4d..6d9ad67e 100644 --- a/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java +++ b/src/main/java/baritone/pathing/calc/AbstractNodeCostSearch.java @@ -83,13 +83,14 @@ 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 { - IPath path = calculate0(timeout).map(IPath::postProcess).orElse(null); + IPath path = calculate0(primaryTimeout, failureTimeout).map(IPath::postProcess).orElse(null); isFinished = true; if (cancelRequested) { return new PathCalculationResult(PathCalculationResult.Type.CANCELLATION, path); @@ -112,7 +113,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { } } - 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 @@ -157,7 +158,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder { @Override public Optional bestPathSoFar() { - if (startNode == null || bestSoFar == null || bestSoFar[0] == null) { + if (startNode == null || bestSoFar == null) { return Optional.empty(); } for (int i = 0; i < bestSoFar.length; i++) { @@ -165,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 From 7c51106d27c120db1f419a2a3437c3b89f412ac2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 22 Nov 2018 10:08:55 -0800 Subject: [PATCH 65/77] unneeded --- src/main/java/baritone/pathing/calc/AStarPathFinder.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/baritone/pathing/calc/AStarPathFinder.java b/src/main/java/baritone/pathing/calc/AStarPathFinder.java index aa83bc44..d0061921 100644 --- a/src/main/java/baritone/pathing/calc/AStarPathFinder.java +++ b/src/main/java/baritone/pathing/calc/AStarPathFinder.java @@ -85,9 +85,6 @@ public final class AStarPathFinder extends AbstractNodeCostSearch implements Hel if (now - failureTimeoutTime >= 0 || (!failing && now - primaryTimeoutTime >= 0)) { break; } - if (failing == bestPathSoFar().isPresent()) { - throw new IllegalStateException(); - } if (slowPath) { try { Thread.sleep(Baritone.settings().slowPathTimeDelayMS.get()); From b5a4e65fbf9cd05a54624cb7e46662a52808c92c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 07:47:28 -0800 Subject: [PATCH 66/77] unable to start a parkour jump from stairs --- src/main/java/baritone/pathing/movement/MovementHelper.java | 2 +- .../baritone/pathing/movement/movements/MovementParkour.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 72177669..ff73b0f2 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -274,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) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 44334569..9010251d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -33,6 +33,7 @@ import baritone.utils.BlockStateInterface; import baritone.utils.Helper; import baritone.utils.pathing.MutableMoveResult; import net.minecraft.block.Block; +import net.minecraft.block.BlockStairs; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; @@ -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(); From 0d7131413aaad269ca6dec5348f02e5df0bb3827 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 07:55:59 -0800 Subject: [PATCH 67/77] prevent double jumping --- .../baritone/pathing/movement/movements/MovementAscend.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 9c33742e..0baef881 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -211,6 +211,10 @@ 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(Input.JUMP, true); } From 70f8d1d4aeac648581b8afd8486bb30d8e875bd9 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 09:00:52 -0800 Subject: [PATCH 68/77] fix bsi creation on wrong thread, cache chunks, fixes #210 --- .../mixins/MixinChunkProviderClient.java | 39 +++++++ src/launch/resources/mixins.baritone.json | 1 + src/main/java/baritone/pathing/calc/Path.java | 2 +- .../java/baritone/pathing/movement/Moves.java | 107 +++++++++--------- .../movement/movements/MovementParkour.java | 6 +- .../baritone/process/GetToBlockProcess.java | 12 +- .../java/baritone/process/MineProcess.java | 38 ++++--- .../baritone/utils/BlockStateInterface.java | 19 ++++ .../utils/ExampleBaritoneControl.java | 3 +- .../utils/accessor/IChunkProviderClient.java | 25 ++++ 10 files changed, 172 insertions(+), 80 deletions(-) create mode 100644 src/launch/java/baritone/launch/mixins/MixinChunkProviderClient.java create mode 100644 src/main/java/baritone/utils/accessor/IChunkProviderClient.java 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/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/pathing/calc/Path.java b/src/main/java/baritone/pathing/calc/Path.java index ee3b182b..0b5b2cc7 100644 --- a/src/main/java/baritone/pathing/calc/Path.java +++ b/src/main/java/baritone/pathing/calc/Path.java @@ -129,7 +129,7 @@ class Path extends PathBase { private Movement runBackwards(BetterBlockPos src, BetterBlockPos dest, double cost) { for (Moves moves : Moves.values()) { - Movement move = moves.apply0(context.getBaritone(), src); + Movement move = moves.apply0(context, src); if (move.getDest().equals(dest)) { // have to calculate the cost at calculation time so we can accurately judge whether a cost increase happened between cached calculation and real execution move.override(cost); diff --git a/src/main/java/baritone/pathing/movement/Moves.java b/src/main/java/baritone/pathing/movement/Moves.java index ebb97081..c5a6ceb6 100644 --- a/src/main/java/baritone/pathing/movement/Moves.java +++ b/src/main/java/baritone/pathing/movement/Moves.java @@ -17,7 +17,6 @@ package baritone.pathing.movement; -import baritone.api.IBaritone; import baritone.api.utils.BetterBlockPos; import baritone.pathing.movement.movements.*; import baritone.utils.pathing.MutableMoveResult; @@ -31,8 +30,8 @@ import net.minecraft.util.EnumFacing; public enum Moves { DOWNWARD(0, -1, 0) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementDownward(baritone, src, src.down()); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementDownward(context.getBaritone(), src, src.down()); } @Override @@ -43,8 +42,8 @@ public enum Moves { PILLAR(0, +1, 0) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementPillar(baritone, src, src.up()); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementPillar(context.getBaritone(), src, src.up()); } @Override @@ -55,8 +54,8 @@ public enum Moves { TRAVERSE_NORTH(0, 0, -1) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementTraverse(baritone, src, src.north()); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementTraverse(context.getBaritone(), src, src.north()); } @Override @@ -67,8 +66,8 @@ public enum Moves { TRAVERSE_SOUTH(0, 0, +1) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementTraverse(baritone, src, src.south()); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementTraverse(context.getBaritone(), src, src.south()); } @Override @@ -79,8 +78,8 @@ public enum Moves { TRAVERSE_EAST(+1, 0, 0) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementTraverse(baritone, src, src.east()); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementTraverse(context.getBaritone(), src, src.east()); } @Override @@ -91,8 +90,8 @@ public enum Moves { TRAVERSE_WEST(-1, 0, 0) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementTraverse(baritone, src, src.west()); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementTraverse(context.getBaritone(), src, src.west()); } @Override @@ -103,8 +102,8 @@ public enum Moves { ASCEND_NORTH(0, +1, -1) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementAscend(baritone, src, new BetterBlockPos(src.x, src.y + 1, src.z - 1)); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementAscend(context.getBaritone(), src, new BetterBlockPos(src.x, src.y + 1, src.z - 1)); } @Override @@ -115,8 +114,8 @@ public enum Moves { ASCEND_SOUTH(0, +1, +1) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementAscend(baritone, src, new BetterBlockPos(src.x, src.y + 1, src.z + 1)); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementAscend(context.getBaritone(), src, new BetterBlockPos(src.x, src.y + 1, src.z + 1)); } @Override @@ -127,8 +126,8 @@ public enum Moves { ASCEND_EAST(+1, +1, 0) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementAscend(baritone, src, new BetterBlockPos(src.x + 1, src.y + 1, src.z)); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementAscend(context.getBaritone(), src, new BetterBlockPos(src.x + 1, src.y + 1, src.z)); } @Override @@ -139,8 +138,8 @@ public enum Moves { ASCEND_WEST(-1, +1, 0) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementAscend(baritone, src, new BetterBlockPos(src.x - 1, src.y + 1, src.z)); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementAscend(context.getBaritone(), src, new BetterBlockPos(src.x - 1, src.y + 1, src.z)); } @Override @@ -151,13 +150,13 @@ public enum Moves { DESCEND_EAST(+1, -1, 0, false, true) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(new CalculationContext(baritone), src.x, src.y, src.z, res); + apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { - return new MovementDescend(baritone, 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(baritone, src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementFall(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -169,13 +168,13 @@ public enum Moves { DESCEND_WEST(-1, -1, 0, false, true) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(new CalculationContext(baritone), src.x, src.y, src.z, res); + apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { - return new MovementDescend(baritone, 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(baritone, src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementFall(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -187,13 +186,13 @@ public enum Moves { DESCEND_NORTH(0, -1, -1, false, true) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(new CalculationContext(baritone), src.x, src.y, src.z, res); + apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { - return new MovementDescend(baritone, 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(baritone, src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementFall(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -205,13 +204,13 @@ public enum Moves { DESCEND_SOUTH(0, -1, +1, false, true) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { + public Movement apply0(CalculationContext context, BetterBlockPos src) { MutableMoveResult res = new MutableMoveResult(); - apply(new CalculationContext(baritone), src.x, src.y, src.z, res); + apply(context, src.x, src.y, src.z, res); if (res.y == src.y - 1) { - return new MovementDescend(baritone, 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(baritone, src, new BetterBlockPos(res.x, res.y, res.z)); + return new MovementFall(context.getBaritone(), src, new BetterBlockPos(res.x, res.y, res.z)); } } @@ -223,8 +222,8 @@ public enum Moves { DIAGONAL_NORTHEAST(+1, 0, -1) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementDiagonal(baritone, src, EnumFacing.NORTH, EnumFacing.EAST); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementDiagonal(context.getBaritone(), src, EnumFacing.NORTH, EnumFacing.EAST); } @Override @@ -235,8 +234,8 @@ public enum Moves { DIAGONAL_NORTHWEST(-1, 0, -1) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementDiagonal(baritone, src, EnumFacing.NORTH, EnumFacing.WEST); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementDiagonal(context.getBaritone(), src, EnumFacing.NORTH, EnumFacing.WEST); } @Override @@ -247,8 +246,8 @@ public enum Moves { DIAGONAL_SOUTHEAST(+1, 0, +1) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementDiagonal(baritone, src, EnumFacing.SOUTH, EnumFacing.EAST); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementDiagonal(context.getBaritone(), src, EnumFacing.SOUTH, EnumFacing.EAST); } @Override @@ -259,8 +258,8 @@ public enum Moves { DIAGONAL_SOUTHWEST(-1, 0, +1) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return new MovementDiagonal(baritone, src, EnumFacing.SOUTH, EnumFacing.WEST); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return new MovementDiagonal(context.getBaritone(), src, EnumFacing.SOUTH, EnumFacing.WEST); } @Override @@ -271,8 +270,8 @@ public enum Moves { PARKOUR_NORTH(0, 0, -4, true, false) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return MovementParkour.cost(baritone, src, EnumFacing.NORTH); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return MovementParkour.cost(context, src, EnumFacing.NORTH); } @Override @@ -283,8 +282,8 @@ public enum Moves { PARKOUR_SOUTH(0, 0, +4, true, false) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return MovementParkour.cost(baritone, src, EnumFacing.SOUTH); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return MovementParkour.cost(context, src, EnumFacing.SOUTH); } @Override @@ -295,8 +294,8 @@ public enum Moves { PARKOUR_EAST(+4, 0, 0, true, false) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return MovementParkour.cost(baritone, src, EnumFacing.EAST); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return MovementParkour.cost(context, src, EnumFacing.EAST); } @Override @@ -307,8 +306,8 @@ public enum Moves { PARKOUR_WEST(-4, 0, 0, true, false) { @Override - public Movement apply0(IBaritone baritone, BetterBlockPos src) { - return MovementParkour.cost(baritone, src, EnumFacing.WEST); + public Movement apply0(CalculationContext context, BetterBlockPos src) { + return MovementParkour.cost(context, src, EnumFacing.WEST); } @Override @@ -336,7 +335,7 @@ public enum Moves { this(x, y, z, false, false); } - public abstract Movement apply0(IBaritone baritone, BetterBlockPos src); + public abstract Movement apply0(CalculationContext context, BetterBlockPos src); public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { if (dynamicXZ || dynamicY) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 9010251d..80d6feb4 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -57,11 +57,11 @@ public class MovementParkour extends Movement { this.dist = dist; } - public static MovementParkour cost(IBaritone baritone, BetterBlockPos src, EnumFacing direction) { + public static MovementParkour cost(CalculationContext context, BetterBlockPos src, EnumFacing direction) { MutableMoveResult res = new MutableMoveResult(); - cost(new CalculationContext(baritone), src.x, src.y, src.z, direction, res); + 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(baritone, 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) { diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 5eefe6a9..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,7 +77,8 @@ 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(ctx.playerFeet())) { @@ -96,7 +98,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl return "Get To Block " + gettingTo; } - private void rescan(List known) { - knownLocations = MineProcess.searchWorld(ctx, Collections.singletonList(gettingTo), 64, 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 a0495ade..a59695c7 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -27,6 +27,7 @@ import baritone.api.utils.RotationUtils; import baritone.cache.CachedChunk; import baritone.cache.ChunkPacker; import baritone.cache.WorldScanner; +import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; @@ -88,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(); @@ -116,7 +118,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro private Goal updateGoal() { List locs = knownOreLocations; if (!locs.isEmpty()) { - List locs2 = prune(ctx, new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT); + 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(ctx, loc, locs2)).toArray(Goal[]::new)); knownOreLocations = locs2; @@ -151,14 +153,14 @@ 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(ctx, mining, ORE_LOCATIONS_COUNT, already); + 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"); @@ -205,13 +207,14 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro /*public static List searchWorld(List mining, int max, World world) { }*/ - public static List searchWorld(IPlayerContext ctx, List mining, int max, List alreadyKnown) { + public static List searchWorld(CalculationContext ctx, List mining, int max, List alreadyKnown) { + IPlayerContext ipc; 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(ctx.worldData().getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 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); } @@ -222,7 +225,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } if (!uninteresting.isEmpty()) { //long before = System.currentTimeMillis(); - locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx, 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); @@ -246,22 +249,22 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } } } - knownOreLocations = prune(ctx, knownOreLocations, mining, ORE_LOCATIONS_COUNT); + knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, mining, ORE_LOCATIONS_COUNT); } - public static List prune(IPlayerContext ctx, List locs2, List mining, int max) { + 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 -> ctx.world().getChunk(pos) instanceof EmptyChunk || mining.contains(BlockStateInterface.getBlock(ctx, pos)) || 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(pos -> MineProcess.plausibleToBreak(ctx, pos)) + .filter(pos -> MineProcess.plausibleToBreak(ctx.bsi(), pos)) - .sorted(Comparator.comparingDouble(ctx.playerFeet()::distanceSq)) + .sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().playerFeet()::distanceSq)) .collect(Collectors.toList()); if (locs.size() > max) { @@ -270,12 +273,13 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return locs; } - public static boolean plausibleToBreak(IPlayerContext ctx, BlockPos pos) { - if (MovementHelper.avoidBreaking(new BlockStateInterface(ctx), pos.getX(), pos.getY(), pos.getZ(), BlockStateInterface.get(ctx, 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(ctx, pos.up()) == Blocks.BEDROCK && BlockStateInterface.getBlock(ctx, pos.down()) == Blocks.BEDROCK); + return !(bsi.get0(pos.up()).getBlock() == Blocks.BEDROCK && bsi.get0(pos.down()).getBlock() == Blocks.BEDROCK); } @Override @@ -290,6 +294,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/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index 63ba8d83..9b6401e9 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -21,12 +21,17 @@ import baritone.Baritone; import baritone.api.utils.IPlayerContext; import baritone.cache.CachedRegion; import baritone.cache.WorldData; +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; +import net.minecraft.world.chunk.EmptyChunk; /** * Wraps get for chuck caching capability @@ -36,6 +41,7 @@ import net.minecraft.world.chunk.Chunk; public class BlockStateInterface { private final World world; + private final Long2ObjectMap loadedChunks; private final WorldData worldData; private Chunk prev = null; @@ -50,6 +56,10 @@ public class BlockStateInterface { 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 World getWorld() { @@ -66,6 +76,10 @@ public class BlockStateInterface { // 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(BlockPos pos) { + return get0(pos.getX(), pos.getY(), pos.getZ()); + } + public IBlockState get0(int x, int y, int z) { // Mickey resigned // Invalid vertical position @@ -84,7 +98,12 @@ public class BlockStateInterface { if (cached != null && cached.x == x >> 4 && cached.z == z >> 4) { return cached.getBlockState(x, y, z); } + Chunk c2 = loadedChunks.get(ChunkPos.asLong(x >> 4, z >> 4)); Chunk chunk = world.getChunk(x >> 4, z >> 4); + + if ((c2 != null && c2 != chunk) || (c2 == null && !(chunk instanceof EmptyChunk))) { + throw new IllegalStateException((((IChunkProviderClient) world.getChunkProvider()).loadedChunks() == loadedChunks) + " " + x + " " + y + " " + c2 + " " + chunk); + } if (chunk.isLoaded()) { prev = chunk; return chunk.getBlockState(x, y, z); diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 841349e4..93e2742a 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -28,6 +28,7 @@ import baritone.behavior.Behavior; import baritone.behavior.PathingBehavior; import baritone.cache.ChunkPacker; import baritone.cache.Waypoint; +import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.process.CustomGoalProcess; @@ -446,7 +447,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.equals("costs")) { - List moves = Stream.of(Moves.values()).map(x -> x.apply0(baritone, ctx.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); } 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(); +} From b228f4c6fb6d8a952634a5949dc3dba2145f5f75 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 09:03:51 -0800 Subject: [PATCH 69/77] remove extraneous checks in bsi --- .../pathing/movement/MovementHelper.java | 2 +- .../baritone/utils/BlockStateInterface.java | 19 ++++++------------- 2 files changed, 7 insertions(+), 14 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index ff73b0f2..917adc7c 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -86,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 (bsi.getWorld().getChunk(x >> 4, z >> 4) instanceof EmptyChunk) { + if (!bsi.worldContainsLoadedChunk(x, z)) { return true; } if (snow) { diff --git a/src/main/java/baritone/utils/BlockStateInterface.java b/src/main/java/baritone/utils/BlockStateInterface.java index 9b6401e9..b6b264d0 100644 --- a/src/main/java/baritone/utils/BlockStateInterface.java +++ b/src/main/java/baritone/utils/BlockStateInterface.java @@ -31,7 +31,6 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; -import net.minecraft.world.chunk.EmptyChunk; /** * Wraps get for chuck caching capability @@ -40,7 +39,6 @@ import net.minecraft.world.chunk.EmptyChunk; */ public class BlockStateInterface { - private final World world; private final Long2ObjectMap loadedChunks; private final WorldData worldData; @@ -55,15 +53,14 @@ public class BlockStateInterface { 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 World getWorld() { - return world; + public boolean worldContainsLoadedChunk(int blockX, int blockZ) { + return loadedChunks.containsKey(ChunkPos.asLong(blockX >> 4, blockZ >> 4)); } 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 @@ -98,13 +95,9 @@ public class BlockStateInterface { if (cached != null && cached.x == x >> 4 && cached.z == z >> 4) { return cached.getBlockState(x, y, z); } - Chunk c2 = loadedChunks.get(ChunkPos.asLong(x >> 4, z >> 4)); - Chunk chunk = world.getChunk(x >> 4, z >> 4); + Chunk chunk = loadedChunks.get(ChunkPos.asLong(x >> 4, z >> 4)); - if ((c2 != null && c2 != chunk) || (c2 == null && !(chunk instanceof EmptyChunk))) { - throw new IllegalStateException((((IChunkProviderClient) world.getChunkProvider()).loadedChunks() == loadedChunks) + " " + x + " " + y + " " + c2 + " " + chunk); - } - if (chunk.isLoaded()) { + if (chunk != null && chunk.isLoaded()) { prev = chunk; return chunk.getBlockState(x, y, z); } @@ -135,8 +128,8 @@ public class BlockStateInterface { 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; } From 6ed8d617cd01e2fcf97859ba4c5ef1ec14b675ba Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 09:31:25 -0800 Subject: [PATCH 70/77] improve path checks, and add a overlap splice option --- .../java/baritone/api/pathing/calc/IPath.java | 11 +++++-- .../baritone/pathing/path/PathExecutor.java | 2 +- .../baritone/pathing/path/SplicedPath.java | 29 ++++++++++++++----- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/api/java/baritone/api/pathing/calc/IPath.java b/src/api/java/baritone/api/pathing/calc/IPath.java index 0844ab90..133de5ef 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; /** @@ -153,9 +153,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 +164,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/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index af0fe142..171dd769 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -458,7 +458,7 @@ 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(); } 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())); } } From 81ecc209d382e0abeab7d62c90a324d9dcd9c214 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 10:09:13 -0800 Subject: [PATCH 71/77] synchronize partial reads and writes to a socket --- src/comms/java/comms/ConstructingDeserializer.java | 2 +- src/comms/java/comms/SerializedConnection.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/comms/java/comms/ConstructingDeserializer.java b/src/comms/java/comms/ConstructingDeserializer.java index c6407976..5b49ecdb 100644 --- a/src/comms/java/comms/ConstructingDeserializer.java +++ b/src/comms/java/comms/ConstructingDeserializer.java @@ -39,7 +39,7 @@ public enum ConstructingDeserializer implements MessageDeserializer { } @Override - public iMessage deserialize(DataInputStream in) throws IOException { + public synchronized iMessage deserialize(DataInputStream in) throws IOException { int type = ((int) in.readByte()) & 0xff; try { return MSGS.get(type).getConstructor(DataInputStream.class).newInstance(in); diff --git a/src/comms/java/comms/SerializedConnection.java b/src/comms/java/comms/SerializedConnection.java index 0952854d..c4191194 100644 --- a/src/comms/java/comms/SerializedConnection.java +++ b/src/comms/java/comms/SerializedConnection.java @@ -35,7 +35,7 @@ public class SerializedConnection implements IConnection { } @Override - public void sendMessage(iMessage message) throws IOException { + public synchronized void sendMessage(iMessage message) throws IOException { message.writeHeader(out); message.write(out); } From dd47e20070c1ada8ad5f48a58343a4456ce4d664 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 10:20:48 -0800 Subject: [PATCH 72/77] remove unneeded --- src/main/java/baritone/process/MineProcess.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index a59695c7..4ea75387 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -204,11 +204,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro return ret; } - /*public static List searchWorld(List mining, int max, World world) { - - }*/ public static List searchWorld(CalculationContext ctx, List mining, int max, List alreadyKnown) { - IPlayerContext ipc; List locs = new ArrayList<>(); List uninteresting = new ArrayList<>(); //long b = System.currentTimeMillis(); From 4502adda28b317f15bd8dad1b3584e43b3e4b402 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 10:36:06 -0800 Subject: [PATCH 73/77] segmented path calculator --- .../api/utils/PathCalculationResult.java | 3 + .../baritone/behavior/PathingBehavior.java | 11 ++- .../utils/pathing/SegmentedCalculator.java | 87 +++++++++++++++++++ 3 files changed, 95 insertions(+), 6 deletions(-) create mode 100644 src/main/java/baritone/utils/pathing/SegmentedCalculator.java diff --git a/src/api/java/baritone/api/utils/PathCalculationResult.java b/src/api/java/baritone/api/utils/PathCalculationResult.java index df009952..20aef9de 100644 --- a/src/api/java/baritone/api/utils/PathCalculationResult.java +++ b/src/api/java/baritone/api/utils/PathCalculationResult.java @@ -33,6 +33,9 @@ public class PathCalculationResult { public PathCalculationResult(Type type, IPath path) { this.path = path; this.type = type; + if (type == null) { + throw new IllegalArgumentException("come on"); + } } public final Optional getPath() { diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index f2017eef..42186b5b 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -40,10 +40,7 @@ import baritone.utils.PathRenderer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.EmptyChunk; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Optional; +import java.util.*; import java.util.concurrent.LinkedBlockingQueue; import java.util.stream.Collectors; @@ -410,6 +407,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } 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) { @@ -480,12 +480,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, }); } - private AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, IPath previous, CalculationContext context) { + 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"); transformed = new GoalXZ(pos.getX(), pos.getZ()); } } 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); + }); + } +} From c423d5f575bf06e2cb7599bb19808d45849b0c93 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 11:35:13 -0800 Subject: [PATCH 74/77] report path start position --- src/comms/java/comms/upward/MessageStatus.java | 14 +++++++++++++- .../java/baritone/behavior/ControllerBehavior.java | 8 +++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/comms/java/comms/upward/MessageStatus.java b/src/comms/java/comms/upward/MessageStatus.java index 7a5e74af..53786a01 100644 --- a/src/comms/java/comms/upward/MessageStatus.java +++ b/src/comms/java/comms/upward/MessageStatus.java @@ -35,6 +35,9 @@ public class MessageStatus implements iMessage { 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; @@ -54,6 +57,9 @@ public class MessageStatus implements iMessage { 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(); @@ -64,7 +70,7 @@ public class MessageStatus implements iMessage { this.currentProcess = in.readUTF(); } - public MessageStatus(double x, double y, double z, float yaw, float pitch, boolean onGround, float health, float saturation, int foodLevel, boolean hasCurrentSegment, boolean hasNextSegment, boolean calcInProgress, double ticksRemainingInCurrent, boolean calcFailedLastTick, boolean safeToCancel, String currentGoal, String currentProcess) { + 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; @@ -74,6 +80,9 @@ public class MessageStatus implements iMessage { 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; @@ -95,6 +104,9 @@ public class MessageStatus implements iMessage { 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); diff --git a/src/main/java/baritone/behavior/ControllerBehavior.java b/src/main/java/baritone/behavior/ControllerBehavior.java index 3f8329bd..736d6ac6 100644 --- a/src/main/java/baritone/behavior/ControllerBehavior.java +++ b/src/main/java/baritone/behavior/ControllerBehavior.java @@ -28,6 +28,7 @@ import comms.IMessageListener; import comms.downward.MessageChat; import comms.iMessage; import comms.upward.MessageStatus; +import net.minecraft.util.math.BlockPos; import java.io.IOException; import java.util.List; @@ -49,7 +50,9 @@ public class ControllerBehavior extends Behavior implements IMessageListener { } public MessageStatus buildStatus() { - // TODO inventory + // 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, @@ -60,6 +63,9 @@ public class ControllerBehavior extends Behavior implements IMessageListener { 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(), From 3a2620192b37bd4bb0f1a326818b6f4fe2433b6d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 11:46:47 -0800 Subject: [PATCH 75/77] too much log spam --- src/main/java/baritone/behavior/PathingBehavior.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 42186b5b..de973a5f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -358,7 +358,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } 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; } } @@ -367,7 +367,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // !onGround // we're in the middle of a jump if (MovementHelper.canWalkOn(ctx, feet.down().down())) { - logDebug("Faking path start assuming player is midair and falling"); + //logDebug("Faking path start assuming player is midair and falling"); return feet.down(); } } From fdd758bc90fd3fc93685e7782837e9591e217485 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 11:46:47 -0800 Subject: [PATCH 76/77] too much log spam --- src/main/java/baritone/behavior/PathingBehavior.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 42186b5b..de973a5f 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -358,7 +358,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } 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; } } @@ -367,7 +367,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // !onGround // we're in the middle of a jump if (MovementHelper.canWalkOn(ctx, feet.down().down())) { - logDebug("Faking path start assuming player is midair and falling"); + //logDebug("Faking path start assuming player is midair and falling"); return feet.down(); } } From e0d894d2964fe7c858eec6d03d505ff0c967c504 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 23 Nov 2018 12:09:35 -0800 Subject: [PATCH 77/77] computation request and response --- .../java/baritone/api/pathing/calc/IPath.java | 11 ++- src/comms/java/comms/IMessageListener.java | 10 +++ .../downward/MessageComputationRequest.java | 62 ++++++++++++++++ .../upward/MessageComputationResponse.java | 72 +++++++++++++++++++ .../baritone/behavior/ControllerBehavior.java | 40 +++++++++++ 5 files changed, 194 insertions(+), 1 deletion(-) create mode 100644 src/comms/java/comms/downward/MessageComputationRequest.java create mode 100644 src/comms/java/comms/upward/MessageComputationResponse.java diff --git a/src/api/java/baritone/api/pathing/calc/IPath.java b/src/api/java/baritone/api/pathing/calc/IPath.java index 133de5ef..c3f7fc14 100644 --- a/src/api/java/baritone/api/pathing/calc/IPath.java +++ b/src/api/java/baritone/api/pathing/calc/IPath.java @@ -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. diff --git a/src/comms/java/comms/IMessageListener.java b/src/comms/java/comms/IMessageListener.java index afed4cfe..94300f1f 100644 --- a/src/comms/java/comms/IMessageListener.java +++ b/src/comms/java/comms/IMessageListener.java @@ -18,6 +18,8 @@ package comms; import comms.downward.MessageChat; +import comms.downward.MessageComputationRequest; +import comms.upward.MessageComputationResponse; import comms.upward.MessageStatus; public interface IMessageListener { @@ -29,6 +31,14 @@ public interface IMessageListener { 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 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/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/main/java/baritone/behavior/ControllerBehavior.java b/src/main/java/baritone/behavior/ControllerBehavior.java index 736d6ac6..405ccc4d 100644 --- a/src/main/java/baritone/behavior/ControllerBehavior.java +++ b/src/main/java/baritone/behavior/ControllerBehavior.java @@ -20,20 +20,31 @@ 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); } @@ -126,6 +137,35 @@ public class ControllerBehavior extends Behavior implements IMessageListener { 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);