Merge branch 'master' into bot-system

This commit is contained in:
Leijurv
2018-11-14 16:41:52 -08:00
64 changed files with 549 additions and 467 deletions
+5 -51
View File
@@ -17,16 +17,6 @@
package baritone.api; 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 baritone.api.utils.SettingsUtil;
import java.util.Iterator; import java.util.Iterator;
@@ -42,59 +32,23 @@ import java.util.ServiceLoader;
*/ */
public final class BaritoneAPI { public final class BaritoneAPI {
private static final IBaritone baritone; private static final IBaritoneProvider provider;
private static final Settings settings; private static final Settings settings;
static { static {
ServiceLoader<IBaritoneProvider> baritoneLoader = ServiceLoader.load(IBaritoneProvider.class); ServiceLoader<IBaritoneProvider> baritoneLoader = ServiceLoader.load(IBaritoneProvider.class);
Iterator<IBaritoneProvider> instances = baritoneLoader.iterator(); Iterator<IBaritoneProvider> instances = baritoneLoader.iterator();
baritone = instances.next().getBaritoneForPlayer(null); // PWNAGE provider = instances.next();
settings = new Settings(); settings = new Settings();
SettingsUtil.readAndApply(settings); SettingsUtil.readAndApply(settings);
} }
public static IFollowProcess getFollowProcess() { public static IBaritoneProvider getProvider() {
return baritone.getFollowProcess(); return BaritoneAPI.provider;
}
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 Settings getSettings() { public static Settings getSettings() {
return settings; return BaritoneAPI.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);
} }
} }
+2 -14
View File
@@ -21,8 +21,7 @@ import baritone.api.behavior.ILookBehavior;
import baritone.api.behavior.IMemoryBehavior; import baritone.api.behavior.IMemoryBehavior;
import baritone.api.behavior.IPathingBehavior; import baritone.api.behavior.IPathingBehavior;
import baritone.api.cache.IWorldProvider; import baritone.api.cache.IWorldProvider;
import baritone.api.cache.IWorldScanner; import baritone.api.event.listener.IEventBus;
import baritone.api.event.listener.IGameEventListener;
import baritone.api.process.ICustomGoalProcess; import baritone.api.process.ICustomGoalProcess;
import baritone.api.process.IFollowProcess; import baritone.api.process.IFollowProcess;
import baritone.api.process.IGetToBlockProcess; import baritone.api.process.IGetToBlockProcess;
@@ -72,12 +71,6 @@ public interface IBaritone {
*/ */
IWorldProvider getWorldProvider(); IWorldProvider getWorldProvider();
/**
* @return The {@link IWorldScanner} instance
* @see IWorldScanner
*/
IWorldScanner getWorldScanner();
IInputOverrideHandler getInputOverrideHandler(); IInputOverrideHandler getInputOverrideHandler();
ICustomGoalProcess getCustomGoalProcess(); ICustomGoalProcess getCustomGoalProcess();
@@ -86,10 +79,5 @@ public interface IBaritone {
IPlayerContext getPlayerContext(); IPlayerContext getPlayerContext();
/** IEventBus getGameEventHandler();
* Registers a {@link IGameEventListener} with Baritone's "event bus".
*
* @param listener The listener
*/
void registerEventListener(IGameEventListener listener);
} }
@@ -17,13 +17,34 @@
package baritone.api; package baritone.api;
import baritone.api.cache.IWorldScanner;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import java.util.List;
/** /**
* @author Leijurv * @author Leijurv
*/ */
public interface IBaritoneProvider { public interface IBaritoneProvider {
/**
* Returns the primary {@link IBaritone} instance. This instance is persistent, and
* is represented by the local player that is created by the game itself, not a "bot"
* player through Baritone.
*
* @return The primary {@link IBaritone} instance.
*/
IBaritone getPrimaryBaritone();
/**
* Returns all of the active {@link IBaritone} instances. This includes the local one
* returned by {@link #getPrimaryBaritone()}.
*
* @return All active {@link IBaritone} instances.
* @see #getBaritoneForPlayer(EntityPlayerSP)
*/
List<IBaritone> getAllBaritones();
/** /**
* Provides the {@link IBaritone} instance for a given {@link EntityPlayerSP}. This will likely be * 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. * replaced with {@code #getBaritoneForUser(IBaritoneUser)} when {@code bot-system} is merged.
@@ -31,5 +52,20 @@ public interface IBaritoneProvider {
* @param player The player * @param player The player
* @return The {@link IBaritone} instance. * @return The {@link IBaritone} instance.
*/ */
IBaritone getBaritoneForPlayer(EntityPlayerSP player); default IBaritone getBaritoneForPlayer(EntityPlayerSP player) {
for (IBaritone baritone : getAllBaritones()) {
if (player.equals(baritone.getPlayerContext().player())) {
return baritone;
}
}
throw new IllegalStateException("No baritone for player " + player);
}
/**
* Returns the {@link IWorldScanner} instance. This is not a type returned by
* {@link IBaritone} implementation, because it is not linked with {@link IBaritone}.
*
* @return The {@link IWorldScanner} instance.
*/
IWorldScanner getWorldScanner();
} }
@@ -71,7 +71,7 @@ public interface IPathingBehavior extends IBehavior {
/** /**
* @return The current path finder being executed * @return The current path finder being executed
*/ */
Optional<IPathFinder> getPathFinder(); Optional<? extends IPathFinder> getInProgress();
/** /**
* @return The current path executor * @return The current path executor
+1 -1
View File
@@ -22,7 +22,7 @@ import net.minecraft.util.math.BlockPos;
/** /**
* @author Brady * @author Brady
* @since 8/4/2018 2:01 AM * @since 8/4/2018
*/ */
public interface IBlockTypeAccess { public interface IBlockTypeAccess {
@@ -22,7 +22,7 @@ import net.minecraft.client.entity.EntityPlayerSP;
/** /**
* @author Brady * @author Brady
* @since 8/1/2018 6:39 PM * @since 8/1/2018
*/ */
public final class ChatEvent extends ManagedPlayerEvent.Cancellable { public final class ChatEvent extends ManagedPlayerEvent.Cancellable {
@@ -21,7 +21,7 @@ import baritone.api.event.events.type.EventState;
/** /**
* @author Brady * @author Brady
* @since 8/2/2018 12:32 AM * @since 8/2/2018
*/ */
public final class ChunkEvent { public final class ChunkEvent {
@@ -23,7 +23,7 @@ import net.minecraft.network.Packet;
/** /**
* @author Brady * @author Brady
* @since 8/6/2018 9:31 PM * @since 8/6/2018
*/ */
public final class PacketEvent { public final class PacketEvent {
@@ -19,7 +19,7 @@ package baritone.api.event.events;
/** /**
* @author Brady * @author Brady
* @since 8/5/2018 12:28 AM * @since 8/5/2018
*/ */
public final class RenderEvent { public final class RenderEvent {
@@ -22,7 +22,7 @@ import net.minecraft.client.multiplayer.WorldClient;
/** /**
* @author Brady * @author Brady
* @since 8/4/2018 3:13 AM * @since 8/4/2018
*/ */
public final class WorldEvent { public final class WorldEvent {
@@ -19,7 +19,7 @@ package baritone.api.event.events.type;
/** /**
* @author Brady * @author Brady
* @since 8/1/2018 6:41 PM * @since 8/1/2018
*/ */
public class Cancellable implements ICancellable { public class Cancellable implements ICancellable {
@@ -19,7 +19,7 @@ package baritone.api.event.events.type;
/** /**
* @author Brady * @author Brady
* @since 8/2/2018 12:34 AM * @since 8/2/2018
*/ */
public enum EventState { public enum EventState {
@@ -26,7 +26,7 @@ import baritone.api.event.events.*;
* *
* @author Brady * @author Brady
* @see IGameEventListener * @see IGameEventListener
* @since 8/1/2018 6:29 PM * @since 8/1/2018
*/ */
public interface AbstractGameEventListener extends IGameEventListener { public interface AbstractGameEventListener extends IGameEventListener {
@@ -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 <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.listener;
/**
* A type of {@link IGameEventListener} that can have additional listeners
* registered so that they receive the events that are dispatched to this
* listener.
*
* @author Brady
* @since 11/14/2018
*/
public interface IEventBus extends IGameEventListener {
/**
* Registers the specified {@link IGameEventListener} to this event bus
*
* @param listener The listener
*/
void registerEventListener(IGameEventListener listener);
}
@@ -33,7 +33,7 @@ import net.minecraft.util.text.ITextComponent;
/** /**
* @author Brady * @author Brady
* @since 7/31/2018 11:05 PM * @since 7/31/2018
*/ */
public interface IGameEventListener { public interface IGameEventListener {
@@ -18,7 +18,6 @@
package baritone.api.pathing.movement; package baritone.api.pathing.movement;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.IPlayerContext;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import java.util.List; import java.util.List;
@@ -21,9 +21,14 @@ import baritone.api.cache.IWorldData;
import net.minecraft.block.BlockSlab; import net.minecraft.block.BlockSlab;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.multiplayer.PlayerControllerMP; 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.util.math.Vec3d;
import net.minecraft.world.World; import net.minecraft.world.World;
import java.util.Optional;
/** /**
* @author Brady * @author Brady
* @since 11/12/2018 * @since 11/12/2018
@@ -38,6 +43,8 @@ public interface IPlayerContext {
IWorldData worldData(); IWorldData worldData();
RayTraceResult objectMouseOver();
default BetterBlockPos playerFeet() { default BetterBlockPos playerFeet() {
// TODO find a better way to deal with soul sand!!!!! // TODO find a better way to deal with soul sand!!!!!
BetterBlockPos feet = new BetterBlockPos(player().posX, player().posY + 0.1251, player().posZ); BetterBlockPos feet = new BetterBlockPos(player().posX, player().posY + 0.1251, player().posZ);
@@ -58,4 +65,28 @@ public interface IPlayerContext {
default Rotation playerRotations() { default Rotation playerRotations() {
return new Rotation(player().rotationYaw, player().rotationPitch); return new Rotation(player().rotationYaw, player().rotationPitch);
} }
/**
* Returns the block that the crosshair is currently placed over. Updated once per tick.
*
* @return The position of the highlighted block
*/
default Optional<BlockPos> getSelectedBlock() {
if (objectMouseOver() != null && objectMouseOver().typeOfHit == RayTraceResult.Type.BLOCK) {
return Optional.of(objectMouseOver().getBlockPos());
}
return Optional.empty();
}
/**
* Returns the entity that the crosshair is currently placed over. Updated once per tick.
*
* @return The entity
*/
default Optional<Entity> getSelectedEntity() {
if (objectMouseOver() != null && objectMouseOver().typeOfHit == RayTraceResult.Type.ENTITY) {
return Optional.of(objectMouseOver().entityHit);
}
return Optional.empty();
}
} }
@@ -17,22 +17,16 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import java.util.Optional;
/** /**
* @author Brady * @author Brady
* @since 8/25/2018 * @since 8/25/2018
*/ */
public final class RayTraceUtils { public final class RayTraceUtils {
private static final Minecraft mc = Minecraft.getMinecraft();
private RayTraceUtils() {} private RayTraceUtils() {}
/** /**
@@ -51,30 +45,6 @@ public final class RayTraceUtils {
direction.y * blockReachDistance, direction.y * blockReachDistance,
direction.z * blockReachDistance direction.z * blockReachDistance
); );
return mc.world.rayTraceBlocks(start, end, false, false, true); 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<BlockPos> getSelectedBlock() {
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) {
return Optional.of(mc.objectMouseOver.getBlockPos());
}
return Optional.empty();
}
/**
* Returns the entity that the crosshair is currently placed over. Updated once per render tick.
*
* @return The entity
*/
public static Optional<Entity> getSelectedEntity() {
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.ENTITY) {
return Optional.of(mc.objectMouseOver.entityHit);
}
return Optional.empty();
} }
} }
@@ -17,8 +17,11 @@
package baritone.api.utils; package baritone.api.utils;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import net.minecraft.block.BlockFire; import net.minecraft.block.BlockFire;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.math.*; import net.minecraft.util.math.*;
@@ -135,8 +138,9 @@ public final class RotationUtils {
* @param pos The target block position * @param pos The target block position
* @return The optional rotation * @return The optional rotation
*/ */
public static Optional<Rotation> reachable(Entity entity, BlockPos pos, double blockReachDistance) { public static Optional<Rotation> reachable(EntityPlayerSP entity, BlockPos pos, double blockReachDistance) {
if (pos.equals(RayTraceUtils.getSelectedBlock().orElse(null))) { IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(entity);
if (pos.equals(baritone.getPlayerContext().getSelectedBlock().orElse(null))) {
/* /*
* why add 0.0001? * why add 0.0001?
* to indicate that we actually have a desired pitch * to indicate that we actually have a desired pitch
@@ -203,6 +207,6 @@ public final class RotationUtils {
* @return The optional rotation * @return The optional rotation
*/ */
public static Optional<Rotation> reachableCenter(Entity entity, BlockPos pos, double blockReachDistance) { public static Optional<Rotation> 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);
} }
} }
@@ -19,21 +19,17 @@ package baritone.api.utils;
import net.minecraft.block.BlockFire; import net.minecraft.block.BlockFire;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
/** /**
* @author Brady * @author Brady
* @since 10/13/2018 * @since 10/13/2018
*/ */
public final class VecUtils { public final class VecUtils {
/**
* The {@link Minecraft} instance
*/
private static final Minecraft mc = Minecraft.getMinecraft();
private VecUtils() {} private VecUtils() {}
@@ -44,9 +40,9 @@ public final class VecUtils {
* @return The center of the block's bounding box * @return The center of the block's bounding box
* @see #getBlockPosCenter(BlockPos) * @see #getBlockPosCenter(BlockPos)
*/ */
public static Vec3d calculateBlockCenter(BlockPos pos) { public static Vec3d calculateBlockCenter(World world, BlockPos pos) {
IBlockState b = mc.world.getBlockState(pos); IBlockState b = world.getBlockState(pos);
AxisAlignedBB bbox = b.getBoundingBox(mc.world, pos); AxisAlignedBB bbox = b.getBoundingBox(world, pos);
double xDiff = (bbox.minX + bbox.maxX) / 2; double xDiff = (bbox.minX + bbox.maxX) / 2;
double yDiff = (bbox.minY + bbox.maxY) / 2; double yDiff = (bbox.minY + bbox.maxY) / 2;
double zDiff = (bbox.minZ + bbox.maxZ) / 2; double zDiff = (bbox.minZ + bbox.maxZ) / 2;
@@ -68,7 +64,7 @@ public final class VecUtils {
* *
* @param pos The block position * @param pos The block position
* @return The assumed center of the position * @return The assumed center of the position
* @see #calculateBlockCenter(BlockPos) * @see #calculateBlockCenter(World, BlockPos)
*/ */
public static Vec3d getBlockPosCenter(BlockPos pos) { public static Vec3d getBlockPosCenter(BlockPos pos) {
return new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5); return new Vec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5);
@@ -29,7 +29,7 @@ import java.util.List;
/** /**
* @author Brady * @author Brady
* @since 7/31/2018 9:59 PM * @since 7/31/2018
*/ */
public class BaritoneTweaker extends SimpleTweaker { public class BaritoneTweaker extends SimpleTweaker {
@@ -17,7 +17,7 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.Baritone; import baritone.api.BaritoneAPI;
import baritone.api.event.events.RotationMoveEvent; import baritone.api.event.events.RotationMoveEvent;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
@@ -53,7 +53,7 @@ public class MixinEntity {
// noinspection ConstantConditions // noinspection ConstantConditions
if (EntityPlayerSP.class.isInstance(this)) { if (EntityPlayerSP.class.isInstance(this)) {
this.motionUpdateRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw); this.motionUpdateRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw);
Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(this.motionUpdateRotationEvent); BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.motionUpdateRotationEvent);
} }
} }
@@ -17,7 +17,7 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.Baritone; import baritone.api.BaritoneAPI;
import baritone.api.event.events.RotationMoveEvent; import baritone.api.event.events.RotationMoveEvent;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
@@ -56,7 +56,7 @@ public abstract class MixinEntityLivingBase extends Entity {
// noinspection ConstantConditions // noinspection ConstantConditions
if (EntityPlayerSP.class.isInstance(this)) { if (EntityPlayerSP.class.isInstance(this)) {
this.jumpRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.JUMP, this.rotationYaw); this.jumpRotationEvent = new RotationMoveEvent((EntityPlayerSP) (Object) this, RotationMoveEvent.Type.JUMP, this.rotationYaw);
Baritone.INSTANCE.getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent); BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent);
} }
} }
@@ -17,11 +17,11 @@
package baritone.launch.mixins; 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.ChatEvent;
import baritone.api.event.events.PlayerUpdateEvent; import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import baritone.behavior.PathingBehavior;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.player.PlayerCapabilities; import net.minecraft.entity.player.PlayerCapabilities;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
@@ -32,7 +32,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/** /**
* @author Brady * @author Brady
* @since 8/1/2018 5:06 PM * @since 8/1/2018
*/ */
@Mixin(EntityPlayerSP.class) @Mixin(EntityPlayerSP.class)
public class MixinEntityPlayerSP { public class MixinEntityPlayerSP {
@@ -44,7 +44,7 @@ public class MixinEntityPlayerSP {
) )
private void sendChatMessage(String msg, CallbackInfo ci) { private void sendChatMessage(String msg, CallbackInfo ci) {
ChatEvent event = new ChatEvent((EntityPlayerSP) (Object) this, msg); ChatEvent event = new ChatEvent((EntityPlayerSP) (Object) this, msg);
Baritone.INSTANCE.getGameEventHandler().onSendChatMessage(event); BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onSendChatMessage(event);
if (event.isCancelled()) { if (event.isCancelled()) {
ci.cancel(); ci.cancel();
} }
@@ -60,7 +60,7 @@ public class MixinEntityPlayerSP {
) )
) )
private void onPreUpdate(CallbackInfo ci) { private void onPreUpdate(CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.PRE)); BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.PRE));
} }
@Inject( @Inject(
@@ -73,7 +73,7 @@ public class MixinEntityPlayerSP {
) )
) )
private void onPostUpdate(CallbackInfo ci) { private void onPostUpdate(CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST)); BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent((EntityPlayerSP) (Object) this, EventState.POST));
} }
@Redirect( @Redirect(
@@ -84,7 +84,7 @@ public class MixinEntityPlayerSP {
) )
) )
private boolean isAllowFlying(PlayerCapabilities capabilities) { private boolean isAllowFlying(PlayerCapabilities capabilities) {
PathingBehavior pathingBehavior = Baritone.INSTANCE.getPathingBehavior(); IPathingBehavior pathingBehavior = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getPathingBehavior();
return !pathingBehavior.isPathing() && capabilities.allowFlying; return !pathingBehavior.isPathing() && capabilities.allowFlying;
} }
} }
@@ -17,7 +17,8 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.Baritone; import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.RenderEvent; import baritone.api.event.events.RenderEvent;
import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.EntityRenderer;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
@@ -37,6 +38,8 @@ public class MixinEntityRenderer {
) )
) )
private void renderWorldPass(int pass, float partialTicks, long finishTimeNano, CallbackInfo ci) { private void renderWorldPass(int pass, float partialTicks, long finishTimeNano, CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks)); for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks));
}
} }
} }
@@ -17,7 +17,7 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.Baritone; import baritone.api.BaritoneAPI;
import net.minecraft.client.settings.KeyBinding; import net.minecraft.client.settings.KeyBinding;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
@@ -26,7 +26,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
/** /**
* @author Brady * @author Brady
* @since 7/31/2018 11:44 PM * @since 7/31/2018
*/ */
@Mixin(KeyBinding.class) @Mixin(KeyBinding.class)
public class MixinKeyBinding { public class MixinKeyBinding {
@@ -37,7 +37,8 @@ public class MixinKeyBinding {
cancellable = true cancellable = true
) )
private void isKeyDown(CallbackInfoReturnable<Boolean> cir) { private void isKeyDown(CallbackInfoReturnable<Boolean> 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); cir.setReturnValue(true);
} }
} }
@@ -18,6 +18,8 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.BlockInteractEvent; import baritone.api.event.events.BlockInteractEvent;
import baritone.api.event.events.TickEvent; import baritone.api.event.events.TickEvent;
import baritone.api.event.events.WorldEvent; import baritone.api.event.events.WorldEvent;
@@ -42,7 +44,7 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
/** /**
* @author Brady * @author Brady
* @since 7/31/2018 10:51 PM * @since 7/31/2018
*/ */
@Mixin(Minecraft.class) @Mixin(Minecraft.class)
public class MixinMinecraft { public class MixinMinecraft {
@@ -57,7 +59,7 @@ public class MixinMinecraft {
at = @At("RETURN") at = @At("RETURN")
) )
private void postInit(CallbackInfo ci) { private void postInit(CallbackInfo ci) {
Baritone.INSTANCE.init(); ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).init();
} }
@Inject( @Inject(
@@ -83,12 +85,15 @@ public class MixinMinecraft {
) )
) )
private void runTick(CallbackInfo ci) { private void runTick(CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onTick(new TickEvent( for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
EventState.PRE,
(player != null && world != null) TickEvent.Type type = ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().world() != null
? TickEvent.Type.IN ? TickEvent.Type.IN
: TickEvent.Type.OUT : TickEvent.Type.OUT;
));
ibaritone.getGameEventHandler().onTick(new TickEvent(EventState.PRE, type));
}
} }
@Inject( @Inject(
@@ -96,7 +101,8 @@ public class MixinMinecraft {
at = @At("HEAD") at = @At("HEAD")
) )
private void runTickKeyboard(CallbackInfo ci) { private void runTickKeyboard(CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onProcessKeyBinds(); // keyboard input is only the primary baritone
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onProcessKeyBinds();
} }
@Inject( @Inject(
@@ -109,7 +115,9 @@ public class MixinMinecraft {
return; return;
} }
Baritone.INSTANCE.getGameEventHandler().onWorldEvent( // mc.world changing is only the primary baritone
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onWorldEvent(
new WorldEvent( new WorldEvent(
world, world,
EventState.PRE EventState.PRE
@@ -124,7 +132,8 @@ public class MixinMinecraft {
private void postLoadWorld(WorldClient world, String loadingMessage, CallbackInfo ci) { 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 // still fire event for both null, as that means we've just finished exiting a world
Baritone.INSTANCE.getGameEventHandler().onWorldEvent( // mc.world changing is only the primary baritone
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onWorldEvent(
new WorldEvent( new WorldEvent(
world, world,
EventState.POST EventState.POST
@@ -141,7 +150,8 @@ public class MixinMinecraft {
) )
) )
private boolean isAllowUserInput(GuiScreen screen) { 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( @Inject(
@@ -153,7 +163,8 @@ public class MixinMinecraft {
locals = LocalCapture.CAPTURE_FAILHARD locals = LocalCapture.CAPTURE_FAILHARD
) )
private void onBlockBreak(CallbackInfo ci, BlockPos pos) { private void onBlockBreak(CallbackInfo ci, BlockPos pos) {
Baritone.INSTANCE.getGameEventHandler().onBlockInteract(new BlockInteractEvent(pos, BlockInteractEvent.Type.BREAK)); // clickMouse is only for the main player
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(pos, BlockInteractEvent.Type.BREAK));
} }
@Inject( @Inject(
@@ -165,6 +176,7 @@ public class MixinMinecraft {
locals = LocalCapture.CAPTURE_FAILHARD 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) { private void onBlockUse(CallbackInfo ci, EnumHand var1[], int var2, int var3, EnumHand enumhand, ItemStack itemstack, BlockPos blockpos, int i, EnumActionResult enumactionresult) {
Baritone.INSTANCE.getGameEventHandler().onBlockInteract(new BlockInteractEvent(blockpos, BlockInteractEvent.Type.USE)); // rightClickMouse is only for the main player
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(blockpos, BlockInteractEvent.Type.USE));
} }
} }
@@ -17,7 +17,8 @@
package baritone.launch.mixins; 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.ChunkEvent;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.client.network.NetHandlerPlayClient;
@@ -30,7 +31,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/** /**
* @author Brady * @author Brady
* @since 8/3/2018 12:54 AM * @since 8/3/2018
*/ */
@Mixin(NetHandlerPlayClient.class) @Mixin(NetHandlerPlayClient.class)
public class MixinNetHandlerPlayClient { public class MixinNetHandlerPlayClient {
@@ -43,14 +44,18 @@ public class MixinNetHandlerPlayClient {
) )
) )
private void preRead(SPacketChunkData packetIn, CallbackInfo ci) { private void preRead(SPacketChunkData packetIn, CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onChunkEvent( for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
new ChunkEvent( if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) {
EventState.PRE, ibaritone.getGameEventHandler().onChunkEvent(
ChunkEvent.Type.POPULATE, new ChunkEvent(
packetIn.getChunkX(), EventState.PRE,
packetIn.getChunkZ() ChunkEvent.Type.POPULATE,
) packetIn.getChunkX(),
); packetIn.getChunkZ()
)
);
}
}
} }
@Inject( @Inject(
@@ -58,14 +63,18 @@ public class MixinNetHandlerPlayClient {
at = @At("RETURN") at = @At("RETURN")
) )
private void postHandleChunkData(SPacketChunkData packetIn, CallbackInfo ci) { private void postHandleChunkData(SPacketChunkData packetIn, CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onChunkEvent( for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
new ChunkEvent( if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) {
EventState.POST, ibaritone.getGameEventHandler().onChunkEvent(
ChunkEvent.Type.POPULATE, new ChunkEvent(
packetIn.getChunkX(), EventState.POST,
packetIn.getChunkZ() ChunkEvent.Type.POPULATE,
) packetIn.getChunkX(),
); packetIn.getChunkZ()
)
);
}
}
} }
@Inject( @Inject(
@@ -76,6 +85,10 @@ public class MixinNetHandlerPlayClient {
) )
) )
private void onPlayerDeath(SPacketCombatEvent packetIn, CallbackInfo ci) { private void onPlayerDeath(SPacketCombatEvent packetIn, CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onPlayerDeath(); for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) {
ibaritone.getGameEventHandler().onPlayerDeath();
}
}
} }
} }
@@ -17,7 +17,8 @@
package baritone.launch.mixins; 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.PacketEvent;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import io.netty.channel.Channel; import io.netty.channel.Channel;
@@ -36,7 +37,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/** /**
* @author Brady * @author Brady
* @since 8/6/2018 9:30 PM * @since 8/6/2018
*/ */
@Mixin(NetworkManager.class) @Mixin(NetworkManager.class)
public class MixinNetworkManager { public class MixinNetworkManager {
@@ -53,8 +54,14 @@ public class MixinNetworkManager {
at = @At("HEAD") at = @At("HEAD")
) )
private void preDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>>[] futureListeners, CallbackInfo ci) { private void preDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>>[] futureListeners, CallbackInfo ci) {
if (this.direction == EnumPacketDirection.CLIENTBOUND) { if (this.direction != EnumPacketDirection.CLIENTBOUND) {
Baritone.INSTANCE.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, inPacket)); return;
}
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) {
ibaritone.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, inPacket));
}
} }
} }
@@ -63,8 +70,14 @@ public class MixinNetworkManager {
at = @At("RETURN") at = @At("RETURN")
) )
private void postDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>>[] futureListeners, CallbackInfo ci) { private void postDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>>[] futureListeners, CallbackInfo ci) {
if (this.direction == EnumPacketDirection.CLIENTBOUND) { if (this.direction != EnumPacketDirection.CLIENTBOUND) {
Baritone.INSTANCE.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, inPacket)); return;
}
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) {
ibaritone.getGameEventHandler().onSendPacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, inPacket));
}
} }
} }
@@ -76,8 +89,13 @@ public class MixinNetworkManager {
) )
) )
private void preProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) { private void preProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) {
if (this.direction == EnumPacketDirection.CLIENTBOUND) { if (this.direction != EnumPacketDirection.CLIENTBOUND) {
Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, packet)); return;
}
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) {
ibaritone.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.PRE, packet));
}
} }
} }
@@ -86,8 +104,13 @@ public class MixinNetworkManager {
at = @At("RETURN") at = @At("RETURN")
) )
private void postProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) { private void postProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) {
if (this.channel.isOpen() && this.direction == EnumPacketDirection.CLIENTBOUND) { if (!this.channel.isOpen() || this.direction != EnumPacketDirection.CLIENTBOUND) {
Baritone.INSTANCE.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, packet)); return;
}
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().player().connection.getNetworkManager() == (NetworkManager) (Object) this) {
ibaritone.getGameEventHandler().onReceivePacket(new PacketEvent((NetworkManager) (Object) this, EventState.POST, packet));
}
} }
} }
} }
@@ -17,7 +17,8 @@
package baritone.launch.mixins; 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.ChunkEvent;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.multiplayer.WorldClient;
@@ -28,7 +29,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/** /**
* @author Brady * @author Brady
* @since 8/2/2018 12:41 AM * @since 8/2/2018
*/ */
@Mixin(WorldClient.class) @Mixin(WorldClient.class)
public class MixinWorldClient { public class MixinWorldClient {
@@ -38,14 +39,19 @@ public class MixinWorldClient {
at = @At("HEAD") at = @At("HEAD")
) )
private void preDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) { private void preDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onChunkEvent( for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
new ChunkEvent( if (ibaritone.getPlayerContext().world() == (WorldClient) (Object) this) {
EventState.PRE, ibaritone.getGameEventHandler().onChunkEvent(
loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD, new ChunkEvent(
chunkX, EventState.PRE,
chunkZ loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD,
) chunkX,
); chunkZ
)
);
}
}
} }
@Inject( @Inject(
@@ -53,13 +59,17 @@ public class MixinWorldClient {
at = @At("RETURN") at = @At("RETURN")
) )
private void postDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) { private void postDoPreChunk(int chunkX, int chunkZ, boolean loadChunk, CallbackInfo ci) {
Baritone.INSTANCE.getGameEventHandler().onChunkEvent( for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
new ChunkEvent( if (ibaritone.getPlayerContext().world() == (WorldClient) (Object) this) {
EventState.POST, ibaritone.getGameEventHandler().onChunkEvent(
loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD, new ChunkEvent(
chunkX, EventState.POST,
chunkZ loadChunk ? ChunkEvent.Type.LOAD : ChunkEvent.Type.UNLOAD,
) chunkX,
); chunkZ
)
);
}
}
} }
} }
+27 -43
View File
@@ -20,14 +20,13 @@ package baritone;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.Settings; import baritone.api.Settings;
import baritone.api.event.listener.IGameEventListener; import baritone.api.event.listener.IEventBus;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import baritone.behavior.Behavior; import baritone.behavior.Behavior;
import baritone.behavior.LookBehavior; import baritone.behavior.LookBehavior;
import baritone.behavior.MemoryBehavior; import baritone.behavior.MemoryBehavior;
import baritone.behavior.PathingBehavior; import baritone.behavior.PathingBehavior;
import baritone.cache.WorldProvider; import baritone.cache.WorldProvider;
import baritone.cache.WorldScanner;
import baritone.event.GameEventHandler; import baritone.event.GameEventHandler;
import baritone.process.CustomGoalProcess; import baritone.process.CustomGoalProcess;
import baritone.process.FollowProcess; import baritone.process.FollowProcess;
@@ -37,7 +36,7 @@ import baritone.utils.BaritoneAutoTest;
import baritone.utils.ExampleBaritoneControl; import baritone.utils.ExampleBaritoneControl;
import baritone.utils.InputOverrideHandler; import baritone.utils.InputOverrideHandler;
import baritone.utils.PathingControlManager; import baritone.utils.PathingControlManager;
import baritone.utils.player.LocalPlayerContext; import baritone.utils.player.PrimaryPlayerContext;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import java.io.File; import java.io.File;
@@ -52,14 +51,9 @@ import java.util.concurrent.TimeUnit;
/** /**
* @author Brady * @author Brady
* @since 7/31/2018 10:50 PM * @since 7/31/2018
*/ */
public enum Baritone implements IBaritone { public class Baritone implements IBaritone {
/**
* Singleton instance of this class
*/
INSTANCE;
private static ThreadPoolExecutor threadPool; private static ThreadPoolExecutor threadPool;
private static File dir; private static File dir;
@@ -95,6 +89,7 @@ public enum Baritone implements IBaritone {
private PathingControlManager pathingControlManager; private PathingControlManager pathingControlManager;
private IPlayerContext playerContext;
private WorldProvider worldProvider; private WorldProvider worldProvider;
Baritone() { Baritone() {
@@ -106,6 +101,9 @@ public enum Baritone implements IBaritone {
return; return;
} }
// Define this before behaviors try and get it, or else it will be null and the builds will fail!
this.playerContext = PrimaryPlayerContext.INSTANCE;
this.behaviors = new ArrayList<>(); this.behaviors = new ArrayList<>();
{ {
// the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist // the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist
@@ -127,23 +125,14 @@ public enum Baritone implements IBaritone {
this.worldProvider = new WorldProvider(); this.worldProvider = new WorldProvider();
if (BaritoneAutoTest.ENABLE_AUTO_TEST) { if (BaritoneAutoTest.ENABLE_AUTO_TEST) {
registerEventListener(BaritoneAutoTest.INSTANCE); this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE);
} }
this.initialized = true; this.initialized = true;
} }
public PathingControlManager getPathingControlManager() { public PathingControlManager getPathingControlManager() {
return pathingControlManager; return this.pathingControlManager;
}
public IGameEventListener getGameEventHandler() {
return this.gameEventHandler;
}
@Override
public InputOverrideHandler getInputOverrideHandler() {
return this.inputOverrideHandler;
} }
public List<Behavior> getBehaviors() { public List<Behavior> getBehaviors() {
@@ -152,67 +141,62 @@ public enum Baritone implements IBaritone {
public void registerBehavior(Behavior behavior) { public void registerBehavior(Behavior behavior) {
this.behaviors.add(behavior); this.behaviors.add(behavior);
this.registerEventListener(behavior); this.gameEventHandler.registerEventListener(behavior);
}
@Override
public InputOverrideHandler getInputOverrideHandler() {
return this.inputOverrideHandler;
} }
@Override @Override
public CustomGoalProcess getCustomGoalProcess() { // Iffy public CustomGoalProcess getCustomGoalProcess() { // Iffy
return customGoalProcess; return this.customGoalProcess;
} }
@Override @Override
public GetToBlockProcess getGetToBlockProcess() { // Iffy public GetToBlockProcess getGetToBlockProcess() { // Iffy
return getToBlockProcess; return this.getToBlockProcess;
} }
@Override @Override
public IPlayerContext getPlayerContext() { public IPlayerContext getPlayerContext() {
return LocalPlayerContext.INSTANCE; return this.playerContext;
} }
@Override @Override
public FollowProcess getFollowProcess() { public FollowProcess getFollowProcess() {
return followProcess; return this.followProcess;
} }
@Override @Override
public LookBehavior getLookBehavior() { public LookBehavior getLookBehavior() {
return lookBehavior; return this.lookBehavior;
} }
@Override @Override
public MemoryBehavior getMemoryBehavior() { public MemoryBehavior getMemoryBehavior() {
return memoryBehavior; return this.memoryBehavior;
} }
@Override @Override
public MineProcess getMineProcess() { public MineProcess getMineProcess() {
return mineProcess; return this.mineProcess;
} }
@Override @Override
public PathingBehavior getPathingBehavior() { public PathingBehavior getPathingBehavior() {
return pathingBehavior; return this.pathingBehavior;
} }
@Override @Override
public WorldProvider getWorldProvider() { public WorldProvider getWorldProvider() {
return worldProvider; return this.worldProvider;
}
/**
* TODO-yeet This shouldn't be baritone-instance specific
*
* @return world scanner instance
*/
@Override
public WorldScanner getWorldScanner() {
return WorldScanner.INSTANCE;
} }
@Override @Override
public void registerEventListener(IGameEventListener listener) { public IEventBus getGameEventHandler() {
this.gameEventHandler.registerEventListener(listener); return this.gameEventHandler;
} }
public static Settings settings() { public static Settings settings() {
+21 -3
View File
@@ -19,15 +19,33 @@ package baritone;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.IBaritoneProvider; import baritone.api.IBaritoneProvider;
import net.minecraft.client.entity.EntityPlayerSP; import baritone.api.cache.IWorldScanner;
import baritone.cache.WorldScanner;
import java.util.Collections;
import java.util.List;
/** /**
* @author Brady * @author Brady
* @since 9/29/2018 * @since 9/29/2018
*/ */
public final class BaritoneProvider implements IBaritoneProvider { public final class BaritoneProvider implements IBaritoneProvider {
private final Baritone primary = new Baritone();
@Override @Override
public IBaritone getBaritoneForPlayer(EntityPlayerSP player) { public IBaritone getPrimaryBaritone() {
return Baritone.INSTANCE; // pwnage return primary;
}
@Override
public List<IBaritone> getAllBaritones() {
// TODO return a CopyOnWriteArrayList
return Collections.singletonList(primary);
}
@Override
public IWorldScanner getWorldScanner() {
return WorldScanner.INSTANCE;
} }
} }
@@ -25,7 +25,7 @@ import baritone.api.utils.IPlayerContext;
* A type of game event listener that is given {@link Baritone} instance context. * A type of game event listener that is given {@link Baritone} instance context.
* *
* @author Brady * @author Brady
* @since 8/1/2018 6:29 PM * @since 8/1/2018
*/ */
public class Behavior implements IBehavior { public class Behavior implements IBehavior {
@@ -42,7 +42,7 @@ import java.util.*;
/** /**
* @author Brady * @author Brady
* @since 8/6/2018 9:47 PM * @since 8/6/2018
*/ */
public final class MemoryBehavior extends Behavior implements IMemoryBehavior { public final class MemoryBehavior extends Behavior implements IMemoryBehavior {
@@ -24,7 +24,6 @@ import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.RenderEvent; import baritone.api.event.events.RenderEvent;
import baritone.api.event.events.TickEvent; import baritone.api.event.events.TickEvent;
import baritone.api.pathing.calc.IPath; import baritone.api.pathing.calc.IPath;
import baritone.api.pathing.calc.IPathFinder;
import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalXZ; import baritone.api.pathing.goals.GoalXZ;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
@@ -36,7 +35,6 @@ import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementHelper;
import baritone.pathing.path.CutoffPath; import baritone.pathing.path.CutoffPath;
import baritone.pathing.path.PathExecutor; import baritone.pathing.path.PathExecutor;
import baritone.utils.BlockBreakHelper;
import baritone.utils.Helper; import baritone.utils.Helper;
import baritone.utils.PathRenderer; import baritone.utils.PathRenderer;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@@ -58,7 +56,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
private boolean cancelRequested; private boolean cancelRequested;
private boolean calcFailedLastTick; private boolean calcFailedLastTick;
private volatile boolean isPathCalcInProgress; private volatile AbstractNodeCostSearch inProgress;
private final Object pathCalcLock = new Object(); private final Object pathCalcLock = new Object();
private final Object pathPlanLock = new Object(); private final Object pathPlanLock = new Object();
@@ -101,7 +99,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
if (pauseRequestedLastTick && safeToCancel) { if (pauseRequestedLastTick && safeToCancel) {
pauseRequestedLastTick = false; pauseRequestedLastTick = false;
baritone.getInputOverrideHandler().clearAllKeys(); baritone.getInputOverrideHandler().clearAllKeys();
BlockBreakHelper.stopBreakingBlock(); baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock();
return; return;
} }
if (cancelRequested) { if (cancelRequested) {
@@ -142,13 +140,13 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
} }
// at this point, current just ended, but we aren't in the goal and have no plan for the future // at this point, current just ended, but we aren't in the goal and have no plan for the future
synchronized (pathCalcLock) { synchronized (pathCalcLock) {
if (isPathCalcInProgress) { if (inProgress != null) {
queuePathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING); queuePathEvent(PathEvent.PATH_FINISHED_NEXT_STILL_CALCULATING);
// if we aren't calculating right now // if we aren't calculating right now
return; return;
} }
queuePathEvent(PathEvent.CALC_STARTED); queuePathEvent(PathEvent.CALC_STARTED);
findPathInNewThread(pathStart(), true, Optional.empty()); findPathInNewThread(pathStart(), true);
} }
return; return;
} }
@@ -167,7 +165,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
next = null; next = null;
} }
synchronized (pathCalcLock) { synchronized (pathCalcLock) {
if (isPathCalcInProgress) { if (inProgress != null) {
// if we aren't calculating right now // if we aren't calculating right now
return; return;
} }
@@ -183,7 +181,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
// and this path has 5 seconds or less left // and this path has 5 seconds or less left
logDebug("Path almost over. Planning ahead..."); logDebug("Path almost over. Planning ahead...");
queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED); queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED);
findPathInNewThread(current.getPath().getDest(), false, Optional.of(current.getPath())); findPathInNewThread(current.getPath().getDest(), false);
} }
} }
} }
@@ -239,8 +237,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
} }
@Override @Override
public Optional<IPathFinder> getPathFinder() { public Optional<AbstractNodeCostSearch> getInProgress() {
return Optional.ofNullable(AbstractNodeCostSearch.currentlyRunning()); return Optional.ofNullable(inProgress);
} }
@Override @Override
@@ -285,7 +283,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
current = null; current = null;
next = null; next = null;
cancelRequested = true; cancelRequested = true;
AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(AbstractNodeCostSearch::cancel); getInProgress().ifPresent(AbstractNodeCostSearch::cancel); // only cancel ours
// do everything BUT clear keys // do everything BUT clear keys
} }
@@ -295,14 +293,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
current = null; current = null;
next = null; next = null;
baritone.getInputOverrideHandler().clearAllKeys(); baritone.getInputOverrideHandler().clearAllKeys();
AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(AbstractNodeCostSearch::cancel); getInProgress().ifPresent(AbstractNodeCostSearch::cancel);
BlockBreakHelper.stopBreakingBlock(); baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock();
} }
public void forceCancel() { // NOT exposed on public api public void forceCancel() { // NOT exposed on public api
cancelEverything(); cancelEverything();
secretInternalSegmentCancel(); secretInternalSegmentCancel();
isPathCalcInProgress = false; inProgress = null;
} }
/** /**
@@ -322,11 +320,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
return false; return false;
} }
synchronized (pathCalcLock) { synchronized (pathCalcLock) {
if (isPathCalcInProgress) { if (inProgress != null) {
return false; return false;
} }
queuePathEvent(PathEvent.CALC_STARTED); queuePathEvent(PathEvent.CALC_STARTED);
findPathInNewThread(pathStart(), true, Optional.empty()); findPathInNewThread(pathStart(), true);
return true; return true;
} }
} }
@@ -337,7 +335,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
* *
* @return The starting {@link BlockPos} for a new path * @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(); BetterBlockPos feet = ctx.playerFeet();
if (!MovementHelper.canWalkOn(ctx, feet.down())) { if (!MovementHelper.canWalkOn(ctx, feet.down())) {
if (ctx.player().onGround) { if (ctx.player().onGround) {
@@ -383,20 +381,36 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
* @param start * @param start
* @param talkAboutIt * @param talkAboutIt
*/ */
private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt, final Optional<IPath> previous) { private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt) {
synchronized (pathCalcLock) { // this must be called with synchronization on pathCalcLock!
if (isPathCalcInProgress) { // actually, we can check this, muahaha
throw new IllegalStateException("Already doing it"); if (!Thread.holdsLock(pathCalcLock)) {
} throw new IllegalStateException("Must be called with synchronization on pathCalcLock");
isPathCalcInProgress = true; // 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.<Long>get();
} else {
timeout = Baritone.settings().planAheadTimeoutMS.<Long>get();
} }
CalculationContext context = new CalculationContext(baritone); // 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
AbstractNodeCostSearch pathfinder = createPathfinder(start, goal, Optional.ofNullable(current).map(PathExecutor::getPath), context);
inProgress = pathfinder;
Baritone.getExecutor().execute(() -> { Baritone.getExecutor().execute(() -> {
if (talkAboutIt) { if (talkAboutIt) {
logDebug("Starting to search for path from " + start + " to " + goal); logDebug("Starting to search for path from " + start + " to " + goal);
} }
PathCalculationResult calcResult = findPath(start, previous, context); PathCalculationResult calcResult = pathfinder.calculate(timeout);
Optional<IPath> path = calcResult.path; Optional<IPath> path = calcResult.path;
if (Baritone.settings().cutoffAtLoadBoundary.get()) { if (Baritone.settings().cutoffAtLoadBoundary.get()) {
path = path.map(p -> { path = path.map(p -> {
@@ -454,51 +468,28 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
} }
} }
synchronized (pathCalcLock) { synchronized (pathCalcLock) {
isPathCalcInProgress = false; inProgress = null;
} }
} }
}); });
} }
/** private AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, Optional<IPath> previous, CalculationContext context) {
* Actually do the pathing Goal transformed = goal;
*
* @param start
* @return
*/
private PathCalculationResult findPath(BlockPos start, Optional<IPath> previous, CalculationContext context) {
Goal goal = this.goal;
if (goal == null) {
logDebug("no goal");
return new PathCalculationResult(PathCalculationResult.Type.CANCELLATION, Optional.empty());
}
if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) { if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) {
BlockPos pos = ((IGoalRenderPos) goal).getGoalPos(); BlockPos pos = ((IGoalRenderPos) goal).getGoalPos();
if (context.world().getChunk(pos) instanceof EmptyChunk) { if (context.world().getChunk(pos) instanceof EmptyChunk) {
logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance"); 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.<Long>get();
} else {
timeout = Baritone.settings().planAheadTimeoutMS.<Long>get();
}
Optional<HashSet<Long>> favoredPositions; Optional<HashSet<Long>> favoredPositions;
if (Baritone.settings().backtrackCostFavoringCoefficient.get() == 1D) { if (Baritone.settings().backtrackCostFavoringCoefficient.get() == 1D) {
favoredPositions = Optional.empty(); favoredPositions = Optional.empty();
} else { } 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.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 { return new AStarPathFinder(start.getX(), start.getY(), start.getZ(), transformed, favoredPositions, context);
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());
}
} }
@Override @Override
+3 -3
View File
@@ -17,7 +17,7 @@
package baritone.bot; package baritone.bot;
import baritone.Baritone; import baritone.api.BaritoneAPI;
import baritone.api.event.events.TickEvent; import baritone.api.event.events.TickEvent;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.event.listener.AbstractGameEventListener;
@@ -56,7 +56,7 @@ public final class UserManager implements Helper {
private UserManager() { private UserManager() {
// Setup an event listener that automatically disconnects bots when we're not in-game // Setup an event listener that automatically disconnects bots when we're not in-game
Baritone.INSTANCE.registerEventListener(new AbstractGameEventListener() { BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().registerEventListener(new AbstractGameEventListener() {
@Override @Override
public final void onTick(TickEvent event) { public final void onTick(TickEvent event) {
@@ -131,7 +131,7 @@ public final class UserManager implements Helper {
* Notifies the manager of an {@link IBaritoneUser} disconnect, and * Notifies the manager of an {@link IBaritoneUser} disconnect, and
* removes the {@link IBaritoneUser} from the list of users. * removes the {@link IBaritoneUser} from the list of users.
* *
* @param user The user that disconnected * @param user The user that disconnected
* @param state The connection state at the time of disconnect * @param state The connection state at the time of disconnect
*/ */
public final void notifyDisconnect(IBaritoneUser user, EnumConnectionState state) { public final void notifyDisconnect(IBaritoneUser user, EnumConnectionState state) {
+1 -1
View File
@@ -27,7 +27,7 @@ import java.util.*;
/** /**
* @author Brady * @author Brady
* @since 8/3/2018 1:04 AM * @since 8/3/2018
*/ */
public final class CachedChunk { public final class CachedChunk {
+1 -1
View File
@@ -32,7 +32,7 @@ import java.util.zip.GZIPOutputStream;
/** /**
* @author Brady * @author Brady
* @since 8/3/2018 9:35 PM * @since 8/3/2018
*/ */
public final class CachedRegion implements ICachedRegion { public final class CachedRegion implements ICachedRegion {
+9 -5
View File
@@ -18,7 +18,10 @@
package baritone.cache; package baritone.cache;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.cache.ICachedWorld; import baritone.api.cache.ICachedWorld;
import baritone.api.cache.IWorldData;
import baritone.utils.Helper; import baritone.utils.Helper;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
@@ -35,7 +38,7 @@ import java.util.concurrent.LinkedBlockingQueue;
/** /**
* @author Brady * @author Brady
* @since 8/4/2018 12:02 AM * @since 8/4/2018
*/ */
public final class CachedWorld implements ICachedWorld, Helper { public final class CachedWorld implements ICachedWorld, Helper {
@@ -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 * If we are still in this world and dimension, return player feet, otherwise return most recently modified chunk
*/ */
private BlockPos guessPosition() { private BlockPos guessPosition() {
WorldData data = Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (data != null && data.getCachedWorld() == this) { IWorldData data = ibaritone.getWorldProvider().getCurrentWorld();
// TODO-yeet fix if (data != null && data.getCachedWorld() == this) {
return Baritone.INSTANCE.getPlayerContext().playerFeet(); return ibaritone.getPlayerContext().playerFeet();
}
} }
CachedChunk mostRecentlyModified = null; CachedChunk mostRecentlyModified = null;
for (CachedRegion region : allRegions()) { for (CachedRegion region : allRegions()) {
+1 -1
View File
@@ -35,7 +35,7 @@ import java.util.*;
/** /**
* @author Brady * @author Brady
* @since 8/3/2018 1:09 AM * @since 8/3/2018
*/ */
public final class ChunkPacker { public final class ChunkPacker {
+1 -1
View File
@@ -36,7 +36,7 @@ import java.util.function.Consumer;
/** /**
* @author Brady * @author Brady
* @since 8/4/2018 11:06 AM * @since 8/4/2018
*/ */
public class WorldProvider implements IWorldProvider, Helper { public class WorldProvider implements IWorldProvider, Helper {
@@ -20,25 +20,27 @@ package baritone.event;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.event.events.*; import baritone.api.event.events.*;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import baritone.api.event.listener.IEventBus;
import baritone.api.event.listener.IGameEventListener; import baritone.api.event.listener.IGameEventListener;
import baritone.bot.UserManager; import baritone.bot.UserManager;
import baritone.cache.WorldProvider; import baritone.cache.WorldProvider;
import baritone.utils.Helper; import baritone.utils.Helper;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
/** /**
* @author Brady * @author Brady
* @since 7/31/2018 11:04 PM * @since 7/31/2018
*/ */
public final class GameEventHandler implements IGameEventListener, Helper { public final class GameEventHandler implements IEventBus, Helper {
private final Baritone baritone; private final Baritone baritone;
private final List<IGameEventListener> listeners = new ArrayList<>(); private final List<IGameEventListener> listeners = new CopyOnWriteArrayList<>();
public GameEventHandler(Baritone baritone) { public GameEventHandler(Baritone baritone) {
this.baritone = baritone; this.baritone = baritone;
@@ -83,17 +85,19 @@ public final class GameEventHandler implements IGameEventListener, Helper {
boolean isPostPopulate = state == EventState.POST boolean isPostPopulate = state == EventState.POST
&& type == ChunkEvent.Type.POPULATE; && type == ChunkEvent.Type.POPULATE;
World world = baritone.getPlayerContext().world();
// Whenever the server sends us to another dimension, chunks are unloaded // Whenever the server sends us to another dimension, chunks are unloaded
// technically after the new world has been loaded, so we perform a check // technically after the new world has been loaded, so we perform a check
// to make sure the chunk being unloaded is already loaded. // to make sure the chunk being unloaded is already loaded.
boolean isPreUnload = state == EventState.PRE boolean isPreUnload = state == EventState.PRE
&& type == ChunkEvent.Type.UNLOAD && type == ChunkEvent.Type.UNLOAD
&& mc.world.getChunkProvider().isChunkGeneratedAt(event.getX(), event.getZ()); && world.getChunkProvider().isChunkGeneratedAt(event.getX(), event.getZ());
if (isPostPopulate || isPreUnload) { if (isPostPopulate || isPreUnload) {
baritone.getWorldProvider().ifWorldLoaded(world -> { baritone.getWorldProvider().ifWorldLoaded(worldData -> {
Chunk chunk = mc.world.getChunk(event.getX(), event.getZ()); Chunk chunk = world.getChunk(event.getX(), event.getZ());
world.getCachedWorld().queueForPacking(chunk); worldData.getCachedWorld().queueForPacking(chunk);
}); });
} }
@@ -154,8 +158,8 @@ public final class GameEventHandler implements IGameEventListener, Helper {
listeners.forEach(l -> l.onPathEvent(event)); listeners.forEach(l -> l.onPathEvent(event));
} }
@Override
public final void registerEventListener(IGameEventListener listener) { public final void registerEventListener(IGameEventListener listener) {
this.listeners.add(listener); this.listeners.add(listener);
} }
} }
@@ -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 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(); double favorCoeff = Baritone.settings().backtrackCostFavoringCoefficient.get();
boolean minimumImprovementRepropagation = Baritone.settings().minimumImprovementRepropagation.get(); boolean minimumImprovementRepropagation = Baritone.settings().minimumImprovementRepropagation.get();
loopBegin();
while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && System.nanoTime() / 1000000L - timeoutTime < 0 && !cancelRequested) { while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && System.nanoTime() / 1000000L - timeoutTime < 0 && !cancelRequested) {
if (slowPath) { if (slowPath) {
try { try {
@@ -23,6 +23,7 @@ import baritone.api.pathing.calc.IPathFinder;
import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.Goal;
import baritone.api.utils.PathCalculationResult; import baritone.api.utils.PathCalculationResult;
import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.CalculationContext;
import baritone.utils.Helper;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import java.util.Optional; import java.util.Optional;
@@ -34,11 +35,6 @@ import java.util.Optional;
*/ */
public abstract class AbstractNodeCostSearch implements IPathFinder { public abstract class AbstractNodeCostSearch implements IPathFinder {
/**
* The currently running search task
*/
private static AbstractNodeCostSearch currentlyRunning = null;
protected final int startX; protected final int startX;
protected final int startY; protected final int startY;
protected final int startZ; protected final int startZ;
@@ -107,21 +103,16 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
} else { } else {
return new PathCalculationResult(PathCalculationResult.Type.SUCCESS_SEGMENT, path); 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 { } finally {
// this is run regardless of what exception may or may not be raised by calculate0 // this is run regardless of what exception may or may not be raised by calculate0
currentlyRunning = null;
isFinished = true; 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<IPath> calculate0(long timeout); protected abstract Optional<IPath> calculate0(long timeout);
/** /**
@@ -156,22 +147,6 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
return node; 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 @Override
public Optional<IPath> pathToMostRecentNodeConsidered() { public Optional<IPath> pathToMostRecentNodeConsidered() {
try { try {
@@ -188,7 +163,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
@Override @Override
public Optional<IPath> bestPathSoFar() { public Optional<IPath> bestPathSoFar() {
if (startNode == null || bestSoFar[0] == null) { if (startNode == null || bestSoFar == null || bestSoFar[0] == null) {
return Optional.empty(); return Optional.empty();
} }
for (int i = 0; i < bestSoFar.length; i++) { for (int i = 0; i < bestSoFar.length; i++) {
@@ -218,12 +193,4 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
public final Goal getGoal() { public final Goal getGoal() {
return goal; return goal;
} }
public static Optional<AbstractNodeCostSearch> getCurrentlyRunning() {
return Optional.ofNullable(currentlyRunning);
}
public static AbstractNodeCostSearch currentlyRunning() {
return currentlyRunning;
}
} }
@@ -36,7 +36,7 @@ import net.minecraft.world.World;
/** /**
* @author Brady * @author Brady
* @since 8/7/2018 4:30 PM * @since 8/7/2018
*/ */
public class CalculationContext { public class CalculationContext {
@@ -153,7 +153,7 @@ public abstract class Movement implements IMovement, MovementHelper {
if (reachable.isPresent()) { if (reachable.isPresent()) {
MovementHelper.switchToBestToolFor(ctx, BlockStateInterface.get(ctx, blockPos)); MovementHelper.switchToBestToolFor(ctx, BlockStateInterface.get(ctx, blockPos));
state.setTarget(new MovementState.MovementTarget(reachable.get(), true)); 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); state.setInput(Input.CLICK_LEFT, true);
} }
return false; return false;
@@ -35,6 +35,7 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.NonNullList; import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.EmptyChunk; 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 // so the only remaining dynamic isPassables are snow and trapdoor
// if they're cached as a top block, we don't know their metadata // 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) // 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; return true;
} }
if (snow) { if (snow) {
@@ -150,7 +151,7 @@ public interface MovementHelper extends ActionCosts, Helper {
return block.isPassable(null, null); 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 // for MovementTraverse and MovementAscend
// block double plant defaults to true when the block doesn't match, so don't need to check that case // 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 // all other overrides just return true or false
@@ -164,7 +165,7 @@ public interface MovementHelper extends ActionCosts, Helper {
Block block = state.getBlock(); Block block = state.getBlock();
if (block instanceof BlockSnow) { if (block instanceof BlockSnow) {
// as before, default to true (mostly because it would otherwise make long distance pathing through snowy biomes impossible) // 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 true;
} }
return state.getValue(BlockSnow.LAYERS) == 1; 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. * water, regardless of whether or not it is flowing.
* *
* @param ctx The player context * @param ctx The player context
* @param bp The block pos * @param bp The block pos
* @return Whether or not the block is water * @return Whether or not the block is water
*/ */
static boolean isWater(IPlayerContext ctx, BlockPos bp) { 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 * Returns whether or not the specified pos has a liquid
* *
* @param ctx The player context * @param ctx The player context
* @param p The pos * @param p The pos
* @return Whether or not the block is a liquid * @return Whether or not the block is a liquid
*/ */
static boolean isLiquid(IPlayerContext ctx, BlockPos p) { static boolean isLiquid(IPlayerContext ctx, BlockPos p) {
@@ -21,7 +21,6 @@ import baritone.Baritone;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus; import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.RayTraceUtils;
import baritone.api.utils.RotationUtils; import baritone.api.utils.RotationUtils;
import baritone.api.utils.input.Input; import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.CalculationContext;
@@ -31,7 +30,6 @@ import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import net.minecraft.block.BlockFalling; import net.minecraft.block.BlockFalling;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@@ -76,7 +74,7 @@ public class MovementAscend extends Movement {
if (!context.canPlaceThrowawayAt(destX, y, destZ)) { if (!context.canPlaceThrowawayAt(destX, y, destZ)) {
return COST_INF; 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; return COST_INF;
} }
// TODO: add ability to place against .down() as well as the cardinal directions // TODO: add ability to place against .down() as well as the cardinal directions
@@ -181,9 +179,9 @@ public class MovementAscend extends Movement {
double faceY = (dest.getY() + anAgainst.getY()) * 0.5D; double faceY = (dest.getY() + anAgainst.getY()) * 0.5D;
double faceZ = (dest.getZ() + anAgainst.getZ() + 1.0D) * 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)); 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)) { if (Objects.equals(selectedBlock, anAgainst) && selectedBlock.offset(side).equals(positionToPlace)) {
ticksWithoutPlacement++; ticksWithoutPlacement++;
state.setInput(Input.SNEAK, true); state.setInput(Input.SNEAK, true);
@@ -77,7 +77,7 @@ public class MovementFall extends Movement {
targetRotation = new Rotation(toDest.getYaw(), 90.0F); 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) { if (trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK && ctx.player().rotationPitch > 89.0F) {
state.setInput(Input.CLICK_RIGHT, true); state.setInput(Input.CLICK_RIGHT, true);
} }
@@ -34,7 +34,6 @@ import baritone.utils.Helper;
import baritone.utils.pathing.MutableMoveResult; import baritone.utils.pathing.MutableMoveResult;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@@ -45,7 +44,7 @@ import java.util.Objects;
public class MovementParkour extends Movement { 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 static final BetterBlockPos[] EMPTY = new BetterBlockPos[]{};
private final EnumFacing direction; private final EnumFacing direction;
@@ -135,12 +134,12 @@ public class MovementParkour extends Movement {
if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) { if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) {
return; 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; return;
} }
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP [i].getXOffset(); 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 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 if (againstX == x + xDiff * 3 && againstZ == z + zDiff * 3) { // we can't turn around that fast
continue; continue;
} }
@@ -216,7 +215,7 @@ public class MovementParkour extends Movement {
if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround) { if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround) {
BlockPos positionToPlace = dest.down(); BlockPos positionToPlace = dest.down();
for (int i = 0; i < 5; i++) { 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 if (against1.up().equals(src.offset(direction, 3))) { // we can't turn around that fast
continue; continue;
} }
@@ -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())) { 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)); state.setTarget(new MovementState.MovementTarget(place, true));
} }
RayTraceUtils.getSelectedBlock().ifPresent(selectedBlock -> { ctx.getSelectedBlock().ifPresent(selectedBlock -> {
EnumFacing side = Minecraft.getMinecraft().objectMouseOver.sideHit; EnumFacing side = ctx.objectMouseOver().sideHit;
if (Objects.equals(selectedBlock, against1) && selectedBlock.offset(side).equals(dest.down())) { if (Objects.equals(selectedBlock, against1) && selectedBlock.offset(side).equals(dest.down())) {
state.setInput(Input.CLICK_RIGHT, true); state.setInput(Input.CLICK_RIGHT, true);
} }
@@ -20,7 +20,10 @@ package baritone.pathing.movement.movements;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus; 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.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement; import baritone.pathing.movement.Movement;
@@ -29,7 +32,6 @@ import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@@ -101,7 +103,7 @@ public class MovementTraverse extends Movement {
if (srcDown == Blocks.LADDER || srcDown == Blocks.VINE) { if (srcDown == Blocks.LADDER || srcDown == Blocks.VINE) {
return COST_INF; 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()); boolean throughWater = MovementHelper.isWater(pb0.getBlock()) || MovementHelper.isWater(pb1.getBlock());
if (MovementHelper.isWater(destOn.getBlock()) && throughWater) { if (MovementHelper.isWater(destOn.getBlock()) && throughWater) {
return COST_INF; return COST_INF;
@@ -167,7 +169,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 // 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 // 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(); float pitchToBreak = state.getTarget().getRotation().get().getPitch();
state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true)); state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true));
@@ -191,7 +193,7 @@ public class MovementTraverse extends Movement {
isDoorActuallyBlockingUs = true; isDoorActuallyBlockingUs = true;
} }
if (isDoorActuallyBlockingUs && !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()))) { 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); .setInput(Input.CLICK_RIGHT, true);
} }
} }
@@ -205,7 +207,7 @@ public class MovementTraverse extends Movement {
} }
if (blocked != null) { 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); .setInput(Input.CLICK_RIGHT, true);
} }
} }
@@ -265,8 +267,8 @@ public class MovementTraverse extends Movement {
double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; 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)); 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;
if (Objects.equals(RayTraceUtils.getSelectedBlock().orElse(null), against1) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && RayTraceUtils.getSelectedBlock().get().offset(side).equals(positionToPlace)) { 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); return state.setInput(Input.CLICK_RIGHT, true);
} }
//System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); //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.setTarget(new MovementState.MovementTarget(backToFace, true));
} }
state.setInput(Input.SNEAK, 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 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()); // Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt());
@@ -32,7 +32,6 @@ import baritone.pathing.calc.AbstractNodeCostSearch;
import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.movements.*; import baritone.pathing.movement.movements.*;
import baritone.utils.BlockBreakHelper;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import baritone.utils.Helper; import baritone.utils.Helper;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
@@ -296,7 +295,7 @@ public class PathExecutor implements IPathExecutor, Helper {
} }
private boolean shouldPause() { private boolean shouldPause() {
Optional<AbstractNodeCostSearch> current = AbstractNodeCostSearch.getCurrentlyRunning(); Optional<AbstractNodeCostSearch> current = behavior.getInProgress();
if (!current.isPresent()) { if (!current.isPresent()) {
return false; return false;
} }
@@ -452,7 +451,7 @@ public class PathExecutor implements IPathExecutor, Helper {
private void cancel() { private void cancel() {
clearKeys(); clearKeys();
BlockBreakHelper.stopBreakingBlock(); behavior.baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock();
pathPosition = path.length() + 3; pathPosition = path.length() + 3;
failed = true; failed = true;
} }
@@ -17,7 +17,7 @@
package baritone.utils; package baritone.utils;
import baritone.Baritone; import baritone.api.BaritoneAPI;
import baritone.api.event.events.TickEvent; import baritone.api.event.events.TickEvent;
import baritone.api.event.listener.AbstractGameEventListener; import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.Goal;
@@ -41,8 +41,6 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
private static final BlockPos STARTING_POSITION = new BlockPos(0, 65, 0); private static final BlockPos STARTING_POSITION = new BlockPos(0, 65, 0);
private static final Goal GOAL = new GoalBlock(69, 121, 420); private static final Goal GOAL = new GoalBlock(69, 121, 420);
private static final int MAX_TICKS = 3500; 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. * Called right after the {@link GameSettings} object is created in the {@link Minecraft} instance.
@@ -72,7 +70,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
@Override @Override
public void onTick(TickEvent event) { public void onTick(TickEvent event) {
IPlayerContext ctx = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext();
// If we're on the main menu then create the test world and launch the integrated server // If we're on the main menu then create the test world and launch the integrated server
if (mc.currentScreen instanceof GuiMainMenu) { if (mc.currentScreen instanceof GuiMainMenu) {
System.out.println("Beginning Baritone automatic test routine"); System.out.println("Beginning Baritone automatic test routine");
@@ -108,7 +106,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
} }
// Setup Baritone's pathing goal and (if needed) begin pathing // 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 we have reached our goal, print a message and safely close the game
if (GOAL.isInGoal(ctx.playerFeet())) { if (GOAL.isInGoal(ctx.playerFeet())) {
@@ -17,6 +17,9 @@
package baritone.utils; package baritone.utils;
import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.utils.IPlayerContext;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand; import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos; 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 * The last block that we tried to break, if this value changes
* between attempts, then we re-initialize the breaking process. * between attempts, then we re-initialize the breaking process.
*/ */
private static BlockPos lastBlock; private BlockPos lastBlock;
private static boolean didBreakLastTick; 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)) { if (!pos.equals(lastBlock)) {
mc.playerController.clickBlock(pos, side); playerContext.playerController().clickBlock(pos, side);
} }
if (mc.playerController.onPlayerDamageBlock(pos, side)) { if (playerContext.playerController().onPlayerDamageBlock(pos, side)) {
mc.player.swingArm(EnumHand.MAIN_HAND); playerContext.player().swingArm(EnumHand.MAIN_HAND);
} }
lastBlock = pos; lastBlock = pos;
} }
public static void stopBreakingBlock() { public void stopBreakingBlock() {
if (mc.playerController != null) { if (playerContext.playerController() != null) {
mc.playerController.resetBlockRemoving(); playerContext.playerController().resetBlockRemoving();
} }
lastBlock = null; lastBlock = null;
} }
public static boolean tick(boolean isLeftClick) { private boolean fakeBreak() {
RayTraceResult trace = mc.objectMouseOver; if (playerContext != BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext()) {
// for a non primary player, we need to fake break always, CLICK_LEFT has no effect
return true;
}
if (!Baritone.settings().leftClickWorkaround.get()) {
// if this setting is false, we CLICK_LEFT regardless of gui status
return false;
}
return mc.currentScreen != null;
}
public boolean tick(boolean isLeftClick) {
if (!fakeBreak()) {
if (didBreakLastTick) {
stopBreakingBlock();
}
return isLeftClick;
}
RayTraceResult trace = playerContext.objectMouseOver();
boolean isBlockTrace = trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK; 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 if (isLeftClick && isBlockTrace) {
// at a block, break the block without a direct game input manipulation.
if (mc.currentScreen != null && isLeftClick && isBlockTrace) {
tryBreakBlock(trace.getBlockPos(), trace.sideHit); tryBreakBlock(trace.getBlockPos(), trace.sideHit);
didBreakLastTick = true; didBreakLastTick = true;
} else if (didBreakLastTick) { } else if (didBreakLastTick) {
stopBreakingBlock(); stopBreakingBlock();
didBreakLastTick = false; didBreakLastTick = false;
} }
return !didBreakLastTick && isLeftClick; return false; // fakeBreak is true so no matter what we aren't forcing CLICK_LEFT
} }
} }
@@ -18,11 +18,9 @@
package baritone.utils; package baritone.utils;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import baritone.cache.CachedRegion; import baritone.cache.CachedRegion;
import baritone.cache.WorldData; import baritone.cache.WorldData;
import baritone.pathing.movement.CalculationContext;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks; import net.minecraft.init.Blocks;
@@ -54,6 +52,10 @@ public class BlockStateInterface {
this.world = world; 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 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(); return get(ctx, pos).getBlock();
} }
@@ -23,14 +23,12 @@ import baritone.api.cache.IWaypoint;
import baritone.api.event.events.ChatEvent; import baritone.api.event.events.ChatEvent;
import baritone.api.pathing.goals.*; import baritone.api.pathing.goals.*;
import baritone.api.pathing.movement.ActionCosts; import baritone.api.pathing.movement.ActionCosts;
import baritone.api.utils.RayTraceUtils;
import baritone.api.utils.SettingsUtil; import baritone.api.utils.SettingsUtil;
import baritone.behavior.Behavior; import baritone.behavior.Behavior;
import baritone.behavior.PathingBehavior; import baritone.behavior.PathingBehavior;
import baritone.bot.UserManager; import baritone.bot.UserManager;
import baritone.cache.ChunkPacker; import baritone.cache.ChunkPacker;
import baritone.cache.Waypoint; import baritone.cache.Waypoint;
import baritone.pathing.calc.AbstractNodeCostSearch;
import baritone.pathing.movement.Movement; import baritone.pathing.movement.Movement;
import baritone.pathing.movement.Moves; import baritone.pathing.movement.Moves;
import baritone.process.CustomGoalProcess; import baritone.process.CustomGoalProcess;
@@ -233,7 +231,6 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
} }
if (msg.equals("forcecancel")) { if (msg.equals("forcecancel")) {
pathingBehavior.cancelEverything(); pathingBehavior.cancelEverything();
AbstractNodeCostSearch.forceCancel();
pathingBehavior.forceCancel(); pathingBehavior.forceCancel();
logDirect("ok force canceled"); logDirect("ok force canceled");
return true; return true;
@@ -272,7 +269,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
String name = msg.substring(6).trim(); String name = msg.substring(6).trim();
Optional<Entity> toFollow = Optional.empty(); Optional<Entity> toFollow = Optional.empty();
if (name.length() == 0) { if (name.length() == 0) {
toFollow = RayTraceUtils.getSelectedEntity(); toFollow = ctx.getSelectedEntity();
} else { } else {
for (EntityPlayer pl : ctx.world().playerEntities) { for (EntityPlayer pl : ctx.world().playerEntities) {
String theirName = pl.getName().trim().toLowerCase(); String theirName = pl.getName().trim().toLowerCase();
+1 -1
View File
@@ -25,7 +25,7 @@ import net.minecraft.util.text.TextFormatting;
/** /**
* @author Brady * @author Brady
* @since 8/1/2018 12:18 AM * @since 8/1/2018
*/ */
public interface Helper { public interface Helper {
@@ -34,7 +34,7 @@ import java.util.Map;
* physically forcing down the assigned key. * physically forcing down the assigned key.
* *
* @author Brady * @author Brady
* @since 7/31/2018 11:20 PM * @since 7/31/2018
*/ */
public final class InputOverrideHandler extends Behavior implements IInputOverrideHandler { public final class InputOverrideHandler extends Behavior implements IInputOverrideHandler {
@@ -43,8 +43,11 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri
*/ */
private final Map<Input, Boolean> inputForceStateMap = new HashMap<>(); private final Map<Input, Boolean> inputForceStateMap = new HashMap<>();
private final BlockBreakHelper blockBreakHelper;
public InputOverrideHandler(Baritone baritone) { public InputOverrideHandler(Baritone baritone) {
super(baritone); super(baritone);
this.blockBreakHelper = new BlockBreakHelper(baritone.getPlayerContext());
} }
/** /**
@@ -109,9 +112,11 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri
if (event.getType() == TickEvent.Type.OUT) { if (event.getType() == TickEvent.Type.OUT) {
return; return;
} }
if (Baritone.settings().leftClickWorkaround.get()) { boolean stillClick = blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.getKeyBinding()));
boolean stillClick = BlockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT.getKeyBinding())); setInputForceState(Input.CLICK_LEFT, stillClick);
setInputForceState(Input.CLICK_LEFT, stillClick); }
}
public BlockBreakHelper getBlockBreakHelper() {
return blockBreakHelper;
} }
} }
+38 -25
View File
@@ -18,6 +18,7 @@
package baritone.utils; package baritone.utils;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.event.events.RenderEvent; import baritone.api.event.events.RenderEvent;
import baritone.api.pathing.calc.IPath; import baritone.api.pathing.calc.IPath;
import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.Goal;
@@ -27,16 +28,13 @@ import baritone.api.pathing.goals.GoalXZ;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.interfaces.IGoalRenderPos; import baritone.api.utils.interfaces.IGoalRenderPos;
import baritone.behavior.PathingBehavior; import baritone.behavior.PathingBehavior;
import baritone.pathing.calc.AbstractNodeCostSearch;
import baritone.pathing.path.PathExecutor; import baritone.pathing.path.PathExecutor;
import net.minecraft.block.state.IBlockState; 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.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats; 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.init.Blocks;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@@ -51,7 +49,7 @@ import static org.lwjgl.opengl.GL11.*;
/** /**
* @author Brady * @author Brady
* @since 8/9/2018 4:39 PM * @since 8/9/2018
*/ */
public final class PathRenderer implements Helper { public final class PathRenderer implements Helper {
@@ -65,9 +63,26 @@ public final class PathRenderer implements Helper {
// System.out.println(event.getPartialTicks()); // System.out.println(event.getPartialTicks());
float partialTicks = event.getPartialTicks(); float partialTicks = event.getPartialTicks();
Goal goal = behavior.getGoal(); 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) { 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()) { if (!Baritone.settings().renderPath.get()) {
return; return;
@@ -79,34 +94,32 @@ public final class PathRenderer implements Helper {
PathExecutor current = behavior.getCurrent(); // this should prevent most race conditions? 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 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 // Render the current path, if there is one
if (current != null && current.getPath() != null) { if (current != null && current.getPath() != null) {
int renderBegin = Math.max(current.getPosition() - 3, 0); 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) { 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(); //long split = System.nanoTime();
if (current != null) { if (current != null) {
drawManySelectionBoxes(player, current.toBreak(), partialTicks, Baritone.settings().colorBlocksToBreak.get()); drawManySelectionBoxes(renderView, current.toBreak(), partialTicks, Baritone.settings().colorBlocksToBreak.get());
drawManySelectionBoxes(player, current.toPlace(), partialTicks, Baritone.settings().colorBlocksToPlace.get()); drawManySelectionBoxes(renderView, current.toPlace(), partialTicks, Baritone.settings().colorBlocksToPlace.get());
drawManySelectionBoxes(player, current.toWalkInto(), partialTicks, Baritone.settings().colorBlocksToWalkInto.get()); drawManySelectionBoxes(renderView, current.toWalkInto(), partialTicks, Baritone.settings().colorBlocksToWalkInto.get());
} }
// If there is a path calculation currently running, render the path calculation process // 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 -> { 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 -> { currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> {
drawPath(mr, 0, player, partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20); drawPath(mr, 0, renderView, partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20);
drawManySelectionBoxes(player, Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get()); drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get());
}); });
}); });
//long end = System.nanoTime(); //long end = System.nanoTime();
@@ -116,7 +129,7 @@ public final class PathRenderer implements Helper {
//} //}
} }
public static void drawPath(IPath path, int startIndex, EntityPlayerSP player, float partialTicks, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) { public static void drawPath(IPath path, int startIndex, Entity player, float partialTicks, Color color, boolean fadeOut, int fadeStart0, int fadeEnd0) {
GlStateManager.enableBlend(); GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); 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); GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F);
@@ -175,7 +188,7 @@ public final class PathRenderer implements Helper {
GlStateManager.disableBlend(); 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 d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks;
double d1 = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; double d1 = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks;
double d2 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; double d2 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks;
@@ -187,7 +200,7 @@ public final class PathRenderer implements Helper {
BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).endVertex(); BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).endVertex();
} }
public static void drawManySelectionBoxes(EntityPlayer player, Collection<BlockPos> positions, float partialTicks, Color color) { public static void drawManySelectionBoxes(Entity player, Collection<BlockPos> positions, float partialTicks, Color color) {
GlStateManager.enableBlend(); GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F); GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F);
@@ -206,12 +219,12 @@ public final class PathRenderer implements Helper {
double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks;
double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks;
positions.forEach(pos -> { positions.forEach(pos -> {
IBlockState state = BlockStateInterface.get(Baritone.INSTANCE.getPlayerContext(), pos); IBlockState state = BlockStateInterface.get(BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext(), pos);
AxisAlignedBB toDraw; AxisAlignedBB toDraw;
if (state.getBlock().equals(Blocks.AIR)) { if (state.getBlock().equals(Blocks.AIR)) {
toDraw = Blocks.DIRT.getDefaultState().getSelectedBoundingBox(Minecraft.getMinecraft().world, pos); toDraw = Blocks.DIRT.getDefaultState().getSelectedBoundingBox(player.world, pos);
} else { } else {
toDraw = state.getSelectedBoundingBox(Minecraft.getMinecraft().world, pos); toDraw = state.getSelectedBoundingBox(player.world, pos);
} }
toDraw = toDraw.expand(expand, expand, expand).offset(-renderPosX, -renderPosY, -renderPosZ); toDraw = toDraw.expand(expand, expand, expand).offset(-renderPosX, -renderPosY, -renderPosZ);
BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION);
@@ -249,7 +262,7 @@ public final class PathRenderer implements Helper {
GlStateManager.disableBlend(); 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 renderPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks;
double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks;
double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks;
@@ -24,7 +24,6 @@ import baritone.api.pathing.goals.Goal;
import baritone.api.process.IBaritoneProcess; import baritone.api.process.IBaritoneProcess;
import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommand;
import baritone.behavior.PathingBehavior; import baritone.behavior.PathingBehavior;
import baritone.pathing.calc.AbstractNodeCostSearch;
import baritone.pathing.path.PathExecutor; import baritone.pathing.path.PathExecutor;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@@ -44,7 +43,7 @@ public class PathingControlManager {
public PathingControlManager(Baritone baritone) { public PathingControlManager(Baritone baritone) {
this.baritone = baritone; this.baritone = baritone;
this.processes = new HashSet<>(); 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 @Override
public void onTick(TickEvent event) { public void onTick(TickEvent event) {
if (event.getType() == TickEvent.Type.OUT) { if (event.getType() == TickEvent.Type.OUT) {
@@ -90,12 +89,12 @@ public class PathingControlManager {
p.cancelSegmentIfSafe(); p.cancelSegmentIfSafe();
break; break;
case FORCE_REVALIDATE_GOAL_AND_PATH: case FORCE_REVALIDATE_GOAL_AND_PATH:
if (!p.isPathing() && !AbstractNodeCostSearch.getCurrentlyRunning().isPresent()) { if (!p.isPathing() && !p.getInProgress().isPresent()) {
p.secretInternalSetGoalAndPath(command.goal); p.secretInternalSetGoalAndPath(command.goal);
} }
break; break;
case REVALIDATE_GOAL_AND_PATH: case REVALIDATE_GOAL_AND_PATH:
if (!p.isPathing() && !AbstractNodeCostSearch.getCurrentlyRunning().isPresent()) { if (!p.isPathing() && !p.getInProgress().isPresent()) {
p.secretInternalSetGoalAndPath(command.goal); p.secretInternalSetGoalAndPath(command.goal);
} }
break; break;
@@ -24,7 +24,7 @@ import java.io.File;
/** /**
* @author Brady * @author Brady
* @see WorldProvider * @see WorldProvider
* @since 8/4/2018 11:36 AM * @since 8/4/2018
*/ */
public interface IAnvilChunkLoader { public interface IAnvilChunkLoader {
@@ -23,7 +23,7 @@ import net.minecraft.world.chunk.storage.IChunkLoader;
/** /**
* @author Brady * @author Brady
* @see WorldProvider * @see WorldProvider
* @since 8/4/2018 11:33 AM * @since 8/4/2018
*/ */
public interface IChunkProviderServer { public interface IChunkProviderServer {
@@ -19,7 +19,7 @@ package baritone.utils.pathing;
/** /**
* @author Brady * @author Brady
* @since 8/4/2018 1:11 AM * @since 8/4/2018
*/ */
public enum PathingBlockType { public enum PathingBlockType {
@@ -17,12 +17,13 @@
package baritone.utils.player; package baritone.utils.player;
import baritone.Baritone; import baritone.api.BaritoneAPI;
import baritone.api.cache.IWorldData; import baritone.api.cache.IWorldData;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import net.minecraft.client.Minecraft; import baritone.utils.Helper;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.multiplayer.PlayerControllerMP; import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World; import net.minecraft.world.World;
/** /**
@@ -31,13 +32,9 @@ import net.minecraft.world.World;
* @author Brady * @author Brady
* @since 11/12/2018 * @since 11/12/2018
*/ */
public final class LocalPlayerContext implements IPlayerContext { public enum PrimaryPlayerContext implements IPlayerContext, Helper {
private static final Minecraft mc = Minecraft.getMinecraft(); INSTANCE;
public static final LocalPlayerContext INSTANCE = new LocalPlayerContext();
private LocalPlayerContext() {}
@Override @Override
public EntityPlayerSP player() { public EntityPlayerSP player() {
@@ -56,6 +53,11 @@ public final class LocalPlayerContext implements IPlayerContext {
@Override @Override
public IWorldData worldData() { public IWorldData worldData() {
return Baritone.INSTANCE.getWorldProvider().getCurrentWorld(); return BaritoneAPI.getProvider().getPrimaryBaritone().getWorldProvider().getCurrentWorld();
}
@Override
public RayTraceResult objectMouseOver() {
return mc.objectMouseOver;
} }
} }