Compare commits

...

26 Commits

Author SHA1 Message Date
Leijurv c528dba0ea v1.4.2 2019-10-11 17:52:11 -07:00
Leijurv 2b3a302a5f Merge branch '1.13.2' into 1.14.4 2019-10-11 17:04:53 -07:00
Leijurv 84a257faf4 fix air scuff 2019-10-06 17:37:07 -07:00
Leijurv 34620a448e Merge branch '1.13.2' into 1.14.4 2019-10-06 17:36:25 -07:00
Leijurv e54d63576f Merge branch '1.13.2' into 1.14.4 2019-10-06 17:02:41 -07:00
Leijurv 02419f8b07 v1.4.1 2019-08-20 15:25:30 -07:00
Leijurv ddeb2a5c14 perhaps fix concurrent modification issues 2019-08-20 15:07:36 -07:00
Leijurv 8973b73bfa reduce spamminess 2019-08-20 14:58:00 -07:00
Leijurv 4557bab3c4 maybe travis fix 2019-08-20 14:49:16 -07:00
Leijurv 6e185b580c Merge branch '1.13.2' into 1.14.4 2019-08-20 14:33:18 -07:00
Leijurv 4e73880d4a Merge branch '1.14.4' of github.com:cabaletta/baritone into 1.14.4 2019-08-17 20:29:32 -07:00
Leijurv 0bb148844d Merge branch '1.13.2' into 1.14.4 2019-08-17 16:10:59 -07:00
Leijurv e53b207148 Merge branch '1.13.2' into 1.14.4 2019-08-17 16:09:45 -07:00
Leijurv afc639ab4b bypass 2019-08-14 22:31:46 -07:00
Leijurv afebdce1f8 fix crash and ice behavior 2019-07-25 16:02:29 -07:00
Leijurv 2ca4c3042a fix realms 2019-07-25 15:50:58 -07:00
Leijurv 6bee5828a0 thank you brigadier very cool 2019-07-23 21:38:42 -07:00
Leijurv 8a5cc5b17d should be peaceful anyway 2019-07-23 20:54:00 -07:00
Leijurv 4e563c6130 could this be the worst possible way to copy a chunk array 2019-07-23 20:44:07 -07:00
Leijurv 01cf3c67a6 whatever this works lol 2019-07-23 19:25:48 -07:00
Leijurv 36315c5151 working for realsies 2019-07-23 15:47:18 -07:00
Leijurv 9f951f261d fixes 2019-07-23 15:39:19 -07:00
Leijurv 4c8907c629 it launches 2019-07-23 14:12:44 -07:00
Leijurv 223791cea7 Merge branch '1.13.2' into 1.14.2 2019-07-23 12:09:39 -07:00
Leijurv 8758c77ac0 most of the way there 2019-06-10 18:25:20 -07:00
Leijurv dba496471e api sourceset done 2019-06-10 12:43:02 -07:00
120 changed files with 1386 additions and 1600 deletions
+3 -3
View File
@@ -16,7 +16,7 @@
*/ */
group 'baritone' group 'baritone'
version '1.3.4' version '1.4.2'
buildscript { buildscript {
repositories { repositories {
@@ -82,7 +82,7 @@ task sourceJar(type: Jar, dependsOn: classes) {
} }
minecraft { minecraft {
mappings channel: 'snapshot', version: '20190307-1.13.1' mappings channel: 'snapshot', version: '20190814-1.14.3'
reobfMappings 'notch' reobfMappings 'notch'
runs { runs {
@@ -138,7 +138,7 @@ repositories {
} }
dependencies { dependencies {
minecraft 'com.github.ImpactDevelopment:Vanilla:1.13.2' minecraft 'com.github.ImpactDevelopment:Vanilla:1.14.4'
runtime launchCompile('net.minecraft:launchwrapper:1.12') { runtime launchCompile('net.minecraft:launchwrapper:1.12') {
exclude module: 'lwjgl' exclude module: 'lwjgl'
@@ -20,7 +20,7 @@ package baritone.api;
import baritone.api.cache.IWorldScanner; import baritone.api.cache.IWorldScanner;
import baritone.api.command.ICommand; import baritone.api.command.ICommand;
import baritone.api.command.ICommandSystem; import baritone.api.command.ICommandSystem;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -46,19 +46,19 @@ public interface IBaritoneProvider {
* returned by {@link #getPrimaryBaritone()}. * returned by {@link #getPrimaryBaritone()}.
* *
* @return All active {@link IBaritone} instances. * @return All active {@link IBaritone} instances.
* @see #getBaritoneForPlayer(EntityPlayerSP) * @see #getBaritoneForPlayer(ClientPlayerEntity)
*/ */
List<IBaritone> getAllBaritones(); 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 ClientPlayerEntity}. This will likely be
* replaced with or be overloaded in addition to {@code #getBaritoneForUser(IBaritoneUser)} when * replaced with or be overloaded in addition to {@code #getBaritoneForUser(IBaritoneUser)} when
* {@code bot-system} is merged into {@code master}. * {@code bot-system} is merged into {@code master}.
* *
* @param player The player * @param player The player
* @return The {@link IBaritone} instance. * @return The {@link IBaritone} instance.
*/ */
default IBaritone getBaritoneForPlayer(EntityPlayerSP player) { default IBaritone getBaritoneForPlayer(ClientPlayerEntity player) {
for (IBaritone baritone : getAllBaritones()) { for (IBaritone baritone : getAllBaritones()) {
if (Objects.equals(player, baritone.getPlayerContext().player())) { if (Objects.equals(player, baritone.getPlayerContext().player())) {
return baritone; return baritone;
+2 -4
View File
@@ -20,8 +20,8 @@ package baritone.api;
import baritone.api.utils.SettingsUtil; import baritone.api.utils.SettingsUtil;
import baritone.api.utils.TypeUtils; import baritone.api.utils.TypeUtils;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
@@ -178,9 +178,7 @@ public final class Settings {
Blocks.CRAFTING_TABLE, Blocks.CRAFTING_TABLE,
Blocks.FURNACE, Blocks.FURNACE,
Blocks.CHEST, Blocks.CHEST,
Blocks.TRAPPED_CHEST, Blocks.TRAPPED_CHEST
Blocks.SIGN,
Blocks.WALL_SIGN
))); )));
/** /**
+3 -3
View File
@@ -17,7 +17,7 @@
package baritone.api.cache; package baritone.api.cache;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
/** /**
@@ -26,9 +26,9 @@ import net.minecraft.util.math.BlockPos;
*/ */
public interface IBlockTypeAccess { public interface IBlockTypeAccess {
IBlockState getBlock(int x, int y, int z); BlockState getBlock(int x, int y, int z);
default IBlockState getBlock(BlockPos pos) { default BlockState getBlock(BlockPos pos) {
return getBlock(pos.getX(), pos.getY(), pos.getZ()); return getBlock(pos.getX(), pos.getY(), pos.getZ());
} }
} }
@@ -27,7 +27,7 @@ import baritone.api.command.datatypes.IDatatypePost;
import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidTypeException; import baritone.api.command.exception.CommandInvalidTypeException;
import baritone.api.command.exception.CommandNotEnoughArgumentsException; import baritone.api.command.exception.CommandNotEnoughArgumentsException;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import java.util.Deque; import java.util.Deque;
import java.util.LinkedList; import java.util.LinkedList;
@@ -404,8 +404,8 @@ public interface IArgConsumer {
/** /**
* Gets an enum value from the enum class with the same name as the next argument's value * Gets an enum value from the enum class with the same name as the next argument's value
* <p> * <p>
* For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return * For example if you getEnum as an {@link Direction}, and the next argument's value is "up", this will return
* {@link EnumFacing#UP} * {@link Direction#UP}
* *
* @param enumClass The enum class to search * @param enumClass The enum class to search
* @return An enum constant of that class with the same name as the next argument's value * @return An enum constant of that class with the same name as the next argument's value
@@ -419,8 +419,8 @@ public interface IArgConsumer {
/** /**
* Gets an enum value from the enum class with the same name as the next argument's value * Gets an enum value from the enum class with the same name as the next argument's value
* <p> * <p>
* For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return * For example if you getEnum as an {@link Direction}, and the next argument's value is "up", this will return
* {@link EnumFacing#UP} * {@link Direction#UP}
* *
* @param enumClass The enum class to search * @param enumClass The enum class to search
* @param def The default value * @param def The default value
@@ -436,8 +436,8 @@ public interface IArgConsumer {
/** /**
* Gets an enum value from the enum class with the same name as the next argument's value * Gets an enum value from the enum class with the same name as the next argument's value
* <p> * <p>
* For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return * For example if you getEnum as an {@link Direction}, and the next argument's value is "up", this will return
* {@link EnumFacing#UP} * {@link Direction#UP}
* *
* @param enumClass The enum class to search * @param enumClass The enum class to search
* @return An enum constant of that class with the same name as the next argument's value, or {@code null} if it * @return An enum constant of that class with the same name as the next argument's value, or {@code null} if it
@@ -19,7 +19,7 @@ package baritone.api.command.argument;
import baritone.api.command.argparser.IArgParser; import baritone.api.command.argparser.IArgParser;
import baritone.api.command.exception.CommandInvalidTypeException; import baritone.api.command.exception.CommandInvalidTypeException;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
/** /**
* A {@link ICommandArgument} is an immutable object representing one command argument. It contains data on the index of * A {@link ICommandArgument} is an immutable object representing one command argument. It contains data on the index of
@@ -50,8 +50,8 @@ public interface ICommandArgument {
/** /**
* Gets an enum value from the enum class with the same name as this argument's value * Gets an enum value from the enum class with the same name as this argument's value
* <p> * <p>
* For example if you getEnum as an {@link EnumFacing}, and this argument's value is "up", it will return {@link * For example if you getEnum as an {@link Direction}, and this argument's value is "up", it will return {@link
* EnumFacing#UP} * Direction#UP}
* *
* @param enumClass The enum class to search * @param enumClass The enum class to search
* @return An enum constant of that class with the same name as this argument's value * @return An enum constant of that class with the same name as this argument's value
@@ -17,12 +17,11 @@
package baritone.api.command.datatypes; package baritone.api.command.datatypes;
import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandException;
import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry; import net.minecraft.util.registry.Registry;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -33,7 +32,7 @@ public enum BlockById implements IDatatypeFor<Block> {
public Block get(IDatatypeContext ctx) throws CommandException { public Block get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString()); ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
Block block; Block block;
if ((block = IRegistry.BLOCK.get(id)) == Blocks.AIR) { if ((block = Registry.BLOCK.getValue(id).orElse(null)) == null) {
throw new IllegalArgumentException("no block found by that id"); throw new IllegalArgumentException("no block found by that id");
} }
return block; return block;
@@ -43,7 +42,7 @@ public enum BlockById implements IDatatypeFor<Block> {
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException { public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper() return new TabCompleteHelper()
.append( .append(
IRegistry.BLOCK.keySet() Registry.BLOCK.keySet()
.stream() .stream()
.map(Object::toString) .map(Object::toString)
) )
@@ -21,7 +21,7 @@ import baritone.api.command.exception.CommandException;
import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.entity.EntityType; import net.minecraft.entity.EntityType;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry; import net.minecraft.util.registry.Registry;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -32,7 +32,7 @@ public enum EntityClassById implements IDatatypeFor<EntityType> {
public EntityType get(IDatatypeContext ctx) throws CommandException { public EntityType get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString()); ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
EntityType entity; EntityType entity;
if ((entity = IRegistry.ENTITY_TYPE.get(id)) == null) { if ((entity = Registry.ENTITY_TYPE.getValue(id).orElse(null)) == null) {
throw new IllegalArgumentException("no entity found by that id"); throw new IllegalArgumentException("no entity found by that id");
} }
return entity; return entity;
@@ -41,7 +41,7 @@ public enum EntityClassById implements IDatatypeFor<EntityType> {
@Override @Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException { public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper() return new TabCompleteHelper()
.append(IRegistry.ENTITY_TYPE.stream().map(Object::toString)) .append(Registry.ENTITY_TYPE.stream().map(Object::toString))
.filterPrefixNamespaced(ctx.getConsumer().getString()) .filterPrefixNamespaced(ctx.getConsumer().getString())
.sortAlphabetically() .sortAlphabetically()
.stream(); .stream();
@@ -19,24 +19,24 @@ package baritone.api.command.datatypes;
import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandException;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import java.util.Locale; import java.util.Locale;
import java.util.stream.Stream; import java.util.stream.Stream;
public enum ForEnumFacing implements IDatatypeFor<EnumFacing> { public enum ForDirection implements IDatatypeFor<Direction> {
INSTANCE; INSTANCE;
@Override @Override
public EnumFacing get(IDatatypeContext ctx) throws CommandException { public Direction get(IDatatypeContext ctx) throws CommandException {
return EnumFacing.valueOf(ctx.getConsumer().getString().toUpperCase(Locale.US)); return Direction.valueOf(ctx.getConsumer().getString().toUpperCase(Locale.US));
} }
@Override @Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException { public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper() return new TabCompleteHelper()
.append(Stream.of(EnumFacing.values()) .append(Stream.of(Direction.values())
.map(EnumFacing::getName).map(String::toLowerCase)) .map(Direction::getName).map(String::toLowerCase))
.filterPrefix(ctx.getConsumer().getString()) .filterPrefix(ctx.getConsumer().getString())
.stream(); .stream();
} }
@@ -20,7 +20,7 @@ package baritone.api.command.datatypes;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandException;
import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import java.util.List; import java.util.List;
@@ -30,11 +30,11 @@ import java.util.stream.Stream;
* An {@link IDatatype} used to resolve nearby players, those within * An {@link IDatatype} used to resolve nearby players, those within
* render distance of the target {@link IBaritone} instance. * render distance of the target {@link IBaritone} instance.
*/ */
public enum NearbyPlayer implements IDatatypeFor<EntityPlayer> { public enum NearbyPlayer implements IDatatypeFor<PlayerEntity> {
INSTANCE; INSTANCE;
@Override @Override
public EntityPlayer get(IDatatypeContext ctx) throws CommandException { public PlayerEntity get(IDatatypeContext ctx) throws CommandException {
final String username = ctx.getConsumer().getString(); final String username = ctx.getConsumer().getString();
return getPlayers(ctx).stream() return getPlayers(ctx).stream()
.filter(s -> s.getName().getString().equalsIgnoreCase(username)) .filter(s -> s.getName().getString().equalsIgnoreCase(username))
@@ -44,13 +44,13 @@ public enum NearbyPlayer implements IDatatypeFor<EntityPlayer> {
@Override @Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException { public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper() return new TabCompleteHelper()
.append(getPlayers(ctx).stream().map(EntityPlayer::getName).map(ITextComponent::getString)) .append(getPlayers(ctx).stream().map(PlayerEntity::getName).map(ITextComponent::getString))
.filterPrefix(ctx.getConsumer().getString()) .filterPrefix(ctx.getConsumer().getString())
.sortAlphabetically() .sortAlphabetically()
.stream(); .stream();
} }
private static List<EntityPlayer> getPlayers(IDatatypeContext ctx) { private static List<? extends PlayerEntity> getPlayers(IDatatypeContext ctx) {
return ctx.getBaritone().getPlayerContext().world().playerEntities; return ctx.getBaritone().getPlayerContext().world().getPlayers();
} }
} }
@@ -22,7 +22,7 @@ import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidTypeException; import baritone.api.command.exception.CommandInvalidTypeException;
import baritone.api.command.argument.IArgConsumer; import baritone.api.command.argument.IArgConsumer;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.util.text.event.HoverEvent; import net.minecraft.util.text.event.HoverEvent;
@@ -74,7 +74,7 @@ public class Paginator<E> implements Helper {
} }
boolean hasPrevPage = commandPrefix != null && validPage(page - 1); boolean hasPrevPage = commandPrefix != null && validPage(page - 1);
boolean hasNextPage = commandPrefix != null && validPage(page + 1); boolean hasNextPage = commandPrefix != null && validPage(page + 1);
ITextComponent prevPageComponent = new TextComponentString("<<"); ITextComponent prevPageComponent = new StringTextComponent("<<");
if (hasPrevPage) { if (hasPrevPage) {
prevPageComponent.getStyle() prevPageComponent.getStyle()
.setClickEvent(new ClickEvent( .setClickEvent(new ClickEvent(
@@ -83,12 +83,12 @@ public class Paginator<E> implements Helper {
)) ))
.setHoverEvent(new HoverEvent( .setHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT, HoverEvent.Action.SHOW_TEXT,
new TextComponentString("Click to view previous page") new StringTextComponent("Click to view previous page")
)); ));
} else { } else {
prevPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY); prevPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
} }
ITextComponent nextPageComponent = new TextComponentString(">>"); ITextComponent nextPageComponent = new StringTextComponent(">>");
if (hasNextPage) { if (hasNextPage) {
nextPageComponent.getStyle() nextPageComponent.getStyle()
.setClickEvent(new ClickEvent( .setClickEvent(new ClickEvent(
@@ -97,12 +97,12 @@ public class Paginator<E> implements Helper {
)) ))
.setHoverEvent(new HoverEvent( .setHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT, HoverEvent.Action.SHOW_TEXT,
new TextComponentString("Click to view next page") new StringTextComponent("Click to view next page")
)); ));
} else { } else {
nextPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY); nextPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
} }
ITextComponent pagerComponent = new TextComponentString(""); ITextComponent pagerComponent = new StringTextComponent("");
pagerComponent.getStyle().setColor(TextFormatting.GRAY); pagerComponent.getStyle().setColor(TextFormatting.GRAY);
pagerComponent.appendSibling(prevPageComponent); pagerComponent.appendSibling(prevPageComponent);
pagerComponent.appendText(" | "); pagerComponent.appendText(" | ");
@@ -19,7 +19,7 @@ package baritone.api.event.events;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import net.minecraft.network.NetworkManager; import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet; import net.minecraft.network.IPacket;
/** /**
* @author Brady * @author Brady
@@ -31,9 +31,9 @@ public final class PacketEvent {
private final EventState state; private final EventState state;
private final Packet<?> packet; private final IPacket<?> packet;
public PacketEvent(NetworkManager networkManager, EventState state, Packet<?> packet) { public PacketEvent(NetworkManager networkManager, EventState state, IPacket<?> packet) {
this.networkManager = networkManager; this.networkManager = networkManager;
this.state = state; this.state = state;
this.packet = packet; this.packet = packet;
@@ -47,12 +47,12 @@ public final class PacketEvent {
return this.state; return this.state;
} }
public final Packet<?> getPacket() { public final IPacket<?> getPacket() {
return this.packet; return this.packet;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public final <T extends Packet<?>> T cast() { public final <T extends IPacket<?>> T cast() {
return (T) this.packet; return (T) this.packet;
} }
} }
@@ -18,7 +18,6 @@
package baritone.api.event.events; package baritone.api.event.events;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
/** /**
* @author Brady * @author Brady
@@ -76,7 +75,7 @@ public final class RotationMoveEvent {
/** /**
* Called when the player jumps. * Called when the player jumps.
* *
* @see EntityLivingBase#jump * @see LivingEntity#jump
*/ */
JUMP JUMP
} }
@@ -18,7 +18,7 @@
package baritone.api.event.events; package baritone.api.event.events;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.world.ClientWorld;
/** /**
* @author Brady * @author Brady
@@ -29,14 +29,14 @@ public final class WorldEvent {
/** /**
* The new world that is being loaded. {@code null} if being unloaded. * The new world that is being loaded. {@code null} if being unloaded.
*/ */
private final WorldClient world; private final ClientWorld world;
/** /**
* The state of the event * The state of the event
*/ */
private final EventState state; private final EventState state;
public WorldEvent(WorldClient world, EventState state) { public WorldEvent(ClientWorld world, EventState state) {
this.world = world; this.world = world;
this.state = state; this.state = state;
} }
@@ -44,7 +44,7 @@ public final class WorldEvent {
/** /**
* @return The new world that is being loaded. {@code null} if being unloaded. * @return The new world that is being loaded. {@code null} if being unloaded.
*/ */
public final WorldClient getWorld() { public final ClientWorld getWorld() {
return this.world; return this.world;
} }
@@ -19,12 +19,11 @@ package baritone.api.event.listener;
import baritone.api.event.events.*; import baritone.api.event.events.*;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.client.gui.GuiGameOver; import net.minecraft.client.gui.screen.DeathScreen;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.world.ClientWorld;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.network.Packet;
/** /**
* @author Brady * @author Brady
@@ -44,7 +43,7 @@ public interface IGameEventListener {
* Run once per game tick from before and after the player rotation is sent to the server. * Run once per game tick from before and after the player rotation is sent to the server.
* *
* @param event The event * @param event The event
* @see EntityPlayerSP#tick() * @see ClientPlayerEntity#tick()
*/ */
void onPlayerUpdate(PlayerUpdateEvent event); void onPlayerUpdate(PlayerUpdateEvent event);
@@ -52,7 +51,7 @@ public interface IGameEventListener {
* Runs whenever the client player sends a message to the server. * Runs whenever the client player sends a message to the server.
* *
* @param event The event * @param event The event
* @see EntityPlayerSP#sendChatMessage(String) * @see ClientPlayerEntity#sendChatMessage(String)
*/ */
void onSendChatMessage(ChatEvent event); void onSendChatMessage(ChatEvent event);
@@ -81,7 +80,7 @@ public interface IGameEventListener {
* Runs before and after whenever a new world is loaded * Runs before and after whenever a new world is loaded
* *
* @param event The event * @param event The event
* @see Minecraft#loadWorld(WorldClient, GuiScreen) * @see Minecraft#loadWorld(ClientWorld, Screen)
*/ */
void onWorldEvent(WorldEvent event); void onWorldEvent(WorldEvent event);
@@ -111,10 +110,10 @@ public interface IGameEventListener {
void onPlayerRotationMove(RotationMoveEvent event); void onPlayerRotationMove(RotationMoveEvent event);
/** /**
* Called whenever the sprint keybind state is checked in {@link EntityPlayerSP#livingTick} * Called whenever the sprint keybind state is checked in {@link ClientPlayerEntity#livingTick}
* *
* @param event The event * @param event The event
* @see EntityPlayerSP#livingTick() * @see ClientPlayerEntity#livingTick()
*/ */
void onPlayerSprintState(SprintStateEvent event); void onPlayerSprintState(SprintStateEvent event);
@@ -18,7 +18,7 @@
package baritone.api.pathing.goals; package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil; import baritone.api.utils.SettingsUtil;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
/** /**
@@ -32,7 +32,7 @@ public class GoalStrictDirection implements Goal {
public final int dx; public final int dx;
public final int dz; public final int dz;
public GoalStrictDirection(BlockPos origin, EnumFacing direction) { public GoalStrictDirection(BlockPos origin, Direction direction) {
x = origin.getX(); x = origin.getX();
y = origin.getY(); y = origin.getY();
z = origin.getZ(); z = origin.getZ();
@@ -18,7 +18,7 @@
package baritone.api.process; package baritone.api.process;
import baritone.api.schematic.ISchematic; import baritone.api.schematic.ISchematic;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
@@ -71,5 +71,5 @@ public interface IBuilderProcess extends IBaritoneProcess {
* schematics, for example, to pick a state that the builder process will be happy with, because any variation will * schematics, for example, to pick a state that the builder process will be happy with, because any variation will
* cause it to give up. This is updated every tick, but only while the builder process is active. * cause it to give up. This is updated every tick, but only while the builder process is active.
*/ */
List<IBlockState> getApproxPlaceable(); List<BlockState> getApproxPlaceable();
} }
@@ -17,7 +17,7 @@
package baritone.api.schematic; package baritone.api.schematic;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -47,7 +47,7 @@ public class CompositeSchematic extends AbstractSchematic {
recalcArr(); recalcArr();
} }
private CompositeSchematicEntry getSchematic(int x, int y, int z, IBlockState currentState) { private CompositeSchematicEntry getSchematic(int x, int y, int z, BlockState currentState) {
for (CompositeSchematicEntry entry : schematicArr) { for (CompositeSchematicEntry entry : schematicArr) {
if (x >= entry.x && y >= entry.y && z >= entry.z && if (x >= entry.x && y >= entry.y && z >= entry.z &&
entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState)) { entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState)) {
@@ -58,13 +58,13 @@ public class CompositeSchematic extends AbstractSchematic {
} }
@Override @Override
public boolean inSchematic(int x, int y, int z, IBlockState currentState) { public boolean inSchematic(int x, int y, int z, BlockState currentState) {
CompositeSchematicEntry entry = getSchematic(x, y, z, currentState); CompositeSchematicEntry entry = getSchematic(x, y, z, currentState);
return entry != null && entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState); return entry != null && entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState);
} }
@Override @Override
public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) { public BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) {
CompositeSchematicEntry entry = getSchematic(x, y, z, current); CompositeSchematicEntry entry = getSchematic(x, y, z, current);
if (entry == null) { if (entry == null) {
throw new IllegalStateException("couldn't find schematic for this position"); throw new IllegalStateException("couldn't find schematic for this position");
@@ -18,8 +18,8 @@
package baritone.api.schematic; package baritone.api.schematic;
import baritone.api.utils.BlockOptionalMeta; import baritone.api.utils.BlockOptionalMeta;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.init.Blocks; import net.minecraft.block.Blocks;
import java.util.List; import java.util.List;
@@ -37,13 +37,13 @@ public class FillSchematic extends AbstractSchematic {
} }
@Override @Override
public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) { public BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) {
if (bom.matches(current)) { if (bom.matches(current)) {
return current; return current;
} else if (current.getBlock() != Blocks.AIR) { } else if (current.getBlock() != Blocks.AIR) {
return Blocks.AIR.getDefaultState(); return Blocks.AIR.getDefaultState();
} }
for (IBlockState placeable : approxPlaceable) { for (BlockState placeable : approxPlaceable) {
if (bom.matches(placeable)) { if (bom.matches(placeable)) {
return placeable; return placeable;
} }
@@ -17,8 +17,8 @@
package baritone.api.schematic; package baritone.api.schematic;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import java.util.List; import java.util.List;
@@ -44,11 +44,11 @@ public interface ISchematic {
* @param currentState The current state of that block in the world, or null * @param currentState The current state of that block in the world, or null
* @return Whether or not the specified position is within the bounds of this schematic * @return Whether or not the specified position is within the bounds of this schematic
*/ */
default boolean inSchematic(int x, int y, int z, IBlockState currentState) { default boolean inSchematic(int x, int y, int z, BlockState currentState) {
return x >= 0 && x < widthX() && y >= 0 && y < heightY() && z >= 0 && z < lengthZ(); return x >= 0 && x < widthX() && y >= 0 && y < heightY() && z >= 0 && z < lengthZ();
} }
default int size(EnumFacing.Axis axis) { default int size(Direction.Axis axis) {
switch (axis) { switch (axis) {
case X: case X:
return widthX(); return widthX();
@@ -71,7 +71,7 @@ public interface ISchematic {
* @param approxPlaceable The list of blockstates estimated to be placeable * @param approxPlaceable The list of blockstates estimated to be placeable
* @return The desired block state at the specified position * @return The desired block state at the specified position
*/ */
IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable); BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable);
/** /**
* @return The width (X axis length) of this schematic * @return The width (X axis length) of this schematic
@@ -17,7 +17,7 @@
package baritone.api.schematic; package baritone.api.schematic;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import java.util.List; import java.util.List;
@@ -30,15 +30,15 @@ public abstract class MaskSchematic extends AbstractSchematic {
this.schematic = schematic; this.schematic = schematic;
} }
protected abstract boolean partOfMask(int x, int y, int z, IBlockState currentState); protected abstract boolean partOfMask(int x, int y, int z, BlockState currentState);
@Override @Override
public boolean inSchematic(int x, int y, int z, IBlockState currentState) { public boolean inSchematic(int x, int y, int z, BlockState currentState) {
return schematic.inSchematic(x, y, z, currentState) && partOfMask(x, y, z, currentState); return schematic.inSchematic(x, y, z, currentState) && partOfMask(x, y, z, currentState);
} }
@Override @Override
public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) { public BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) {
return schematic.desiredState(x, y, z, current, approxPlaceable); return schematic.desiredState(x, y, z, current, approxPlaceable);
} }
} }
@@ -18,7 +18,7 @@
package baritone.api.schematic; package baritone.api.schematic;
import baritone.api.utils.BlockOptionalMetaLookup; import baritone.api.utils.BlockOptionalMetaLookup;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
public class ReplaceSchematic extends MaskSchematic { public class ReplaceSchematic extends MaskSchematic {
@@ -32,7 +32,7 @@ public class ReplaceSchematic extends MaskSchematic {
} }
@Override @Override
protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { protected boolean partOfMask(int x, int y, int z, BlockState currentState) {
if (cache[x][y][z] == null) { if (cache[x][y][z] == null) {
cache[x][y][z] = filter.has(currentState); cache[x][y][z] = filter.has(currentState);
} }
@@ -17,7 +17,7 @@
package baritone.api.schematic; package baritone.api.schematic;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
public class ShellSchematic extends MaskSchematic { public class ShellSchematic extends MaskSchematic {
@@ -26,7 +26,7 @@ public class ShellSchematic extends MaskSchematic {
} }
@Override @Override
protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { protected boolean partOfMask(int x, int y, int z, BlockState currentState) {
return x == 0 || y == 0 || z == 0 || x == widthX() - 1 || y == heightY() - 1 || z == lengthZ() - 1; return x == 0 || y == 0 || z == 0 || x == widthX() - 1 || y == heightY() - 1 || z == lengthZ() - 1;
} }
} }
@@ -17,7 +17,7 @@
package baritone.api.schematic; package baritone.api.schematic;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
public class WallsSchematic extends MaskSchematic { public class WallsSchematic extends MaskSchematic {
@@ -26,7 +26,7 @@ public class WallsSchematic extends MaskSchematic {
} }
@Override @Override
protected boolean partOfMask(int x, int y, int z, IBlockState currentState) { protected boolean partOfMask(int x, int y, int z, BlockState currentState) {
return x == 0 || z == 0 || x == widthX() - 1 || z == lengthZ() - 1; return x == 0 || z == 0 || x == widthX() - 1 || z == lengthZ() - 1;
} }
} }
@@ -18,7 +18,7 @@
package baritone.api.selection; package baritone.api.selection;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
@@ -65,7 +65,7 @@ public interface ISelection {
* @param blocks How many blocks to expand it. * @param blocks How many blocks to expand it.
* @return A new selection, expanded as specified. * @return A new selection, expanded as specified.
*/ */
ISelection expand(EnumFacing direction, int blocks); ISelection expand(Direction direction, int blocks);
/** /**
* Returns a new {@link ISelection} contracted in the specified direction by the specified number of blocks. * Returns a new {@link ISelection} contracted in the specified direction by the specified number of blocks.
@@ -77,7 +77,7 @@ public interface ISelection {
* @param blocks How many blocks to contract it. * @param blocks How many blocks to contract it.
* @return A new selection, contracted as specified. * @return A new selection, contracted as specified.
*/ */
ISelection contract(EnumFacing direction, int blocks); ISelection contract(Direction direction, int blocks);
/** /**
* Returns a new {@link ISelection} shifted in the specified direction by the specified number of blocks. This moves * Returns a new {@link ISelection} shifted in the specified direction by the specified number of blocks. This moves
@@ -87,5 +87,5 @@ public interface ISelection {
* @param blocks How many blocks to shift it. * @param blocks How many blocks to shift it.
* @return A new selection, shifted as specified. * @return A new selection, shifted as specified.
*/ */
ISelection shift(EnumFacing direction, int blocks); ISelection shift(Direction direction, int blocks);
} }
@@ -18,7 +18,7 @@
package baritone.api.selection; package baritone.api.selection;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
/** /**
* The selection manager handles setting Baritone's selections. You can set the selection here, as well as retrieving * The selection manager handles setting Baritone's selections. You can set the selection here, as well as retrieving
@@ -87,7 +87,7 @@ public interface ISelectionManager {
* @param blocks How many blocks to expand it. * @param blocks How many blocks to expand it.
* @return The new selection, expanded as specified. * @return The new selection, expanded as specified.
*/ */
ISelection expand(ISelection selection, EnumFacing direction, int blocks); ISelection expand(ISelection selection, Direction direction, int blocks);
/** /**
* Replaces the specified {@link ISelection} with one contracted in the specified direction by the specified number * Replaces the specified {@link ISelection} with one contracted in the specified direction by the specified number
@@ -101,7 +101,7 @@ public interface ISelectionManager {
* @param blocks How many blocks to contract it. * @param blocks How many blocks to contract it.
* @return The new selection, contracted as specified. * @return The new selection, contracted as specified.
*/ */
ISelection contract(ISelection selection, EnumFacing direction, int blocks); ISelection contract(ISelection selection, Direction direction, int blocks);
/** /**
* Replaces the specified {@link ISelection} with one shifted in the specified direction by the specified number of * Replaces the specified {@link ISelection} with one shifted in the specified direction by the specified number of
@@ -112,5 +112,5 @@ public interface ISelectionManager {
* @param blocks How many blocks to shift it. * @param blocks How many blocks to shift it.
* @return The new selection, shifted as specified. * @return The new selection, shifted as specified.
*/ */
ISelection shift(ISelection selection, EnumFacing direction, int blocks); ISelection shift(ISelection selection, Direction direction, int blocks);
} }
@@ -17,7 +17,7 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
@@ -120,10 +120,10 @@ public final class BetterBlockPos extends BlockPos {
// this is unimaginably faster than blockpos.up // this is unimaginably faster than blockpos.up
// that literally calls // that literally calls
// this.up(1) // this.up(1)
// which calls this.offset(EnumFacing.UP, 1) // which calls this.offset(Direction.UP, 1)
// which does return n == 0 ? this : new BlockPos(this.getX() + facing.getXOffset() * n, this.getY() + facing.getYOffset() * n, this.getZ() + facing.getZOffset() * n); // which does return n == 0 ? this : new BlockPos(this.getX() + facing.getXOffset() * n, this.getY() + facing.getYOffset() * n, this.getZ() + facing.getZOffset() * n);
// how many function calls is that? up(), up(int), offset(EnumFacing, int), new BlockPos, getX, getXOffset, getY, getYOffset, getZ, getZOffset // how many function calls is that? up(), up(int), offset(Direction, int), new BlockPos, getX, getXOffset, getY, getYOffset, getZ, getZOffset
// that's ten. // that's ten.
// this is one function call. // this is one function call.
return new BetterBlockPos(x, y + 1, z); return new BetterBlockPos(x, y + 1, z);
@@ -148,13 +148,13 @@ public final class BetterBlockPos extends BlockPos {
} }
@Override @Override
public BetterBlockPos offset(EnumFacing dir) { public BetterBlockPos offset(Direction dir) {
Vec3i vec = dir.getDirectionVec(); Vec3i vec = dir.getDirectionVec();
return new BetterBlockPos(x + vec.getX(), y + vec.getY(), z + vec.getZ()); return new BetterBlockPos(x + vec.getX(), y + vec.getY(), z + vec.getZ());
} }
@Override @Override
public BetterBlockPos offset(EnumFacing dir, int dist) { public BetterBlockPos offset(Direction dir, int dist) {
if (dist == 0) { if (dist == 0) {
return this; return this;
} }
@@ -19,30 +19,40 @@ package baritone.api.utils;
import baritone.api.utils.accessor.IItemStack; import baritone.api.utils.accessor.IItemStack;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import io.netty.util.concurrent.ThreadPerTaskExecutor;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.resources.*;
import net.minecraft.state.IProperty; import net.minecraft.state.IProperty;
import net.minecraft.state.properties.*; import net.minecraft.state.properties.*;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry; import net.minecraft.util.Unit;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.storage.loot.*;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.regex.MatchResult; import java.util.regex.MatchResult;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
public final class BlockOptionalMeta { public final class BlockOptionalMeta {
private final Block block; private final Block block;
private final Set<IBlockState> blockstates; private final Set<BlockState> blockstates;
private final ImmutableSet<Integer> stateHashes; private final ImmutableSet<Integer> stateHashes;
private final ImmutableSet<Integer> stackHashes; private final ImmutableSet<Integer> stackHashes;
private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$");
private static final Map<Object, Object> normalizations; private static final Map<Object, Object> normalizations;
private static LootTableManager manager;
private static Map<Block, List<Item>> drops = new HashMap<>();
public BlockOptionalMeta(@Nonnull Block block) { public BlockOptionalMeta(@Nonnull Block block) {
this.block = block; this.block = block;
@@ -62,11 +72,11 @@ public final class BlockOptionalMeta {
ResourceLocation id = new ResourceLocation(matchResult.group(1)); ResourceLocation id = new ResourceLocation(matchResult.group(1));
if (!IRegistry.BLOCK.containsKey(id)) { if (!Registry.BLOCK.containsKey(id)) {
throw new IllegalArgumentException("Invalid block ID"); throw new IllegalArgumentException("Invalid block ID");
} }
block = IRegistry.BLOCK.get(id); block = Registry.BLOCK.getValue(id).orElse(null);
blockstates = getStates(block); blockstates = getStates(block);
stateHashes = getStateHashes(blockstates); stateHashes = getStateHashes(blockstates);
stackHashes = getStackHashes(blockstates); stackHashes = getStackHashes(blockstates);
@@ -75,8 +85,8 @@ public final class BlockOptionalMeta {
static { static {
Map<Object, Object> _normalizations = new HashMap<>(); Map<Object, Object> _normalizations = new HashMap<>();
Consumer<Enum> put = instance -> _normalizations.put(instance.getClass(), instance); Consumer<Enum> put = instance -> _normalizations.put(instance.getClass(), instance);
put.accept(EnumFacing.NORTH); put.accept(Direction.NORTH);
put.accept(EnumFacing.Axis.Y); put.accept(Direction.Axis.Y);
put.accept(Half.BOTTOM); put.accept(Half.BOTTOM);
put.accept(StairsShape.STRAIGHT); put.accept(StairsShape.STRAIGHT);
put.accept(AttachFace.FLOOR); put.accept(AttachFace.FLOOR);
@@ -85,80 +95,80 @@ public final class BlockOptionalMeta {
put.accept(DoorHingeSide.LEFT); put.accept(DoorHingeSide.LEFT);
put.accept(BedPart.HEAD); put.accept(BedPart.HEAD);
put.accept(RailShape.NORTH_SOUTH); put.accept(RailShape.NORTH_SOUTH);
_normalizations.put(BlockBanner.ROTATION, 0); _normalizations.put(BannerBlock.ROTATION, 0);
_normalizations.put(BlockBed.OCCUPIED, false); _normalizations.put(BedBlock.OCCUPIED, false);
_normalizations.put(BlockBrewingStand.HAS_BOTTLE[0], false); _normalizations.put(BrewingStandBlock.HAS_BOTTLE[0], false);
_normalizations.put(BlockBrewingStand.HAS_BOTTLE[1], false); _normalizations.put(BrewingStandBlock.HAS_BOTTLE[1], false);
_normalizations.put(BlockBrewingStand.HAS_BOTTLE[2], false); _normalizations.put(BrewingStandBlock.HAS_BOTTLE[2], false);
_normalizations.put(BlockButton.POWERED, false); _normalizations.put(AbstractButtonBlock.POWERED, false);
// _normalizations.put(BlockCactus.AGE, 0); // _normalizations.put(BlockCactus.AGE, 0);
// _normalizations.put(BlockCauldron.LEVEL, 0); // _normalizations.put(BlockCauldron.LEVEL, 0);
// _normalizations.put(BlockChorusFlower.AGE, 0); // _normalizations.put(BlockChorusFlower.AGE, 0);
_normalizations.put(BlockChorusPlant.NORTH, false); _normalizations.put(ChorusPlantBlock.NORTH, false);
_normalizations.put(BlockChorusPlant.EAST, false); _normalizations.put(ChorusPlantBlock.EAST, false);
_normalizations.put(BlockChorusPlant.SOUTH, false); _normalizations.put(ChorusPlantBlock.SOUTH, false);
_normalizations.put(BlockChorusPlant.WEST, false); _normalizations.put(ChorusPlantBlock.WEST, false);
_normalizations.put(BlockChorusPlant.UP, false); _normalizations.put(ChorusPlantBlock.UP, false);
_normalizations.put(BlockChorusPlant.DOWN, false); _normalizations.put(ChorusPlantBlock.DOWN, false);
// _normalizations.put(BlockCocoa.AGE, 0); // _normalizations.put(BlockCocoa.AGE, 0);
// _normalizations.put(BlockCrops.AGE, 0); // _normalizations.put(BlockCrops.AGE, 0);
_normalizations.put(BlockDirtSnowy.SNOWY, false); _normalizations.put(SnowyDirtBlock.SNOWY, false);
_normalizations.put(BlockDoor.OPEN, false); _normalizations.put(DoorBlock.OPEN, false);
_normalizations.put(BlockDoor.POWERED, false); _normalizations.put(DoorBlock.POWERED, false);
// _normalizations.put(BlockFarmland.MOISTURE, 0); // _normalizations.put(BlockFarmland.MOISTURE, 0);
_normalizations.put(BlockFence.NORTH, false); _normalizations.put(FenceBlock.NORTH, false);
_normalizations.put(BlockFence.EAST, false); _normalizations.put(FenceBlock.EAST, false);
_normalizations.put(BlockFence.WEST, false); _normalizations.put(FenceBlock.WEST, false);
_normalizations.put(BlockFence.SOUTH, false); _normalizations.put(FenceBlock.SOUTH, false);
// _normalizations.put(BlockFenceGate.POWERED, false); // _normalizations.put(BlockFenceGate.POWERED, false);
// _normalizations.put(BlockFenceGate.IN_WALL, false); // _normalizations.put(BlockFenceGate.IN_WALL, false);
_normalizations.put(BlockFire.AGE, 0); _normalizations.put(FireBlock.AGE, 0);
_normalizations.put(BlockFire.NORTH, false); _normalizations.put(FireBlock.NORTH, false);
_normalizations.put(BlockFire.EAST, false); _normalizations.put(FireBlock.EAST, false);
_normalizations.put(BlockFire.SOUTH, false); _normalizations.put(FireBlock.SOUTH, false);
_normalizations.put(BlockFire.WEST, false); _normalizations.put(FireBlock.WEST, false);
_normalizations.put(BlockFire.UP, false); _normalizations.put(FireBlock.UP, false);
// _normalizations.put(BlockFrostedIce.AGE, 0); // _normalizations.put(BlockFrostedIce.AGE, 0);
_normalizations.put(BlockGrass.SNOWY, false); _normalizations.put(GrassBlock.SNOWY, false);
// _normalizations.put(BlockHopper.ENABLED, true); // _normalizations.put(BlockHopper.ENABLED, true);
// _normalizations.put(BlockLever.POWERED, false); // _normalizations.put(BlockLever.POWERED, false);
// _normalizations.put(BlockLiquid.LEVEL, 0); // _normalizations.put(BlockLiquid.LEVEL, 0);
// _normalizations.put(BlockMycelium.SNOWY, false); // _normalizations.put(BlockMycelium.SNOWY, false);
// _normalizations.put(BlockNetherWart.AGE, false); // _normalizations.put(BlockNetherWart.AGE, false);
_normalizations.put(BlockLeaves.DISTANCE, false); _normalizations.put(LeavesBlock.DISTANCE, false);
// _normalizations.put(BlockLeaves.DECAYABLE, false); // _normalizations.put(BlockLeaves.DECAYABLE, false);
// _normalizations.put(BlockObserver.POWERED, false); // _normalizations.put(BlockObserver.POWERED, false);
_normalizations.put(BlockPane.NORTH, false); _normalizations.put(PaneBlock.NORTH, false);
_normalizations.put(BlockPane.EAST, false); _normalizations.put(PaneBlock.EAST, false);
_normalizations.put(BlockPane.WEST, false); _normalizations.put(PaneBlock.WEST, false);
_normalizations.put(BlockPane.SOUTH, false); _normalizations.put(PaneBlock.SOUTH, false);
// _normalizations.put(BlockPistonBase.EXTENDED, false); // _normalizations.put(BlockPistonBase.EXTENDED, false);
// _normalizations.put(BlockPressurePlate.POWERED, false); // _normalizations.put(BlockPressurePlate.POWERED, false);
// _normalizations.put(BlockPressurePlateWeighted.POWER, false); // _normalizations.put(BlockPressurePlateWeighted.POWER, false);
// _normalizations.put(BlockRailDetector.POWERED, false); // _normalizations.put(BlockRailDetector.POWERED, false);
// _normalizations.put(BlockRailPowered.POWERED, false); // _normalizations.put(BlockRailPowered.POWERED, false);
_normalizations.put(BlockRedstoneWire.NORTH, false); _normalizations.put(RedstoneWireBlock.NORTH, false);
_normalizations.put(BlockRedstoneWire.EAST, false); _normalizations.put(RedstoneWireBlock.EAST, false);
_normalizations.put(BlockRedstoneWire.SOUTH, false); _normalizations.put(RedstoneWireBlock.SOUTH, false);
_normalizations.put(BlockRedstoneWire.WEST, false); _normalizations.put(RedstoneWireBlock.WEST, false);
// _normalizations.put(BlockReed.AGE, false); // _normalizations.put(BlockReed.AGE, false);
_normalizations.put(BlockSapling.STAGE, 0); _normalizations.put(SaplingBlock.STAGE, 0);
_normalizations.put(BlockStandingSign.ROTATION, 0); _normalizations.put(StandingSignBlock.ROTATION, 0);
_normalizations.put(BlockStem.AGE, 0); _normalizations.put(StemBlock.AGE, 0);
_normalizations.put(BlockTripWire.NORTH, false); _normalizations.put(TripWireBlock.NORTH, false);
_normalizations.put(BlockTripWire.EAST, false); _normalizations.put(TripWireBlock.EAST, false);
_normalizations.put(BlockTripWire.WEST, false); _normalizations.put(TripWireBlock.WEST, false);
_normalizations.put(BlockTripWire.SOUTH, false); _normalizations.put(TripWireBlock.SOUTH, false);
_normalizations.put(BlockVine.NORTH, false); _normalizations.put(VineBlock.NORTH, false);
_normalizations.put(BlockVine.EAST, false); _normalizations.put(VineBlock.EAST, false);
_normalizations.put(BlockVine.SOUTH, false); _normalizations.put(VineBlock.SOUTH, false);
_normalizations.put(BlockVine.WEST, false); _normalizations.put(VineBlock.WEST, false);
_normalizations.put(BlockVine.UP, false); _normalizations.put(VineBlock.UP, false);
_normalizations.put(BlockWall.UP, false); _normalizations.put(WallBlock.UP, false);
_normalizations.put(BlockWall.NORTH, false); _normalizations.put(WallBlock.NORTH, false);
_normalizations.put(BlockWall.EAST, false); _normalizations.put(WallBlock.EAST, false);
_normalizations.put(BlockWall.WEST, false); _normalizations.put(WallBlock.WEST, false);
_normalizations.put(BlockWall.SOUTH, false); _normalizations.put(WallBlock.SOUTH, false);
normalizations = Collections.unmodifiableMap(_normalizations); normalizations = Collections.unmodifiableMap(_normalizations);
} }
@@ -172,8 +182,8 @@ public final class BlockOptionalMeta {
return (C) value; return (C) value;
} }
public static IBlockState normalize(IBlockState state) { public static BlockState normalize(BlockState state) {
IBlockState newState = state; BlockState newState = state;
for (IProperty<?> property : state.getProperties()) { for (IProperty<?> property : state.getProperties()) {
Class<?> valueClass = property.getValueClass(); Class<?> valueClass = property.getValueClass();
@@ -204,30 +214,30 @@ public final class BlockOptionalMeta {
return newState; return newState;
} }
public static int stateMeta(IBlockState state) { public static int stateMeta(BlockState state) {
return state.hashCode(); return state.hashCode();
} }
private static Set<IBlockState> getStates(@Nonnull Block block) { private static Set<BlockState> getStates(@Nonnull Block block) {
return new HashSet<>(block.getStateContainer().getValidStates()); return new HashSet<>(block.getStateContainer().getValidStates());
} }
private static ImmutableSet<Integer> getStateHashes(Set<IBlockState> blockstates) { private static ImmutableSet<Integer> getStateHashes(Set<BlockState> blockstates) {
return ImmutableSet.copyOf( return ImmutableSet.copyOf(
blockstates.stream() blockstates.stream()
.map(IBlockState::hashCode) .map(BlockState::hashCode)
.toArray(Integer[]::new) .toArray(Integer[]::new)
); );
} }
private static ImmutableSet<Integer> getStackHashes(Set<IBlockState> blockstates) { private static ImmutableSet<Integer> getStackHashes(Set<BlockState> blockstates) {
//noinspection ConstantConditions //noinspection ConstantConditions
return ImmutableSet.copyOf( return ImmutableSet.copyOf(
blockstates.stream() blockstates.stream()
.map(state -> new ItemStack( .flatMap(state -> drops(state.getBlock())
state.getBlock().getItemDropped(state, null, null, 0).asItem(), .stream()
1 .map(item -> new ItemStack(item, 1))
)) )
.map(stack -> ((IItemStack) (Object) stack).getBaritoneHash()) .map(stack -> ((IItemStack) (Object) stack).getBaritoneHash())
.toArray(Integer[]::new) .toArray(Integer[]::new)
); );
@@ -241,7 +251,7 @@ public final class BlockOptionalMeta {
return block == this.block; return block == this.block;
} }
public boolean matches(@Nonnull IBlockState blockstate) { public boolean matches(@Nonnull BlockState blockstate) {
Block block = blockstate.getBlock(); Block block = blockstate.getBlock();
return block == this.block && stateHashes.contains(blockstate.hashCode()); return block == this.block && stateHashes.contains(blockstate.hashCode());
} }
@@ -260,11 +270,43 @@ public final class BlockOptionalMeta {
return String.format("BlockOptionalMeta{block=%s}", block); return String.format("BlockOptionalMeta{block=%s}", block);
} }
public IBlockState getAnyBlockState() { public BlockState getAnyBlockState() {
if (blockstates.size() > 0) { if (blockstates.size() > 0) {
return blockstates.iterator().next(); return blockstates.iterator().next();
} }
return null; return null;
} }
public static LootTableManager getManager() {
if (manager == null) {
ResourcePackList rpl = new ResourcePackList<>(ResourcePackInfo::new);
rpl.addPackFinder(new ServerPackFinder());
rpl.reloadPacksFromFinders();
IResourcePack thePack = ((ResourcePackInfo) rpl.getAllPacks().iterator().next()).getResourcePack();
IReloadableResourceManager resourceManager = new SimpleReloadableResourceManager(ResourcePackType.SERVER_DATA, null);
manager = new LootTableManager();
resourceManager.addReloadListener(manager);
try {
resourceManager.reloadResourcesAndThen(new ThreadPerTaskExecutor(Thread::new), new ThreadPerTaskExecutor(Thread::new), Collections.singletonList(thePack), CompletableFuture.completedFuture(Unit.INSTANCE)).get();
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
return manager;
}
private static List<Item> drops(Block b) {
if (!Minecraft.getInstance().isOnExecutionThread()) {
throw new IllegalStateException();
}
return drops.computeIfAbsent(b, block -> {
ResourceLocation lootTableLocation = block.getLootTable();
if (lootTableLocation == LootTables.EMPTY) {
return Collections.emptyList();
} else {
return getManager().getLootTableFromLocation(lootTableLocation).generate(new LootContext.Builder(null).withRandom(new Random()).withParameter(LootParameters.POSITION, BlockPos.ZERO).withParameter(LootParameters.TOOL, ItemStack.EMPTY).withNullableParameter(LootParameters.BLOCK_ENTITY, null).withParameter(LootParameters.BLOCK_STATE, block.getDefaultState()).build(LootParameterSets.BLOCK)).stream().map(ItemStack::getItem).collect(Collectors.toList());
}
});
}
} }
@@ -18,7 +18,7 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import java.util.Arrays; import java.util.Arrays;
@@ -61,7 +61,7 @@ public class BlockOptionalMetaLookup {
return false; return false;
} }
public boolean has(IBlockState state) { public boolean has(BlockState state) {
for (BlockOptionalMeta bom : boms) { for (BlockOptionalMeta bom : boms) {
if (bom.matches(state)) { if (bom.matches(state)) {
return true; return true;
@@ -19,7 +19,7 @@ package baritone.api.utils;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry; import net.minecraft.util.registry.Registry;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -29,7 +29,7 @@ public class BlockUtils {
private static transient Map<String, Block> resourceCache = new HashMap<>(); private static transient Map<String, Block> resourceCache = new HashMap<>();
public static String blockToString(Block block) { public static String blockToString(Block block) {
ResourceLocation loc = IRegistry.BLOCK.getKey(block); ResourceLocation loc = Registry.BLOCK.getKey(block);
String name = loc.getPath(); // normally, only write the part after the minecraft: String name = loc.getPath(); // normally, only write the part after the minecraft:
if (!loc.getNamespace().equals("minecraft")) { if (!loc.getNamespace().equals("minecraft")) {
// Baritone is running on top of forge with mods installed, perhaps? // Baritone is running on top of forge with mods installed, perhaps?
@@ -57,7 +57,7 @@ public class BlockUtils {
if (resourceCache.containsKey(name)) { if (resourceCache.containsKey(name)) {
return null; // cached as null return null; // cached as null
} }
block = IRegistry.BLOCK.get(ResourceLocation.tryCreate(name.contains(":") ? name : "minecraft:" + name)); block = Registry.BLOCK.getValue(ResourceLocation.tryCreate(name.contains(":") ? name : "minecraft:" + name)).orElse(null);
Map<String, Block> copy = new HashMap<>(resourceCache); // read only copy is safe, wont throw concurrentmodification Map<String, Block> copy = new HashMap<>(resourceCache); // read only copy is safe, wont throw concurrentmodification
copy.put(name, block); copy.put(name, block);
resourceCache = copy; resourceCache = copy;
+7 -7
View File
@@ -20,7 +20,7 @@ package baritone.api.utils;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import java.util.Arrays; import java.util.Arrays;
@@ -47,11 +47,11 @@ public interface Helper {
static ITextComponent getPrefix() { static ITextComponent getPrefix() {
// Inner text component // Inner text component
ITextComponent baritone = new TextComponentString(BaritoneAPI.getSettings().shortBaritonePrefix.value ? "B" : "Baritone"); ITextComponent baritone = new StringTextComponent(BaritoneAPI.getSettings().shortBaritonePrefix.value ? "B" : "Baritone");
baritone.getStyle().setColor(TextFormatting.LIGHT_PURPLE); baritone.getStyle().setColor(TextFormatting.LIGHT_PURPLE);
// Outer brackets // Outer brackets
ITextComponent prefix = new TextComponentString(""); ITextComponent prefix = new StringTextComponent("");
prefix.getStyle().setColor(TextFormatting.DARK_PURPLE); prefix.getStyle().setColor(TextFormatting.DARK_PURPLE);
prefix.appendText("["); prefix.appendText("[");
prefix.appendSibling(baritone); prefix.appendSibling(baritone);
@@ -80,11 +80,11 @@ public interface Helper {
* @param components The components to send * @param components The components to send
*/ */
default void logDirect(ITextComponent... components) { default void logDirect(ITextComponent... components) {
ITextComponent component = new TextComponentString(""); ITextComponent component = new StringTextComponent("");
component.appendSibling(getPrefix()); component.appendSibling(getPrefix());
component.appendSibling(new TextComponentString(" ")); component.appendSibling(new StringTextComponent(" "));
Arrays.asList(components).forEach(component::appendSibling); Arrays.asList(components).forEach(component::appendSibling);
mc.addScheduledTask(() -> BaritoneAPI.getSettings().logger.value.accept(component)); mc.execute(() -> BaritoneAPI.getSettings().logger.value.accept(component));
} }
/** /**
@@ -96,7 +96,7 @@ public interface Helper {
*/ */
default void logDirect(String message, TextFormatting color) { default void logDirect(String message, TextFormatting color) {
Stream.of(message.split("\n")).forEach(line -> { Stream.of(message.split("\n")).forEach(line -> {
ITextComponent component = new TextComponentString(line.replace("\t", " ")); ITextComponent component = new StringTextComponent(line.replace("\t", " "));
component.getStyle().setColor(color); component.getStyle().setColor(color);
logDirect(component); logDirect(component);
}); });
@@ -18,15 +18,16 @@
package baritone.api.utils; package baritone.api.utils;
import baritone.api.cache.IWorldData; import baritone.api.cache.IWorldData;
import net.minecraft.block.BlockSlab; import net.minecraft.block.SlabBlock;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.*;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World; import net.minecraft.world.World;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/** /**
* @author Brady * @author Brady
@@ -34,12 +35,21 @@ import java.util.Optional;
*/ */
public interface IPlayerContext { public interface IPlayerContext {
EntityPlayerSP player(); ClientPlayerEntity player();
IPlayerController playerController(); IPlayerController playerController();
World world(); World world();
default Iterable<Entity> entities() {
return ((ClientWorld) world()).getAllEntities();
}
default Stream<Entity> entitiesStream() {
return StreamSupport.stream(entities().spliterator(), false);
}
IWorldData worldData(); IWorldData worldData();
RayTraceResult objectMouseOver(); RayTraceResult objectMouseOver();
@@ -57,7 +67,7 @@ public interface IPlayerContext {
// this does not impact performance at all since we're not null checking constantly // this does not impact performance at all since we're not null checking constantly
// if there is an exception, the only overhead is Java generating the exception object... so we can ignore it // if there is an exception, the only overhead is Java generating the exception object... so we can ignore it
try { try {
if (world().getBlockState(feet).getBlock() instanceof BlockSlab) { if (world().getBlockState(feet).getBlock() instanceof SlabBlock) {
return feet.up(); return feet.up();
} }
} catch (NullPointerException ignored) {} } catch (NullPointerException ignored) {}
@@ -84,8 +94,8 @@ public interface IPlayerContext {
*/ */
default Optional<BlockPos> getSelectedBlock() { default Optional<BlockPos> getSelectedBlock() {
RayTraceResult result = objectMouseOver(); RayTraceResult result = objectMouseOver();
if (result != null && result.type == RayTraceResult.Type.BLOCK) { if (result != null && result.getType() == RayTraceResult.Type.BLOCK) {
return Optional.of(result.getBlockPos()); return Optional.of(((BlockRayTraceResult) result).getPos());
} }
return Optional.empty(); return Optional.empty();
} }
@@ -101,8 +111,8 @@ public interface IPlayerContext {
*/ */
default Optional<Entity> getSelectedEntity() { default Optional<Entity> getSelectedEntity() {
RayTraceResult result = objectMouseOver(); RayTraceResult result = objectMouseOver();
if (result != null && result.type == RayTraceResult.Type.ENTITY) { if (result != null && result.getType() == RayTraceResult.Type.ENTITY) {
return Optional.of(result.entity); return Optional.of(((EntityRayTraceResult) result).getEntity());
} }
return Optional.empty(); return Optional.empty();
} }
@@ -17,15 +17,15 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.ClickType; import net.minecraft.inventory.container.ClickType;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult; import net.minecraft.util.ActionResultType;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.EnumHand; import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.world.GameType; import net.minecraft.world.GameType;
import net.minecraft.world.World; import net.minecraft.world.World;
@@ -39,19 +39,19 @@ public interface IPlayerController {
boolean hasBrokenBlock(); boolean hasBrokenBlock();
boolean onPlayerDamageBlock(BlockPos pos, EnumFacing side); boolean onPlayerDamageBlock(BlockPos pos, Direction side);
void resetBlockRemoving(); void resetBlockRemoving();
ItemStack windowClick(int windowId, int slotId, int mouseButton, ClickType type, EntityPlayer player); ItemStack windowClick(int windowId, int slotId, int mouseButton, ClickType type, PlayerEntity player);
GameType getGameType(); GameType getGameType();
EnumActionResult processRightClickBlock(EntityPlayerSP player, World world, BlockPos pos, EnumFacing direction, Vec3d vec, EnumHand hand); ActionResultType processRightClickBlock(ClientPlayerEntity player, World world, Hand hand, BlockRayTraceResult result);
EnumActionResult processRightClick(EntityPlayerSP player, World world, EnumHand hand); ActionResultType processRightClick(ClientPlayerEntity player, World world, Hand hand);
boolean clickBlock(BlockPos loc, EnumFacing face); boolean clickBlock(BlockPos loc, Direction face);
void setHittingBlock(boolean hittingBlock); void setHittingBlock(boolean hittingBlock);
@@ -18,7 +18,7 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.math.RayTraceFluidMode; import net.minecraft.util.math.RayTraceContext;
import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
@@ -48,6 +48,6 @@ public final class RayTraceUtils {
direction.y * blockReachDistance, direction.y * blockReachDistance,
direction.z * blockReachDistance direction.z * blockReachDistance
); );
return entity.world.rayTraceBlocks(start, end, RayTraceFluidMode.NEVER, false, true); return entity.world.rayTraceBlocks(new RayTraceContext(start, end, RayTraceContext.BlockMode.OUTLINE, RayTraceContext.FluidMode.NONE, entity));
} }
} }
@@ -19,15 +19,12 @@ package baritone.api.utils;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import net.minecraft.block.BlockFire; import net.minecraft.block.BlockState;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.FireBlock;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.*;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.math.shapes.VoxelShapes; import net.minecraft.util.math.shapes.VoxelShapes;
@@ -140,7 +137,7 @@ public final class RotationUtils {
* @param ctx Context for the viewing entity * @param ctx Context for the viewing entity
* @param pos The target block position * @param pos The target block position
* @return The optional rotation * @return The optional rotation
* @see #reachable(EntityPlayerSP, BlockPos, double) * @see #reachable(ClientPlayerEntity, BlockPos, double)
*/ */
public static Optional<Rotation> reachable(IPlayerContext ctx, BlockPos pos) { public static Optional<Rotation> reachable(IPlayerContext ctx, BlockPos pos) {
return reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()); return reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance());
@@ -158,7 +155,7 @@ public final class RotationUtils {
* @param blockReachDistance The block reach distance of the entity * @param blockReachDistance The block reach distance of the entity
* @return The optional rotation * @return The optional rotation
*/ */
public static Optional<Rotation> reachable(EntityPlayerSP entity, BlockPos pos, double blockReachDistance) { public static Optional<Rotation> reachable(ClientPlayerEntity entity, BlockPos pos, double blockReachDistance) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(entity); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(entity);
if (baritone.getPlayerContext().isLookingAt(pos)) { if (baritone.getPlayerContext().isLookingAt(pos)) {
/* /*
@@ -179,15 +176,15 @@ public final class RotationUtils {
return possibleRotation; return possibleRotation;
} }
IBlockState state = entity.world.getBlockState(pos); BlockState state = entity.world.getBlockState(pos);
VoxelShape shape = state.getShape(entity.world, pos); VoxelShape shape = state.getShape(entity.world, pos);
if (shape.isEmpty()) { if (shape.isEmpty()) {
shape = VoxelShapes.fullCube(); shape = VoxelShapes.fullCube();
} }
for (Vec3d sideOffset : BLOCK_SIDE_MULTIPLIERS) { for (Vec3d sideOffset : BLOCK_SIDE_MULTIPLIERS) {
double xDiff = shape.getStart(EnumFacing.Axis.X) * sideOffset.x + shape.getEnd(EnumFacing.Axis.X) * (1 - sideOffset.x); double xDiff = shape.getStart(Direction.Axis.X) * sideOffset.x + shape.getEnd(Direction.Axis.X) * (1 - sideOffset.x);
double yDiff = shape.getStart(EnumFacing.Axis.Y) * sideOffset.y + shape.getEnd(EnumFacing.Axis.Y) * (1 - sideOffset.y); double yDiff = shape.getStart(Direction.Axis.Y) * sideOffset.y + shape.getEnd(Direction.Axis.Y) * (1 - sideOffset.y);
double zDiff = shape.getStart(EnumFacing.Axis.Z) * sideOffset.z + shape.getEnd(EnumFacing.Axis.Z) * (1 - sideOffset.z); double zDiff = shape.getStart(Direction.Axis.Z) * sideOffset.z + shape.getEnd(Direction.Axis.Z) * (1 - sideOffset.z);
possibleRotation = reachableOffset(entity, pos, new Vec3d(pos).add(xDiff, yDiff, zDiff), blockReachDistance); possibleRotation = reachableOffset(entity, pos, new Vec3d(pos).add(xDiff, yDiff, zDiff), blockReachDistance);
if (possibleRotation.isPresent()) { if (possibleRotation.isPresent()) {
return possibleRotation; return possibleRotation;
@@ -211,11 +208,11 @@ public final class RotationUtils {
Rotation rotation = calcRotationFromVec3d(entity.getEyePosition(1.0F), offsetPos, new Rotation(entity.rotationYaw, entity.rotationPitch)); Rotation rotation = calcRotationFromVec3d(entity.getEyePosition(1.0F), offsetPos, new Rotation(entity.rotationYaw, entity.rotationPitch));
RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance); RayTraceResult result = RayTraceUtils.rayTraceTowards(entity, rotation, blockReachDistance);
//System.out.println(result); //System.out.println(result);
if (result != null && result.type == RayTraceResult.Type.BLOCK) { if (result != null && result.getType() == RayTraceResult.Type.BLOCK) {
if (result.getBlockPos().equals(pos)) { if (((BlockRayTraceResult) result).getPos().equals(pos)) {
return Optional.of(rotation); return Optional.of(rotation);
} }
if (entity.world.getBlockState(pos).getBlock() instanceof BlockFire && result.getBlockPos().equals(pos.down())) { if (entity.world.getBlockState(pos).getBlock() instanceof FireBlock && ((BlockRayTraceResult) result).getPos().equals(pos.down())) {
return Optional.of(rotation); return Optional.of(rotation);
} }
} }
@@ -22,10 +22,10 @@ import baritone.api.Settings;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
import net.minecraft.util.registry.IRegistry; import net.minecraft.util.registry.Registry;
import java.awt.*; import java.awt.*;
import java.io.BufferedReader; import java.io.BufferedReader;
@@ -218,7 +218,7 @@ public class SettingsUtil {
FLOAT(Float.class, Float::parseFloat), FLOAT(Float.class, Float::parseFloat),
LONG(Long.class, Long::parseLong), LONG(Long.class, Long::parseLong),
STRING(String.class, String::new), STRING(String.class, String::new),
ENUMFACING(EnumFacing.class, EnumFacing::byName), DIRECTION(Direction.class, Direction::byName),
COLOR( COLOR(
Color.class, Color.class,
str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])), str -> new Color(Integer.parseInt(str.split(",")[0]), Integer.parseInt(str.split(",")[1]), Integer.parseInt(str.split(",")[2])),
@@ -236,8 +236,8 @@ public class SettingsUtil {
), ),
ITEM( ITEM(
Item.class, Item.class,
str -> IRegistry.ITEM.get(new ResourceLocation(str.trim())), str -> Registry.ITEM.getOrDefault(new ResourceLocation(str.trim())), // TODO this now returns AIR on failure instead of null, is that an issue?
item -> IRegistry.ITEM.getKey(item).toString() item -> Registry.ITEM.getKey(item).toString()
), ),
LIST() { LIST() {
@Override @Override
@@ -17,10 +17,10 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.block.BlockFire; import net.minecraft.block.BlockState;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.FireBlock;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
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.util.math.shapes.VoxelShape; import net.minecraft.util.math.shapes.VoxelShape;
@@ -43,18 +43,18 @@ public final class VecUtils {
* @see #getBlockPosCenter(BlockPos) * @see #getBlockPosCenter(BlockPos)
*/ */
public static Vec3d calculateBlockCenter(World world, BlockPos pos) { public static Vec3d calculateBlockCenter(World world, BlockPos pos) {
IBlockState b = world.getBlockState(pos); BlockState b = world.getBlockState(pos);
VoxelShape shape = b.getCollisionShape(world, pos); VoxelShape shape = b.getCollisionShape(world, pos);
if (shape.isEmpty()) { if (shape.isEmpty()) {
return getBlockPosCenter(pos); return getBlockPosCenter(pos);
} }
double xDiff = (shape.getStart(EnumFacing.Axis.X) + shape.getEnd(EnumFacing.Axis.X)) / 2; double xDiff = (shape.getStart(Direction.Axis.X) + shape.getEnd(Direction.Axis.X)) / 2;
double yDiff = (shape.getStart(EnumFacing.Axis.Y) + shape.getEnd(EnumFacing.Axis.Y)) / 2; double yDiff = (shape.getStart(Direction.Axis.Y) + shape.getEnd(Direction.Axis.Y)) / 2;
double zDiff = (shape.getStart(EnumFacing.Axis.Z) + shape.getEnd(EnumFacing.Axis.Z)) / 2; double zDiff = (shape.getStart(Direction.Axis.Z) + shape.getEnd(Direction.Axis.Z)) / 2;
if (Double.isNaN(xDiff) || Double.isNaN(yDiff) || Double.isNaN(zDiff)) { if (Double.isNaN(xDiff) || Double.isNaN(yDiff) || Double.isNaN(zDiff)) {
throw new IllegalStateException(b + " " + pos + " " + shape); throw new IllegalStateException(b + " " + pos + " " + shape);
} }
if (b.getBlock() instanceof BlockFire) {//look at bottom of fire when putting it out if (b.getBlock() instanceof FireBlock) {//look at bottom of fire when putting it out
yDiff = 0; yDiff = 0;
} }
return new Vec3d( return new Vec3d(
@@ -19,7 +19,7 @@ package baritone.launch.mixins;
import baritone.utils.accessor.IBitArray; import baritone.utils.accessor.IBitArray;
import baritone.utils.accessor.IBlockStateContainer; import baritone.utils.accessor.IBlockStateContainer;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.util.BitArray; import net.minecraft.util.BitArray;
import net.minecraft.world.chunk.BlockStateContainer; import net.minecraft.world.chunk.BlockStateContainer;
import net.minecraft.world.chunk.IBlockStatePalette; import net.minecraft.world.chunk.IBlockStatePalette;
@@ -33,10 +33,10 @@ public abstract class MixinBlockStateContainer implements IBlockStateContainer {
protected BitArray storage; protected BitArray storage;
@Shadow @Shadow
protected IBlockStatePalette<IBlockState> palette; protected IBlockStatePalette<BlockState> palette;
@Override @Override
public IBlockState getAtPalette(int index) { public BlockState getAtPalette(int index) {
return palette.get(index); return palette.get(index);
} }
@@ -22,8 +22,8 @@ import baritone.api.event.events.TabCompleteEvent;
import com.mojang.brigadier.context.StringRange; import com.mojang.brigadier.context.StringRange;
import com.mojang.brigadier.suggestion.Suggestion; import com.mojang.brigadier.suggestion.Suggestion;
import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.Suggestions;
import net.minecraft.client.gui.GuiChat; import net.minecraft.client.gui.screen.ChatScreen;
import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.gui.widget.TextFieldWidget;
import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
@@ -40,11 +40,11 @@ import java.util.stream.Stream;
* @author Brady * @author Brady
* @since 10/9/2019 * @since 10/9/2019
*/ */
@Mixin(GuiChat.class) @Mixin(ChatScreen.class)
public class MixinGuiChat { public class MixinChatScreen {
@Shadow @Shadow
protected GuiTextField inputField; protected TextFieldWidget inputField;
@Shadow @Shadow
@Final @Final
@@ -0,0 +1,92 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.utils.accessor.IChunkArray;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import java.util.concurrent.atomic.AtomicReferenceArray;
@Mixin(targets = "net.minecraft.client.multiplayer.ClientChunkProvider$ChunkArray")
public abstract class MixinChunkArray implements IChunkArray {
@Shadow
private AtomicReferenceArray<Chunk> chunks;
@Shadow
private int viewDistance;
@Shadow
private int sideLength;
@Shadow
private int centerX;
@Shadow
private int centerZ;
@Shadow
private int loaded;
@Shadow
protected abstract boolean inView(int x, int z);
@Shadow
protected abstract int getIndex(int x, int z);
@Shadow
protected abstract void replace(int index, Chunk chunk);
@Override
public int centerX() {
return centerX;
}
@Override
public int centerZ() {
return centerZ;
}
@Override
public int viewDistance() {
return viewDistance;
}
@Override
public AtomicReferenceArray<Chunk> getChunks() {
return chunks;
}
@Override
public void copyFrom(IChunkArray other) {
centerX = other.centerX();
centerZ = other.centerZ();
AtomicReferenceArray<Chunk> copyingFrom = other.getChunks();
for (int k = 0; k < copyingFrom.length(); ++k) {
Chunk chunk = copyingFrom.get(k);
if (chunk != null) {
ChunkPos chunkpos = chunk.getPos();
if (inView(chunkpos.x, chunkpos.z)) {
int index = getIndex(chunkpos.x, chunkpos.z);
if (chunks.get(index) != null) {
throw new IllegalStateException("Doing this would mutate the client's REAL loaded chunks?!");
}
replace(index, chunk);
}
}
}
}
}
@@ -1,42 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.utils.accessor.IChunkProviderServer;
import net.minecraft.world.chunk.storage.IChunkLoader;
import net.minecraft.world.gen.ChunkProviderServer;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
/**
* @author Brady
* @since 9/4/2018
*/
@Mixin(ChunkProviderServer.class)
public class MixinChunkProviderServer implements IChunkProviderServer {
@Shadow
@Final
private IChunkLoader chunkLoader;
@Override
public IChunkLoader getChunkLoader() {
return this.chunkLoader;
}
}
@@ -1,55 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.Baritone;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ChunkRenderContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.chunk.RenderChunk;
import net.minecraft.util.math.BlockPos;
import org.lwjgl.opengl.GL14;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import static org.lwjgl.opengl.GL11.GL_ONE;
import static org.lwjgl.opengl.GL11.GL_ZERO;
import static org.lwjgl.opengl.GL14.GL_CONSTANT_ALPHA;
import static org.lwjgl.opengl.GL14.GL_ONE_MINUS_CONSTANT_ALPHA;
@Mixin(ChunkRenderContainer.class)
public class MixinChunkRenderContainer {
@Redirect( // avoid creating CallbackInfo at all costs; this is called 40k times per second
method = "preRenderChunk",
at = @At(
value = "INVOKE",
target = "net/minecraft/client/renderer/chunk/RenderChunk.getPosition()Lnet/minecraft/util/math/BlockPos;"
)
)
private BlockPos getPosition(RenderChunk renderChunkIn) {
if (Baritone.settings().renderCachedChunks.value && !Minecraft.getInstance().isSingleplayer() && Minecraft.getInstance().world.getChunk(renderChunkIn.getPosition()).isEmpty()) {
GlStateManager.enableAlphaTest();
GlStateManager.enableBlend();
GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.value);
GlStateManager.blendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO);
}
return renderChunkIn.getPosition();
}
}
@@ -1,57 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.utils.IPlayerContext;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.chunk.ChunkRenderWorker;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(ChunkRenderWorker.class)
public abstract class MixinChunkRenderWorker {
@Shadow
protected abstract boolean isChunkExisting(BlockPos pos, World worldIn);
@Redirect(
method = "processTask",
at = @At(
value = "INVOKE",
target = "net/minecraft/client/renderer/chunk/ChunkRenderWorker.isChunkExisting(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/world/World;)Z"
)
)
private boolean isChunkExisting(ChunkRenderWorker worker, BlockPos pos, World world) {
if (Baritone.settings().renderCachedChunks.value && !Minecraft.getInstance().isSingleplayer()) {
Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone();
IPlayerContext ctx = baritone.getPlayerContext();
if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) {
return baritone.bsi.isLoaded(pos.getX(), pos.getZ()) || this.isChunkExisting(pos, world);
}
}
return this.isChunkExisting(pos, world);
}
}
@@ -0,0 +1,61 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.utils.accessor.IChunkArray;
import baritone.utils.accessor.IClientChunkProvider;
import net.minecraft.client.multiplayer.ClientChunkProvider;
import net.minecraft.client.world.ClientWorld;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import java.lang.reflect.Field;
import java.util.Arrays;
@Mixin(ClientChunkProvider.class)
public class MixinClientChunkProvider implements IClientChunkProvider {
@Shadow
private ClientWorld world;
@Override
public ClientChunkProvider createThreadSafeCopy() {
IChunkArray arr = extractReferenceArray();
ClientChunkProvider result = new ClientChunkProvider(world, arr.viewDistance() - 3); // -3 because its adds 3 for no reason lmao
IChunkArray copyArr = ((IClientChunkProvider) result).extractReferenceArray();
copyArr.copyFrom(arr);
if (copyArr.viewDistance() != arr.viewDistance()) {
throw new IllegalStateException(copyArr.viewDistance() + " " + arr.viewDistance());
}
return result;
}
@Override
public IChunkArray extractReferenceArray() {
for (Field f : ClientChunkProvider.class.getDeclaredFields()) {
if (IChunkArray.class.isAssignableFrom(f.getType())) {
try {
return (IChunkArray) f.get(this);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
throw new RuntimeException(Arrays.toString(ClientChunkProvider.class.getDeclaredFields()));
}
}
@@ -21,10 +21,10 @@ import baritone.api.BaritoneAPI;
import baritone.api.IBaritone; 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.play.ClientPlayNetHandler;
import net.minecraft.network.play.server.SPacketChunkData; import net.minecraft.network.play.server.SChunkDataPacket;
import net.minecraft.network.play.server.SPacketCombatEvent; import net.minecraft.network.play.server.SCombatPacket;
import net.minecraft.network.play.server.SPacketUnloadChunk; import net.minecraft.network.play.server.SUnloadChunkPacket;
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;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
@@ -34,10 +34,11 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
* @author Brady * @author Brady
* @since 8/3/2018 * @since 8/3/2018
*/ */
@Mixin(NetHandlerPlayClient.class) @Mixin(ClientPlayNetHandler.class)
public class MixinNetHandlerPlayClient { public class MixinClientPlayNetHandler {
@Inject( // unused lol
/*@Inject(
method = "handleChunkData", method = "handleChunkData",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
@@ -57,15 +58,15 @@ public class MixinNetHandlerPlayClient {
); );
} }
} }
} }*/
@Inject( @Inject(
method = "handleChunkData", method = "handleChunkData",
at = @At("RETURN") at = @At("RETURN")
) )
private void postHandleChunkData(SPacketChunkData packetIn, CallbackInfo ci) { private void postHandleChunkData(SChunkDataPacket packetIn, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) { if (ibaritone.getPlayerContext().player().connection == (ClientPlayNetHandler) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent( ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent( new ChunkEvent(
EventState.POST, EventState.POST,
@@ -82,9 +83,9 @@ public class MixinNetHandlerPlayClient {
method = "processChunkUnload", method = "processChunkUnload",
at = @At("HEAD") at = @At("HEAD")
) )
private void preChunkUnload(SPacketUnloadChunk packet, CallbackInfo ci) { private void preChunkUnload(SUnloadChunkPacket packet, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) { if (ibaritone.getPlayerContext().player().connection == (ClientPlayNetHandler) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent( ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(EventState.PRE, ChunkEvent.Type.UNLOAD, packet.getX(), packet.getZ()) new ChunkEvent(EventState.PRE, ChunkEvent.Type.UNLOAD, packet.getX(), packet.getZ())
); );
@@ -96,9 +97,9 @@ public class MixinNetHandlerPlayClient {
method = "processChunkUnload", method = "processChunkUnload",
at = @At("RETURN") at = @At("RETURN")
) )
private void postChunkUnload(SPacketUnloadChunk packet, CallbackInfo ci) { private void postChunkUnload(SUnloadChunkPacket packet, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) { if (ibaritone.getPlayerContext().player().connection == (ClientPlayNetHandler) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent( ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent(EventState.POST, ChunkEvent.Type.UNLOAD, packet.getX(), packet.getZ()) new ChunkEvent(EventState.POST, ChunkEvent.Type.UNLOAD, packet.getX(), packet.getZ())
); );
@@ -110,12 +111,12 @@ public class MixinNetHandlerPlayClient {
method = "handleCombatEvent", method = "handleCombatEvent",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/Minecraft.displayGuiScreen(Lnet/minecraft/client/gui/GuiScreen;)V" target = "net/minecraft/client/Minecraft.displayGuiScreen(Lnet/minecraft/client/gui/screen/Screen;)V"
) )
) )
private void onPlayerDeath(SPacketCombatEvent packetIn, CallbackInfo ci) { private void onPlayerDeath(SCombatPacket packetIn, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) { if (ibaritone.getPlayerContext().player().connection == (ClientPlayNetHandler) (Object) this) {
ibaritone.getGameEventHandler().onPlayerDeath(); ibaritone.getGameEventHandler().onPlayerDeath();
} }
} }
@@ -24,9 +24,9 @@ import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.SprintStateEvent; import baritone.api.event.events.SprintStateEvent;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import baritone.behavior.LookBehavior; import baritone.behavior.LookBehavior;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.client.settings.KeyBinding; import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.player.PlayerCapabilities; import net.minecraft.entity.player.PlayerAbilities;
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;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
@@ -37,8 +37,8 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
* @author Brady * @author Brady
* @since 8/1/2018 * @since 8/1/2018
*/ */
@Mixin(EntityPlayerSP.class) @Mixin(ClientPlayerEntity.class)
public class MixinEntityPlayerSP { public class MixinClientPlayerEntity {
@Inject( @Inject(
method = "sendChatMessage", method = "sendChatMessage",
@@ -47,7 +47,7 @@ public class MixinEntityPlayerSP {
) )
private void sendChatMessage(String msg, CallbackInfo ci) { private void sendChatMessage(String msg, CallbackInfo ci) {
ChatEvent event = new ChatEvent(msg); ChatEvent event = new ChatEvent(msg);
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this);
if (baritone == null) { if (baritone == null) {
return; return;
} }
@@ -61,13 +61,13 @@ public class MixinEntityPlayerSP {
method = "tick", method = "tick",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/entity/EntityPlayerSP.isPassenger()Z", target = "net/minecraft/client/entity/player/ClientPlayerEntity.isPassenger()Z",
shift = At.Shift.BY, shift = At.Shift.BY,
by = -3 by = -3
) )
) )
private void onPreUpdate(CallbackInfo ci) { private void onPreUpdate(CallbackInfo ci) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this);
if (baritone != null) { if (baritone != null) {
baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.PRE)); baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.PRE));
} }
@@ -77,13 +77,13 @@ public class MixinEntityPlayerSP {
method = "tick", method = "tick",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/entity/EntityPlayerSP.onUpdateWalkingPlayer()V", target = "net/minecraft/client/entity/player/ClientPlayerEntity.onUpdateWalkingPlayer()V",
shift = At.Shift.BY, shift = At.Shift.BY,
by = 2 by = 2
) )
) )
private void onPostUpdate(CallbackInfo ci) { private void onPostUpdate(CallbackInfo ci) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this);
if (baritone != null) { if (baritone != null) {
baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST)); baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST));
} }
@@ -93,11 +93,11 @@ public class MixinEntityPlayerSP {
method = "livingTick", method = "livingTick",
at = @At( at = @At(
value = "FIELD", value = "FIELD",
target = "net/minecraft/entity/player/PlayerCapabilities.allowFlying:Z" target = "net/minecraft/entity/player/PlayerAbilities.allowFlying:Z"
) )
) )
private boolean isAllowFlying(PlayerCapabilities capabilities) { private boolean isAllowFlying(PlayerAbilities capabilities) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this);
if (baritone == null) { if (baritone == null) {
return capabilities.allowFlying; return capabilities.allowFlying;
} }
@@ -112,7 +112,7 @@ public class MixinEntityPlayerSP {
) )
) )
private boolean isKeyDown(KeyBinding keyBinding) { private boolean isKeyDown(KeyBinding keyBinding) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this);
if (baritone == null) { if (baritone == null) {
return keyBinding.isKeyDown(); return keyBinding.isKeyDown();
} }
@@ -135,7 +135,7 @@ public class MixinEntityPlayerSP {
) )
) )
private void updateRidden(CallbackInfo cb) { private void updateRidden(CallbackInfo cb) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this);
if (baritone != null) { if (baritone != null) {
((LookBehavior) baritone.getLookBehavior()).pig(); ((LookBehavior) baritone.getLookBehavior()).pig();
} }
@@ -0,0 +1,60 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.event.events.RotationMoveEvent;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Entity.class)
public class MixinEntity {
@Shadow
private float rotationYaw;
float yawRestore;
@Inject(
method = "moveRelative",
at = @At("HEAD")
)
private void moveRelativeHead(CallbackInfo info) {
this.yawRestore = this.rotationYaw;
// noinspection ConstantConditions
if (!ClientPlayerEntity.class.isInstance(this) || BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this) == null) {
return;
}
RotationMoveEvent motionUpdateRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw);
BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this).getGameEventHandler().onPlayerRotationMove(motionUpdateRotationEvent);
this.rotationYaw = motionUpdateRotationEvent.getYaw();
}
@Inject(
method = "moveRelative",
at = @At("RETURN")
)
private void moveRelativeReturn(CallbackInfo info) {
this.rotationYaw = this.yawRestore;
}
}
@@ -17,27 +17,32 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.utils.accessor.IAnvilChunkLoader; import baritone.utils.accessor.IEntityRenderManager;
import net.minecraft.world.chunk.storage.AnvilChunkLoader; import net.minecraft.client.renderer.entity.EntityRendererManager;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
import java.io.File; @Mixin(EntityRendererManager.class)
public class MixinEntityRenderManager implements IEntityRenderManager {
/**
* @author Brady
* @since 9/4/2018
*/
@Mixin(AnvilChunkLoader.class)
public class MixinAnvilChunkLoader implements IAnvilChunkLoader {
@Shadow @Shadow
@Final private double renderPosX;
private File chunkSaveLocation; @Shadow
private double renderPosY;
@Shadow
private double renderPosZ;
@Override @Override
public File getChunkSaveLocation() { public double renderPosX() {
return this.chunkSaveLocation; return renderPosX;
}
@Override
public double renderPosY() {
return renderPosY;
}
@Override
public double renderPosZ() {
return renderPosZ;
} }
} }
@@ -33,7 +33,7 @@ public class MixinGameRenderer {
method = "updateCameraAndRender(FJ)V", method = "updateCameraAndRender(FJ)V",
at = @At( at = @At(
value = "INVOKE_STRING", value = "INVOKE_STRING",
target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V", target = "Lnet/minecraft/profiler/IProfiler;endStartSection(Ljava/lang/String;)V",
args = {"ldc=hand"} args = {"ldc=hand"}
) )
) )
@@ -20,10 +20,11 @@ package baritone.launch.mixins;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.event.events.RotationMoveEvent; import baritone.api.event.events.RotationMoveEvent;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.EntityType; import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World; import net.minecraft.world.World;
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;
@@ -37,15 +38,15 @@ import static org.spongepowered.asm.lib.Opcodes.GETFIELD;
* @author Brady * @author Brady
* @since 9/10/2018 * @since 9/10/2018
*/ */
@Mixin(EntityLivingBase.class) @Mixin(LivingEntity.class)
public abstract class MixinEntityLivingBase extends Entity { public abstract class MixinLivingEntity extends Entity {
/** /**
* Event called to override the movement direction when jumping * Event called to override the movement direction when jumping
*/ */
private RotationMoveEvent jumpRotationEvent; private RotationMoveEvent jumpRotationEvent;
public MixinEntityLivingBase(EntityType<?> entityTypeIn, World worldIn) { public MixinLivingEntity(EntityType<?> entityTypeIn, World worldIn) {
super(entityTypeIn, worldIn); super(entityTypeIn, worldIn);
} }
@@ -55,8 +56,8 @@ public abstract class MixinEntityLivingBase extends Entity {
) )
private void preMoveRelative(CallbackInfo ci) { private void preMoveRelative(CallbackInfo ci) {
// noinspection ConstantConditions // noinspection ConstantConditions
if (EntityPlayerSP.class.isInstance(this)) { if (ClientPlayerEntity.class.isInstance(this)) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this);
if (baritone != null) { if (baritone != null) {
this.jumpRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.JUMP, this.rotationYaw); this.jumpRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.JUMP, this.rotationYaw);
baritone.getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent); baritone.getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent);
@@ -69,34 +70,15 @@ public abstract class MixinEntityLivingBase extends Entity {
at = @At( at = @At(
value = "FIELD", value = "FIELD",
opcode = GETFIELD, opcode = GETFIELD,
target = "net/minecraft/entity/EntityLivingBase.rotationYaw:F" target = "net/minecraft/entity/LivingEntity.rotationYaw:F"
) )
) )
private float overrideYaw(EntityLivingBase self) { private float overrideYaw(LivingEntity self) {
if (self instanceof EntityPlayerSP && BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this) != null) { if (self instanceof ClientPlayerEntity && BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this) != null) {
return this.jumpRotationEvent.getYaw(); return this.jumpRotationEvent.getYaw();
} }
return self.rotationYaw; return self.rotationYaw;
} }
@Redirect(
method = "travel",
at = @At(
value = "INVOKE",
target = "net/minecraft/entity/EntityLivingBase.moveRelative(FFFF)V"
)
)
private void travel(EntityLivingBase self, float strafe, float up, float forward, float friction) {
// noinspection ConstantConditions
if (!EntityPlayerSP.class.isInstance(this) || BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this) == null) {
moveRelative(strafe, up, forward, friction);
return;
}
RotationMoveEvent motionUpdateRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.MOTION_UPDATE, this.rotationYaw);
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(motionUpdateRotationEvent);
float originalYaw = this.rotationYaw;
this.rotationYaw = motionUpdateRotationEvent.getYaw();
this.moveRelative(strafe, up, forward, friction);
this.rotationYaw = originalYaw;
}
} }
@@ -0,0 +1,59 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.api.utils.BlockOptionalMeta;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.LootTableManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(LootContext.Builder.class)
public class MixinLootContext {
@Redirect(
method = "build",
at = @At(
value = "INVOKE",
target = "net/minecraft/world/server/ServerWorld.getServer()Lnet/minecraft/server/MinecraftServer;"
)
)
private MinecraftServer getServer(ServerWorld world) {
if (world == null) {
return null;
}
return world.getServer();
}
@Redirect(
method = "build",
at = @At(
value = "INVOKE",
target = "net/minecraft/server/MinecraftServer.getLootTableManager()Lnet/minecraft/world/storage/loot/LootTableManager;"
)
)
private LootTableManager getLootTableManager(MinecraftServer server) {
if (server == null) {
return BlockOptionalMeta.getManager();
}
return server.getLootTableManager();
}
}
@@ -25,13 +25,13 @@ import baritone.api.event.events.WorldEvent;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import baritone.utils.BaritoneAutoTest; import baritone.utils.BaritoneAutoTest;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.world.ClientWorld;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult; import net.minecraft.util.ActionResultType;
import net.minecraft.util.EnumHand; import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockRayTraceResult;
import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
@@ -49,9 +49,9 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
public class MixinMinecraft { public class MixinMinecraft {
@Shadow @Shadow
public EntityPlayerSP player; public ClientPlayerEntity player;
@Shadow @Shadow
public WorldClient world; public ClientWorld world;
@Inject( @Inject(
method = "init", method = "init",
@@ -77,7 +77,7 @@ public class MixinMinecraft {
at = @At( at = @At(
value = "FIELD", value = "FIELD",
opcode = Opcodes.GETFIELD, opcode = Opcodes.GETFIELD,
target = "net/minecraft/client/Minecraft.currentScreen:Lnet/minecraft/client/gui/GuiScreen;", target = "net/minecraft/client/Minecraft.currentScreen:Lnet/minecraft/client/gui/screen/Screen;",
ordinal = 5, ordinal = 5,
shift = At.Shift.BY, shift = At.Shift.BY,
by = -3 by = -3
@@ -96,10 +96,10 @@ public class MixinMinecraft {
} }
@Inject( @Inject(
method = "loadWorld(Lnet/minecraft/client/multiplayer/WorldClient;Lnet/minecraft/client/gui/GuiScreen;)V", method = "loadWorld(Lnet/minecraft/client/world/ClientWorld;)V",
at = @At("HEAD") at = @At("HEAD")
) )
private void preLoadWorld(WorldClient world, GuiScreen loadingScreen, CallbackInfo ci) { private void preLoadWorld(ClientWorld world, CallbackInfo ci) {
// If we're unloading the world but one doesn't exist, ignore it // If we're unloading the world but one doesn't exist, ignore it
if (this.world == null && world == null) { if (this.world == null && world == null) {
return; return;
@@ -116,10 +116,10 @@ public class MixinMinecraft {
} }
@Inject( @Inject(
method = "loadWorld(Lnet/minecraft/client/multiplayer/WorldClient;Lnet/minecraft/client/gui/GuiScreen;)V", method = "loadWorld(Lnet/minecraft/client/world/ClientWorld;)V",
at = @At("RETURN") at = @At("RETURN")
) )
private void postLoadWorld(WorldClient world, GuiScreen loadingScreen, CallbackInfo ci) { private void postLoadWorld(ClientWorld world, 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
// mc.world changing is only the primary baritone // mc.world changing is only the primary baritone
@@ -136,37 +136,24 @@ public class MixinMinecraft {
at = @At( at = @At(
value = "FIELD", value = "FIELD",
opcode = Opcodes.GETFIELD, opcode = Opcodes.GETFIELD,
target = "net/minecraft/client/gui/GuiScreen.allowUserInput:Z" target = "net/minecraft/client/gui/screen/Screen.passEvents:Z"
) )
) )
private boolean isAllowUserInput(GuiScreen screen) { private boolean passEvents(Screen screen) {
// allow user input is only the primary baritone // allow user input is only the primary baritone
return (BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().getCurrent() != null && player != null) || screen.allowUserInput; return (BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().getCurrent() != null && player != null) || screen.passEvents;
}
@Inject(
method = "clickMouse",
at = @At(
value = "INVOKE",
target = "net/minecraft/client/multiplayer/PlayerControllerMP.clickBlock(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/EnumFacing;)Z"
),
locals = LocalCapture.CAPTURE_FAILHARD
)
private void onBlockBreak(CallbackInfo ci, BlockPos pos) {
// clickMouse is only for the main player
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(pos, BlockInteractEvent.Type.START_BREAK));
} }
@Inject( @Inject(
method = "rightClickMouse", method = "rightClickMouse",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/entity/EntityPlayerSP.swingArm(Lnet/minecraft/util/EnumHand;)V" target = "net/minecraft/client/entity/player/ClientPlayerEntity.swingArm(Lnet/minecraft/util/Hand;)V"
), ),
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, Hand var1[], int var2, int var3, Hand enumhand, ItemStack itemstack, BlockRayTraceResult raytrace, int i, ActionResultType enumactionresult) {
// rightClickMouse is only for the main player // rightClickMouse is only for the main player
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(blockpos, BlockInteractEvent.Type.USE)); BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(raytrace.getPos(), BlockInteractEvent.Type.USE));
} }
} }
@@ -25,9 +25,9 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.GenericFutureListener;
import net.minecraft.network.EnumPacketDirection; import net.minecraft.network.IPacket;
import net.minecraft.network.NetworkManager; import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet; import net.minecraft.network.PacketDirection;
import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
@@ -47,14 +47,14 @@ public class MixinNetworkManager {
@Shadow @Shadow
@Final @Final
private EnumPacketDirection direction; private PacketDirection direction;
@Inject( @Inject(
method = "dispatchPacket", method = "dispatchPacket",
at = @At("HEAD") at = @At("HEAD")
) )
private void preDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>> futureListeners, CallbackInfo ci) { private void preDispatchPacket(IPacket<?> inPacket, final GenericFutureListener<? extends Future<? super Void>> futureListeners, CallbackInfo ci) {
if (this.direction != EnumPacketDirection.CLIENTBOUND) { if (this.direction != PacketDirection.CLIENTBOUND) {
return; return;
} }
@@ -69,8 +69,8 @@ public class MixinNetworkManager {
method = "dispatchPacket", method = "dispatchPacket",
at = @At("RETURN") at = @At("RETURN")
) )
private void postDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>> futureListeners, CallbackInfo ci) { private void postDispatchPacket(IPacket<?> inPacket, final GenericFutureListener<? extends Future<? super Void>> futureListeners, CallbackInfo ci) {
if (this.direction != EnumPacketDirection.CLIENTBOUND) { if (this.direction != PacketDirection.CLIENTBOUND) {
return; return;
} }
@@ -85,11 +85,11 @@ public class MixinNetworkManager {
method = "channelRead0", method = "channelRead0",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/network/NetworkManager.processPacket(Lnet/minecraft/network/Packet;Lnet/minecraft/network/INetHandler;)V" target = "net/minecraft/network/NetworkManager.processPacket(Lnet/minecraft/network/IPacket;Lnet/minecraft/network/INetHandler;)V"
) )
) )
private void preProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) { private void preProcessPacket(ChannelHandlerContext context, IPacket<?> packet, CallbackInfo ci) {
if (this.direction != EnumPacketDirection.CLIENTBOUND) { if (this.direction != PacketDirection.CLIENTBOUND) {
return; return;
} }
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
@@ -103,8 +103,8 @@ public class MixinNetworkManager {
method = "channelRead0", method = "channelRead0",
at = @At("RETURN") at = @At("RETURN")
) )
private void postProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) { private void postProcessPacket(ChannelHandlerContext context, IPacket<?> packet, CallbackInfo ci) {
if (!this.channel.isOpen() || this.direction != EnumPacketDirection.CLIENTBOUND) { if (!this.channel.isOpen() || this.direction != PacketDirection.CLIENTBOUND) {
return; return;
} }
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
@@ -18,14 +18,14 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.utils.accessor.IPlayerControllerMP; import baritone.utils.accessor.IPlayerControllerMP;
import net.minecraft.client.multiplayer.PlayerControllerMP; import net.minecraft.client.multiplayer.PlayerController;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(PlayerControllerMP.class) @Mixin(PlayerController.class)
public abstract class MixinPlayerControllerMP implements IPlayerControllerMP { public abstract class MixinPlayerController implements IPlayerControllerMP {
@Accessor @Accessor
@Override @Override
@@ -1,57 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.utils.IPlayerContext;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.chunk.RenderChunk;
import net.minecraft.client.renderer.chunk.RenderChunkCache;
import net.minecraft.util.math.BlockPos;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
/**
* @author Brady
* @since 1/29/2019
*/
@Mixin(RenderChunk.class)
public class MixinRenderChunk {
@Redirect(
method = "rebuildChunk",
at = @At(
value = "INVOKE",
target = "net/minecraft/client/renderer/chunk/RenderChunkCache.getBlockState(Lnet/minecraft/util/math/BlockPos;)Lnet/minecraft/block/state/IBlockState;"
)
)
private IBlockState getBlockState(RenderChunkCache chunkCache, BlockPos pos) {
if (Baritone.settings().renderCachedChunks.value && !Minecraft.getInstance().isSingleplayer()) {
Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone();
IPlayerContext ctx = baritone.getPlayerContext();
if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) {
return baritone.bsi.get0(pos);
}
}
return chunkCache.getBlockState(pos);
}
}
@@ -1,47 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.Baritone;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.chunk.RenderChunkCache;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(RenderChunkCache.class)
public class MixinRenderChunkCache {
@Redirect(
method = "generateCache",
at = @At(
value = "INVOKE",
target = "net/minecraft/world/chunk/Chunk.isEmptyBetween(II)Z"
)
)
private static boolean isEmpty(Chunk chunk, int yStart, int yEnd) {
if (!chunk.isEmptyBetween(yStart, yEnd)) {
return false;
}
if (chunk.isEmpty() && Baritone.settings().renderCachedChunks.value && Minecraft.getInstance().getIntegratedServer() == null) {
return false;
}
return true;
}
}
@@ -1,47 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.Baritone;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderList;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import static org.lwjgl.opengl.GL11.*;
@Mixin(RenderList.class)
public class MixinRenderList {
@Redirect( // avoid creating CallbackInfo at all costs; this is called 40k times per second
method = "renderChunkLayer",
at = @At(
value = "INVOKE",
target = "net/minecraft/client/renderer/GlStateManager.popMatrix()V"
)
)
private void popMatrix() {
if (Baritone.settings().renderCachedChunks.value && !Minecraft.getInstance().isSingleplayer()) {
// reset the blend func to normal (not dependent on constant alpha)
GlStateManager.blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
}
GlStateManager.popMatrix();
}
}
@@ -18,16 +18,16 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.utils.accessor.IGuiScreen; import baritone.utils.accessor.IGuiScreen;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.screen.Screen;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.gen.Invoker;
import java.net.URI; import java.net.URI;
@Mixin(GuiScreen.class) @Mixin(Screen.class)
public abstract class MixinGuiScreen implements IGuiScreen { public abstract class MixinScreen implements IGuiScreen {
@Override @Override
@Invoker("openWebLink") @Invoker("openLink")
public abstract void openLink(URI url); public abstract void openLink(URI url);
} }
@@ -1,47 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.Baritone;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.VboRenderList;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import static org.lwjgl.opengl.GL11.*;
@Mixin(VboRenderList.class)
public class MixinVboRenderList {
@Redirect( // avoid creating CallbackInfo at all costs; this is called 40k times per second
method = "renderChunkLayer",
at = @At(
value = "INVOKE",
target = "net/minecraft/client/renderer/GlStateManager.popMatrix()V"
)
)
private void popMatrix() {
if (Baritone.settings().renderCachedChunks.value && !Minecraft.getInstance().isSingleplayer()) {
// reset the blend func to normal (not dependent on constant alpha)
GlStateManager.blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
}
GlStateManager.popMatrix();
}
}
+11 -15
View File
@@ -8,26 +8,22 @@
"maxShiftBy": 2 "maxShiftBy": 2
}, },
"client": [ "client": [
"MixinAnvilChunkLoader",
"MixinBitArray", "MixinBitArray",
"MixinBlockStateContainer", "MixinBlockStateContainer",
"MixinChunkProviderClient", "MixinChatScreen",
"MixinChunkProviderServer", "MixinChunkArray",
"MixinChunkRenderContainer", "MixinClientChunkProvider",
"MixinChunkRenderWorker", "MixinClientPlayerEntity",
"MixinEntityLivingBase", "MixinClientPlayNetHandler",
"MixinEntityPlayerSP", "MixinEntity",
"MixinEntityRenderManager",
"MixinGameRenderer", "MixinGameRenderer",
"MixinGuiChat",
"MixinGuiScreen",
"MixinItemStack", "MixinItemStack",
"MixinLivingEntity",
"MixinLootContext",
"MixinMinecraft", "MixinMinecraft",
"MixinNetHandlerPlayClient",
"MixinNetworkManager", "MixinNetworkManager",
"MixinPlayerControllerMP", "MixinPlayerController",
"MixinRenderChunk", "MixinScreen"
"MixinRenderChunkCache",
"MixinRenderList",
"MixinVboRenderList"
] ]
} }
+1 -1
View File
@@ -218,7 +218,7 @@ public class Baritone implements IBaritone {
new Thread(() -> { new Thread(() -> {
try { try {
Thread.sleep(100); Thread.sleep(100);
Helper.mc.addScheduledTask(() -> Helper.mc.displayGuiScreen(new GuiClick())); Helper.mc.execute(() -> Helper.mc.displayGuiScreen(new GuiClick()));
} catch (Exception ignored) {} } catch (Exception ignored) {}
}).start(); }).start();
} }
@@ -21,13 +21,16 @@ import baritone.Baritone;
import baritone.api.event.events.TickEvent; import baritone.api.event.events.TickEvent;
import baritone.utils.ToolSet; import baritone.utils.ToolSet;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.block.Blocks;
import net.minecraft.init.Blocks; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.inventory.ClickType; import net.minecraft.inventory.container.ClickType;
import net.minecraft.item.*; import net.minecraft.item.*;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.NonNullList; import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.Vec3d;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.OptionalInt; import java.util.OptionalInt;
@@ -48,14 +51,14 @@ public final class InventoryBehavior extends Behavior {
if (event.getType() == TickEvent.Type.OUT) { if (event.getType() == TickEvent.Type.OUT) {
return; return;
} }
if (ctx.player().openContainer != ctx.player().inventoryContainer) { if (ctx.player().openContainer != ctx.player().container) {
// we have a crafting table or a chest or something open // we have a crafting table or a chest or something open
return; return;
} }
if (firstValidThrowaway() >= 9) { // aka there are none on the hotbar, but there are some in main inventory if (firstValidThrowaway() >= 9) { // aka there are none on the hotbar, but there are some in main inventory
swapWithHotBar(firstValidThrowaway(), 8); swapWithHotBar(firstValidThrowaway(), 8);
} }
int pick = bestToolAgainst(Blocks.STONE, ItemPickaxe.class); int pick = bestToolAgainst(Blocks.STONE, PickaxeItem.class);
if (pick >= 9) { if (pick >= 9) {
swapWithHotBar(pick, 0); swapWithHotBar(pick, 0);
} }
@@ -90,7 +93,7 @@ public final class InventoryBehavior extends Behavior {
} }
private void swapWithHotBar(int inInventory, int inHotbar) { private void swapWithHotBar(int inInventory, int inHotbar) {
ctx.playerController().windowClick(ctx.player().inventoryContainer.windowId, inInventory < 9 ? inInventory + 36 : inInventory, inHotbar, ClickType.SWAP, ctx.player()); ctx.playerController().windowClick(ctx.player().container.windowId, inInventory < 9 ? inInventory + 36 : inInventory, inHotbar, ClickType.SWAP, ctx.player());
} }
private int firstValidThrowaway() { // TODO offhand idk private int firstValidThrowaway() { // TODO offhand idk
@@ -103,7 +106,7 @@ public final class InventoryBehavior extends Behavior {
return -1; return -1;
} }
private int bestToolAgainst(Block against, Class<? extends ItemTool> cla$$) { private int bestToolAgainst(Block against, Class<? extends ToolItem> cla$$) {
NonNullList<ItemStack> invy = ctx.player().inventory.mainInventory; NonNullList<ItemStack> invy = ctx.player().inventory.mainInventory;
int bestInd = -1; int bestInd = -1;
double bestSpeed = -1; double bestSpeed = -1;
@@ -133,11 +136,11 @@ public final class InventoryBehavior extends Behavior {
} }
public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) { public boolean selectThrowawayForLocation(boolean select, int x, int y, int z) {
IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z, baritone.bsi.get0(x, y, z)); BlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z, baritone.bsi.get0(x, y, z));
if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && maybe.equals(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(new BlockItemUseContext(new ItemUseContext(ctx.player(), stack, ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ)))))) { if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof BlockItem && maybe.equals(((BlockItem) stack.getItem()).getBlock().getStateForPlacement(new BlockItemUseContext(new ItemUseContext(ctx.world(), ctx.player(), Hand.MAIN_HAND, stack, new BlockRayTraceResult(new Vec3d(ctx.player().posX, ctx.player().posY, ctx.player().posZ), Direction.UP, ctx.playerFeet(), false)) {}))))) {
return true; // gotem return true; // gotem
} }
if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock().equals(maybe.getBlock()))) { if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof BlockItem && ((BlockItem) stack.getItem()).getBlock().equals(maybe.getBlock()))) {
return true; return true;
} }
for (Item item : Baritone.settings().acceptableThrowawayItems.value) { for (Item item : Baritone.settings().acceptableThrowawayItems.value) {
@@ -149,7 +152,7 @@ public final class InventoryBehavior extends Behavior {
} }
public boolean throwaway(boolean select, Predicate<? super ItemStack> desired) { public boolean throwaway(boolean select, Predicate<? super ItemStack> desired) {
EntityPlayerSP p = ctx.player(); ClientPlayerEntity p = ctx.player();
NonNullList<ItemStack> inv = p.inventory.mainInventory; NonNullList<ItemStack> inv = p.inventory.mainInventory;
for (int i = 0; i < 9; i++) { for (int i = 0; i < 9; i++) {
ItemStack item = inv.get(i); ItemStack item = inv.get(i);
@@ -173,7 +176,7 @@ public final class InventoryBehavior extends Behavior {
// so not a shovel, not a hoe, not a block, etc // so not a shovel, not a hoe, not a block, etc
for (int i = 0; i < 9; i++) { for (int i = 0; i < 9; i++) {
ItemStack item = inv.get(i); ItemStack item = inv.get(i);
if (item.isEmpty() || item.getItem() instanceof ItemPickaxe) { if (item.isEmpty() || item.getItem() instanceof PickaxeItem) {
if (select) { if (select) {
p.inventory.currentItem = i; p.inventory.currentItem = i;
} }
@@ -20,32 +20,20 @@ package baritone.behavior;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.cache.Waypoint; import baritone.api.cache.Waypoint;
import baritone.api.event.events.BlockInteractEvent; import baritone.api.event.events.BlockInteractEvent;
import baritone.api.event.events.PacketEvent;
import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.TickEvent;
import baritone.api.event.events.type.EventState;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import baritone.cache.ContainerMemory; import baritone.cache.ContainerMemory;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import net.minecraft.block.Block; import net.minecraft.block.BedBlock;
import net.minecraft.block.BlockBed;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.CPacketCloseWindow;
import net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock;
import net.minecraft.network.play.server.SPacketCloseWindow;
import net.minecraft.network.play.server.SPacketOpenWindow;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityLockable;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentTranslation;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.*; import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/** /**
* doesn't work for horse inventories :^) * doesn't work for horse inventories :^)
@@ -55,111 +43,13 @@ import java.util.*;
*/ */
public final class MemoryBehavior extends Behavior { public final class MemoryBehavior extends Behavior {
private final List<FutureInventory> futureInventories = new ArrayList<>(); // this is per-bot
private Integer enderChestWindowId; // nae nae
public MemoryBehavior(Baritone baritone) { public MemoryBehavior(Baritone baritone) {
super(baritone); super(baritone);
} }
@Override
public synchronized void onTick(TickEvent event) {
if (!Baritone.settings().containerMemory.value) {
return;
}
if (event.getType() == TickEvent.Type.OUT) {
enderChestWindowId = null;
futureInventories.clear();
}
}
@Override
public synchronized void onPlayerUpdate(PlayerUpdateEvent event) {
if (event.getState() == EventState.PRE) {
updateInventory();
}
}
@Override
public synchronized void onSendPacket(PacketEvent event) {
if (!Baritone.settings().containerMemory.value) {
return;
}
Packet p = event.getPacket();
if (event.getState() == EventState.PRE) {
if (p instanceof CPacketPlayerTryUseItemOnBlock) {
CPacketPlayerTryUseItemOnBlock packet = event.cast();
TileEntity tileEntity = ctx.world().getTileEntity(packet.getPos());
// if tileEntity is an ender chest, we don't need to do anything. ender chests are treated the same regardless of what coordinate right clicked
// Ensure the TileEntity is a container of some sort
if (tileEntity instanceof TileEntityLockable) {
TileEntityLockable lockable = (TileEntityLockable) tileEntity;
int size = lockable.getSizeInventory();
BetterBlockPos position = BetterBlockPos.from(tileEntity.getPos());
BetterBlockPos adj = BetterBlockPos.from(neighboringConnectedBlock(position));
System.out.println(position + " " + adj);
if (adj != null) {
size *= 2; // double chest or double trapped chest
if (adj.getX() < position.getX() || adj.getZ() < position.getZ()) {
position = adj; // standardize on the lower coordinate, regardless of which side of the large chest we right clicked
}
}
this.futureInventories.add(new FutureInventory(System.nanoTime() / 1000000L, size, lockable.getGuiID(), position));
}
}
if (p instanceof CPacketCloseWindow) {
getCurrent().save();
}
}
}
@Override
public synchronized void onReceivePacket(PacketEvent event) {
if (!Baritone.settings().containerMemory.value) {
return;
}
Packet p = event.getPacket();
if (event.getState() == EventState.PRE) {
if (p instanceof SPacketOpenWindow) {
SPacketOpenWindow packet = event.cast();
// Remove any entries that were created over a second ago, this should make up for INSANE latency
futureInventories.removeIf(i -> System.nanoTime() / 1000000L - i.time > 1000);
System.out.println("Received packet " + packet.getGuiId() + " " + packet.getEntityId() + " " + packet.getSlotCount() + " " + packet.getWindowId());
System.out.println(packet.getWindowTitle());
if (packet.getWindowTitle() instanceof TextComponentTranslation && ((TextComponentTranslation) packet.getWindowTitle()).getKey().equals("container.enderchest")) {
// title is not customized (i.e. this isn't just a renamed shulker)
enderChestWindowId = packet.getWindowId();
return;
}
futureInventories.stream()
.filter(i -> i.type.equals(packet.getGuiId()) && i.slots == packet.getSlotCount())
.findFirst().ifPresent(matched -> {
// Remove the future inventory
futureInventories.remove(matched);
// Setup the remembered inventory
getCurrentContainer().setup(matched.pos, packet.getWindowId(), packet.getSlotCount());
});
}
if (p instanceof SPacketCloseWindow) {
getCurrent().save();
}
}
}
@Override @Override
public void onBlockInteract(BlockInteractEvent event) { public void onBlockInteract(BlockInteractEvent event) {
if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(ctx, event.getPos()) instanceof BlockBed) { if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(ctx, event.getPos()) instanceof BedBlock) {
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, BetterBlockPos.from(event.getPos()))); baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("bed", Waypoint.Tag.BED, BetterBlockPos.from(event.getPos())));
} }
} }
@@ -169,86 +59,6 @@ public final class MemoryBehavior extends Behavior {
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, ctx.playerFeet())); baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, ctx.playerFeet()));
} }
private void updateInventory() {
if (!Baritone.settings().containerMemory.value) {
return;
}
int windowId = ctx.player().openContainer.windowId;
if (enderChestWindowId != null) {
if (windowId == enderChestWindowId) {
getCurrent().contents = ctx.player().openContainer.getInventory().subList(0, 27);
} else {
getCurrent().save();
enderChestWindowId = null;
}
}
if (getCurrentContainer() != null) {
getCurrentContainer().getInventoryFromWindow(windowId).ifPresent(inventory -> inventory.updateFromOpenWindow(ctx));
}
}
private ContainerMemory getCurrentContainer() {
if (baritone.getWorldProvider().getCurrentWorld() == null) {
return null;
}
return (ContainerMemory) baritone.getWorldProvider().getCurrentWorld().getContainerMemory();
}
private BlockPos neighboringConnectedBlock(BlockPos in) {
BlockStateInterface bsi = baritone.bsi;
Block block = bsi.get0(in).getBlock();
if (block != Blocks.TRAPPED_CHEST && block != Blocks.CHEST) {
return null; // other things that have contents, but can be placed adjacent without combining
}
for (int i = 0; i < 4; i++) {
BlockPos adj = in.offset(EnumFacing.byHorizontalIndex(i));
if (bsi.get0(adj).getBlock() == block) {
return adj;
}
}
return null;
}
/**
* An inventory that we are not yet fully aware of, but are expecting to exist at some point in the future.
*/
private static final class FutureInventory {
/**
* The time that we initially expected the inventory to be provided, in milliseconds
*/
private final long time;
/**
* The amount of slots in the inventory
*/
private final int slots;
/**
* The type of inventory
*/
private final String type;
/**
* The position of the inventory container
*/
private final BlockPos pos;
private FutureInventory(long time, int slots, String type, BlockPos pos) {
this.time = time;
this.slots = slots;
this.type = type;
this.pos = pos;
// betterblockpos has censoring
System.out.println("Future inventory created " + time + " " + slots + " " + type + " " + BetterBlockPos.from(pos));
}
}
public Optional<List<ItemStack>> echest() {
return Optional.ofNullable(getCurrent().contents).map(Collections::unmodifiableList);
}
public EnderChestMemory getCurrent() { public EnderChestMemory getCurrent() {
Path path = baritone.getWorldProvider().getCurrentWorld().directory; Path path = baritone.getWorldProvider().getCurrentWorld().directory;
return EnderChestMemory.getByServerAndPlayer(path.getParent(), ctx.player().getUniqueID()); return EnderChestMemory.getByServerAndPlayer(path.getParent(), ctx.player().getUniqueID());
+6 -6
View File
@@ -22,8 +22,8 @@ import baritone.utils.pathing.PathingBlockType;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.init.Blocks; import net.minecraft.block.Blocks;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import java.util.ArrayList; import java.util.ArrayList;
@@ -143,7 +143,7 @@ public final class CachedChunk {
/** /**
* The block names of each surface level block for generating an overview * The block names of each surface level block for generating an overview
*/ */
private final IBlockState[] overview; private final BlockState[] overview;
private final int[] heightMap; private final int[] heightMap;
@@ -151,7 +151,7 @@ public final class CachedChunk {
public final long cacheTimestamp; public final long cacheTimestamp;
CachedChunk(int x, int z, BitSet data, IBlockState[] overview, Map<String, List<BlockPos>> specialBlockLocations, long cacheTimestamp) { CachedChunk(int x, int z, BitSet data, BlockState[] overview, Map<String, List<BlockPos>> specialBlockLocations, long cacheTimestamp) {
validateSize(data); validateSize(data);
this.x = x; this.x = x;
@@ -178,7 +178,7 @@ public final class CachedChunk {
} }
} }
public final IBlockState getBlock(int x, int y, int z, int dimension) { public final BlockState getBlock(int x, int y, int z, int dimension) {
int index = getPositionIndex(x, y, z); int index = getPositionIndex(x, y, z);
PathingBlockType type = getType(index); PathingBlockType type = getType(index);
int internalPos = z << 4 | x; int internalPos = z << 4 | x;
@@ -234,7 +234,7 @@ public final class CachedChunk {
} }
} }
public final IBlockState[] getOverview() { public final BlockState[] getOverview() {
return overview; return overview;
} }
+4 -4
View File
@@ -20,7 +20,7 @@ package baritone.cache;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.cache.ICachedRegion; import baritone.api.cache.ICachedRegion;
import baritone.api.utils.BlockUtils; import baritone.api.utils.BlockUtils;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import java.io.*; import java.io.*;
@@ -75,7 +75,7 @@ public final class CachedRegion implements ICachedRegion {
} }
@Override @Override
public final IBlockState getBlock(int x, int y, int z) { public final BlockState getBlock(int x, int y, int z) {
CachedChunk chunk = chunks[x >> 4][z >> 4]; CachedChunk chunk = chunks[x >> 4][z >> 4];
if (chunk != null) { if (chunk != null) {
return chunk.getBlock(x & 15, y, z & 15, dimension); return chunk.getBlock(x & 15, y, z & 15, dimension);
@@ -216,7 +216,7 @@ public final class CachedRegion implements ICachedRegion {
boolean[][] present = new boolean[32][32]; boolean[][] present = new boolean[32][32];
BitSet[][] bitSets = new BitSet[32][32]; BitSet[][] bitSets = new BitSet[32][32];
Map<String, List<BlockPos>>[][] location = new Map[32][32]; Map<String, List<BlockPos>>[][] location = new Map[32][32];
IBlockState[][][] overview = new IBlockState[32][32][]; BlockState[][][] overview = new BlockState[32][32][];
long[][] cacheTimestamp = new long[32][32]; long[][] cacheTimestamp = new long[32][32];
for (int x = 0; x < 32; x++) { for (int x = 0; x < 32; x++) {
for (int z = 0; z < 32; z++) { for (int z = 0; z < 32; z++) {
@@ -227,7 +227,7 @@ public final class CachedRegion implements ICachedRegion {
in.readFully(bytes); in.readFully(bytes);
bitSets[x][z] = BitSet.valueOf(bytes); bitSets[x][z] = BitSet.valueOf(bytes);
location[x][z] = new HashMap<>(); location[x][z] = new HashMap<>();
overview[x][z] = new IBlockState[256]; overview[x][z] = new BlockState[256];
present[x][z] = true; present[x][z] = true;
break; break;
case CHUNK_NOT_PRESENT: case CHUNK_NOT_PRESENT:
+15 -15
View File
@@ -21,8 +21,6 @@ import baritone.api.utils.BlockUtils;
import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementHelper;
import baritone.utils.pathing.PathingBlockType; import baritone.utils.pathing.PathingBlockType;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
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.chunk.BlockStateContainer; import net.minecraft.world.chunk.BlockStateContainer;
@@ -31,6 +29,8 @@ import net.minecraft.world.chunk.ChunkSection;
import java.util.*; import java.util.*;
import static baritone.utils.BlockStateInterface.getFromChunk;
/** /**
* @author Brady * @author Brady
* @since 8/3/2018 * @since 8/3/2018
@@ -59,7 +59,7 @@ public final class ChunkPacker {
// since a bitset is initialized to all zero, and air is saved as zeros // since a bitset is initialized to all zero, and air is saved as zeros
continue; continue;
} }
BlockStateContainer<IBlockState> bsc = extendedblockstorage.getData(); BlockStateContainer<BlockState> bsc = extendedblockstorage.getData();
int yReal = y0 << 4; int yReal = y0 << 4;
// the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x; // the mapping of BlockStateContainer.getIndex from xyz to index is y << 8 | z << 4 | x;
// for better cache locality, iterate in that order // for better cache locality, iterate in that order
@@ -68,7 +68,7 @@ public final class ChunkPacker {
for (int z = 0; z < 16; z++) { for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) { for (int x = 0; x < 16; x++) {
int index = CachedChunk.getPositionIndex(x, y, z); int index = CachedChunk.getPositionIndex(x, y, z);
IBlockState state = bsc.get(x, y1, z); BlockState state = bsc.get(x, y1, z);
boolean[] bits = getPathingBlockType(state, chunk, x, y, z).getBits(); boolean[] bits = getPathingBlockType(state, chunk, x, y, z).getBits();
bitSet.set(index, bits[0]); bitSet.set(index, bits[0]);
bitSet.set(index + 1, bits[1]); bitSet.set(index + 1, bits[1]);
@@ -86,7 +86,7 @@ public final class ChunkPacker {
} }
//long end = System.nanoTime() / 1000000L; //long end = System.nanoTime() / 1000000L;
//System.out.println("Chunk packing took " + (end - start) + "ms for " + chunk.x + "," + chunk.z); //System.out.println("Chunk packing took " + (end - start) + "ms for " + chunk.x + "," + chunk.z);
IBlockState[] blocks = new IBlockState[256]; BlockState[] blocks = new BlockState[256];
// @formatter:off // @formatter:off
for (int z = 0; z < 16; z++) { for (int z = 0; z < 16; z++) {
@@ -95,7 +95,7 @@ public final class ChunkPacker {
for (int y = 255; y >= 0; y--) { for (int y = 255; y >= 0; y--) {
int index = CachedChunk.getPositionIndex(x, y, z); int index = CachedChunk.getPositionIndex(x, y, z);
if (bitSet.get(index) || bitSet.get(index + 1)) { if (bitSet.get(index) || bitSet.get(index + 1)) {
blocks[z << 4 | x] = chunk.getBlockState(x, y, z); blocks[z << 4 | x] = getFromChunk(chunk, x, y, z);
continue https; continue https;
} }
} }
@@ -103,10 +103,10 @@ public final class ChunkPacker {
} }
} }
// @formatter:on // @formatter:on
return new CachedChunk(chunk.x, chunk.z, bitSet, blocks, specialBlocks, System.currentTimeMillis()); return new CachedChunk(chunk.getPos().x, chunk.getPos().z, bitSet, blocks, specialBlocks, System.currentTimeMillis());
} }
private static PathingBlockType getPathingBlockType(IBlockState state, Chunk chunk, int x, int y, int z) { private static PathingBlockType getPathingBlockType(BlockState state, Chunk chunk, int x, int y, int z) {
Block block = state.getBlock(); Block block = state.getBlock();
if (MovementHelper.isWater(state)) { if (MovementHelper.isWater(state)) {
// only water source blocks are plausibly usable, flowing water should be avoid // only water source blocks are plausibly usable, flowing water should be avoid
@@ -115,15 +115,15 @@ public final class ChunkPacker {
return PathingBlockType.AVOID; return PathingBlockType.AVOID;
} }
if ( if (
(x != 15 && MovementHelper.possiblyFlowing(chunk.getBlockState(x + 1, y, z))) (x != 15 && MovementHelper.possiblyFlowing(getFromChunk(chunk, x + 1, y, z)))
|| (x != 0 && MovementHelper.possiblyFlowing(chunk.getBlockState(x - 1, y, z))) || (x != 0 && MovementHelper.possiblyFlowing(getFromChunk(chunk, x - 1, y, z)))
|| (z != 15 && MovementHelper.possiblyFlowing(chunk.getBlockState(x, y, z + 1))) || (z != 15 && MovementHelper.possiblyFlowing(getFromChunk(chunk, x, y, z + 1)))
|| (z != 0 && MovementHelper.possiblyFlowing(chunk.getBlockState(x, y, z - 1))) || (z != 0 && MovementHelper.possiblyFlowing(getFromChunk(chunk, x, y, z - 1)))
) { ) {
return PathingBlockType.AVOID; return PathingBlockType.AVOID;
} }
if (x == 0 || x == 15 || z == 0 || z == 15) { if (x == 0 || x == 15 || z == 0 || z == 15) {
Vec3d flow = state.getFluidState().getFlow(chunk.getWorld(), new BlockPos(x + chunk.x << 4, y, z + chunk.z << 4)); Vec3d flow = state.getFluidState().getFlow(chunk.getWorld(), new BlockPos(x + chunk.getPos().x << 4, y, z + chunk.getPos().z << 4));
if (flow.x != 0.0 || flow.z != 0.0) { if (flow.x != 0.0 || flow.z != 0.0) {
return PathingBlockType.WATER; return PathingBlockType.WATER;
} }
@@ -139,14 +139,14 @@ public final class ChunkPacker {
// however, this failed in the nether when you were near a nether fortress // however, this failed in the nether when you were near a nether fortress
// because fences check their adjacent blocks in the world for their fence connection status to determine AABB shape // because fences check their adjacent blocks in the world for their fence connection status to determine AABB shape
// this caused a nullpointerexception when we saved chunks on unload, because they were unable to check their neighbors // this caused a nullpointerexception when we saved chunks on unload, because they were unable to check their neighbors
if (block instanceof BlockAir || block instanceof BlockTallGrass || block instanceof BlockDoublePlant || block instanceof BlockFlower) { if (block instanceof AirBlock || block instanceof TallGrassBlock || block instanceof DoublePlantBlock || block instanceof FlowerBlock) {
return PathingBlockType.AIR; return PathingBlockType.AIR;
} }
return PathingBlockType.SOLID; return PathingBlockType.SOLID;
} }
public static IBlockState pathingTypeToBlock(PathingBlockType type, int dimension) { public static BlockState pathingTypeToBlock(PathingBlockType type, int dimension) {
switch (type) { switch (type) {
case AIR: case AIR:
return Blocks.AIR.getDefaultState(); return Blocks.AIR.getDefaultState();
+4 -8
View File
@@ -20,11 +20,9 @@ package baritone.cache;
import baritone.Baritone; import baritone.Baritone;
import baritone.api.cache.IWorldProvider; import baritone.api.cache.IWorldProvider;
import baritone.api.utils.Helper; import baritone.api.utils.Helper;
import baritone.utils.accessor.IAnvilChunkLoader;
import baritone.utils.accessor.IChunkProviderServer;
import net.minecraft.server.integrated.IntegratedServer; import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.world.WorldServer;
import net.minecraft.world.dimension.DimensionType; import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.server.ServerWorld;
import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.SystemUtils;
import java.io.File; import java.io.File;
@@ -64,10 +62,8 @@ public class WorldProvider implements IWorldProvider, Helper {
// If there is an integrated server running (Aka Singleplayer) then do magic to find the world save file // If there is an integrated server running (Aka Singleplayer) then do magic to find the world save file
if (mc.isSingleplayer()) { if (mc.isSingleplayer()) {
WorldServer localServerWorld = integratedServer.getWorld(dimension); ServerWorld localServerWorld = integratedServer.getWorld(dimension);
IChunkProviderServer provider = (IChunkProviderServer) localServerWorld.getChunkProvider(); directory = dimension.getDirectory(localServerWorld.getSaveHandler().getWorldDirectory());
IAnvilChunkLoader loader = (IAnvilChunkLoader) provider.getChunkLoader();
directory = loader.getChunkSaveLocation();
// Gets the "depth" of this directory relative the the game's run directory, 2 is the location of the world // Gets the "depth" of this directory relative the the game's run directory, 2 is the location of the world
if (directory.toPath().relativize(mc.gameDir.toPath()).getNameCount() != 2) { if (directory.toPath().relativize(mc.gameDir.toPath()).getNameCount() != 2) {
@@ -78,7 +74,7 @@ public class WorldProvider implements IWorldProvider, Helper {
directory = new File(directory, "baritone"); directory = new File(directory, "baritone");
readme = directory; readme = directory;
} else { // Otherwise, the server must be remote... } else { // Otherwise, the server must be remote...
String folderName = mc.getCurrentServerData().serverIP; String folderName = mc.isConnectedToRealms() ? "realms" : mc.getCurrentServerData().serverIP;
if (SystemUtils.IS_OS_WINDOWS) { if (SystemUtils.IS_OS_WINDOWS) {
folderName = folderName.replace(":", "_"); folderName = folderName.replace(":", "_");
} }
+12 -14
View File
@@ -23,13 +23,12 @@ import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.BlockOptionalMetaLookup; import baritone.api.utils.BlockOptionalMetaLookup;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import baritone.utils.accessor.IBlockStateContainer; import baritone.utils.accessor.IBlockStateContainer;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.client.multiplayer.ChunkProviderClient; import net.minecraft.client.multiplayer.ClientChunkProvider;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkSection; import net.minecraft.world.chunk.ChunkSection;
import net.minecraft.world.chunk.IChunkProvider;
import java.util.*; import java.util.*;
import java.util.stream.IntStream; import java.util.stream.IntStream;
@@ -47,8 +46,7 @@ public enum WorldScanner implements IWorldScanner {
if (filter.blocks().isEmpty()) { if (filter.blocks().isEmpty()) {
return res; return res;
} }
ClientChunkProvider chunkProvider = (ClientChunkProvider) ctx.world().getChunkProvider();
ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider();
int maxSearchRadiusSq = maxSearchRadius * maxSearchRadius; int maxSearchRadiusSq = maxSearchRadius * maxSearchRadius;
int playerChunkX = ctx.playerFeet().getX() >> 4; int playerChunkX = ctx.playerFeet().getX() >> 4;
@@ -72,7 +70,7 @@ public enum WorldScanner implements IWorldScanner {
foundChunks = true; foundChunks = true;
int chunkX = xoff + playerChunkX; int chunkX = xoff + playerChunkX;
int chunkZ = zoff + playerChunkZ; int chunkZ = zoff + playerChunkZ;
Chunk chunk = chunkProvider.getChunk(chunkX, chunkZ, false, false); Chunk chunk = chunkProvider.getChunk(chunkX, chunkZ, null, false);
if (chunk == null) { if (chunk == null) {
continue; continue;
} }
@@ -98,8 +96,8 @@ public enum WorldScanner implements IWorldScanner {
return Collections.emptyList(); return Collections.emptyList();
} }
ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider(); ClientChunkProvider chunkProvider = (ClientChunkProvider) ctx.world().getChunkProvider();
Chunk chunk = chunkProvider.getChunk(pos.x, pos.z, false, false); Chunk chunk = chunkProvider.getChunk(pos.x, pos.z, null, false);
int playerY = ctx.playerFeet().getY(); int playerY = ctx.playerFeet().getY();
if (chunk == null || chunk.isEmpty()) { if (chunk == null || chunk.isEmpty()) {
@@ -116,18 +114,18 @@ public enum WorldScanner implements IWorldScanner {
boolean foundWithinY = false; boolean foundWithinY = false;
for (int yIndex = 0; yIndex < 16; yIndex++) { for (int yIndex = 0; yIndex < 16; yIndex++) {
int y0 = coordinateIterationOrder[yIndex]; int y0 = coordinateIterationOrder[yIndex];
ChunkSection extendedblockstorage = chunkInternalStorageArray[y0]; ChunkSection section = chunkInternalStorageArray[y0];
if (extendedblockstorage == null) { if (section == null || ChunkSection.isEmpty(section)) {
continue; continue;
} }
int yReal = y0 << 4; int yReal = y0 << 4;
IBlockStateContainer bsc = (IBlockStateContainer) extendedblockstorage.getData(); IBlockStateContainer bsc = (IBlockStateContainer) section.getData();
// storageArray uses an optimized algorithm that's faster than getAt // storageArray uses an optimized algorithm that's faster than getAt
// creating this array and then using getAtPalette is faster than even getFast(int index) // creating this array and then using getAtPalette is faster than even getFast(int index)
int[] storage = bsc.storageArray(); int[] storage = bsc.storageArray();
final int imax = 1 << 12; final int imax = 1 << 12;
for (int i = 0; i < imax; i++) { for (int i = 0; i < imax; i++) {
IBlockState state = bsc.getAtPalette(storage[i]); BlockState state = bsc.getAtPalette(storage[i]);
if (filter.has(state)) { if (filter.has(state)) {
int y = yReal | ((i >> 8) & 15); int y = yReal | ((i >> 8) & 15);
if (result.size() >= max) { if (result.size() >= max) {
@@ -149,7 +147,7 @@ public enum WorldScanner implements IWorldScanner {
} }
public int repack(IPlayerContext ctx) { public int repack(IPlayerContext ctx) {
IChunkProvider chunkProvider = ctx.world().getChunkProvider(); ClientChunkProvider chunkProvider = (ClientChunkProvider) ctx.world().getChunkProvider();
ICachedWorld cachedWorld = ctx.worldData().getCachedWorld(); ICachedWorld cachedWorld = ctx.worldData().getCachedWorld();
BetterBlockPos playerPos = ctx.playerFeet(); BetterBlockPos playerPos = ctx.playerFeet();
@@ -158,7 +156,7 @@ public enum WorldScanner implements IWorldScanner {
int queued = 0; int queued = 0;
for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) { for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) {
for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) { for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) {
Chunk chunk = chunkProvider.getChunk(x, z, false, false); Chunk chunk = chunkProvider.getChunk(x, z, null, false);
if (chunk != null && !chunk.isEmpty()) { if (chunk != null && !chunk.isEmpty()) {
queued++; queued++;
@@ -36,7 +36,7 @@ import baritone.command.argument.CommandArguments;
import baritone.command.manager.CommandManager; import baritone.command.manager.CommandManager;
import net.minecraft.util.Tuple; import net.minecraft.util.Tuple;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.util.text.event.HoverEvent; import net.minecraft.util.text.event.HoverEvent;
@@ -79,12 +79,12 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
if (settings.echoCommands.value) { if (settings.echoCommands.value) {
String msg = command + rest; String msg = command + rest;
String toDisplay = settings.censorRanCommands.value ? command + " ..." : msg; String toDisplay = settings.censorRanCommands.value ? command + " ..." : msg;
ITextComponent component = new TextComponentString(String.format("> %s", toDisplay)); ITextComponent component = new StringTextComponent(String.format("> %s", toDisplay));
component.getStyle() component.getStyle()
.setColor(TextFormatting.WHITE) .setColor(TextFormatting.WHITE)
.setHoverEvent(new HoverEvent( .setHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT, HoverEvent.Action.SHOW_TEXT,
new TextComponentString("Click to rerun command") new StringTextComponent("Click to rerun command")
)) ))
.setClickEvent(new ClickEvent( .setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND, ClickEvent.Action.RUN_COMMAND,
@@ -24,7 +24,7 @@ import baritone.api.command.datatypes.BlockById;
import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandException;
import baritone.api.command.argument.IArgConsumer; import baritone.api.command.argument.IArgConsumer;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.util.registry.IRegistry; import net.minecraft.util.registry.Registry;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -47,7 +47,7 @@ public class FindCommand extends Command {
toFind.stream() toFind.stream()
.flatMap(block -> .flatMap(block ->
ctx.worldData().getCachedWorld().getLocationsOf( ctx.worldData().getCachedWorld().getLocationsOf(
IRegistry.BLOCK.getKey(block).getPath(), Registry.BLOCK.getKey(block).getPath(),
Integer.MAX_VALUE, Integer.MAX_VALUE,
origin.x, origin.x,
origin.y, origin.y,
@@ -26,11 +26,11 @@ import baritone.api.command.exception.CommandException;
import baritone.api.command.argument.IArgConsumer; import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityType; import net.minecraft.entity.EntityType;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry; import net.minecraft.util.registry.Registry;
import java.util.*; import java.util.*;
import java.util.function.Predicate; import java.util.function.Predicate;
@@ -64,10 +64,11 @@ public class FollowCommand extends Command {
entities.add((Entity) gotten); entities.add((Entity) gotten);
} }
} }
baritone.getFollowProcess().follow( baritone.getFollowProcess().follow(
classes.isEmpty() classes.isEmpty()
? entities::contains ? entities::contains
: e -> classes.stream().anyMatch(c -> c.getEntityClass().isInstance(e)) : e -> classes.stream().anyMatch(c -> e.getType().equals(c))
); );
} }
if (group != null) { if (group != null) {
@@ -80,7 +81,7 @@ public class FollowCommand extends Command {
.forEach(this::logDirect); .forEach(this::logDirect);
} else { } else {
classes.stream() classes.stream()
.map(IRegistry.ENTITY_TYPE::getKey) .map(Registry.ENTITY_TYPE::getKey)
.map(Objects::requireNonNull) .map(Objects::requireNonNull)
.map(ResourceLocation::toString) .map(ResourceLocation::toString)
.forEach(this::logDirect); .forEach(this::logDirect);
@@ -132,8 +133,8 @@ public class FollowCommand extends Command {
} }
private enum FollowGroup { private enum FollowGroup {
ENTITIES(EntityLiving.class::isInstance), ENTITIES(LivingEntity.class::isInstance),
PLAYERS(EntityPlayer.class::isInstance); /* , PLAYERS(PlayerEntity.class::isInstance); /* ,
FRIENDLY(entity -> entity.getAttackTarget() != HELPER.mc.player), FRIENDLY(entity -> entity.getAttackTarget() != HELPER.mc.player),
HOSTILE(FRIENDLY.filter.negate()); */ HOSTILE(FRIENDLY.filter.negate()); */
final Predicate<Entity> filter; final Predicate<Entity> filter;
@@ -26,7 +26,7 @@ import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.helpers.Paginator; import baritone.api.command.helpers.Paginator;
import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.util.text.event.HoverEvent; import net.minecraft.util.text.event.HoverEvent;
@@ -58,17 +58,17 @@ public class HelpCommand extends Command {
command -> { command -> {
String names = String.join("/", command.getNames()); String names = String.join("/", command.getNames());
String name = command.getNames().get(0); String name = command.getNames().get(0);
ITextComponent shortDescComponent = new TextComponentString(" - " + command.getShortDesc()); ITextComponent shortDescComponent = new StringTextComponent(" - " + command.getShortDesc());
shortDescComponent.getStyle().setColor(TextFormatting.DARK_GRAY); shortDescComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
ITextComponent namesComponent = new TextComponentString(names); ITextComponent namesComponent = new StringTextComponent(names);
namesComponent.getStyle().setColor(TextFormatting.WHITE); namesComponent.getStyle().setColor(TextFormatting.WHITE);
ITextComponent hoverComponent = new TextComponentString(""); ITextComponent hoverComponent = new StringTextComponent("");
hoverComponent.getStyle().setColor(TextFormatting.GRAY); hoverComponent.getStyle().setColor(TextFormatting.GRAY);
hoverComponent.appendSibling(namesComponent); hoverComponent.appendSibling(namesComponent);
hoverComponent.appendText("\n" + command.getShortDesc()); hoverComponent.appendText("\n" + command.getShortDesc());
hoverComponent.appendText("\n\nClick to view full help"); hoverComponent.appendText("\n\nClick to view full help");
String clickCommand = FORCE_COMMAND_PREFIX + String.format("%s %s", label, command.getNames().get(0)); String clickCommand = FORCE_COMMAND_PREFIX + String.format("%s %s", label, command.getNames().get(0));
ITextComponent component = new TextComponentString(name); ITextComponent component = new StringTextComponent(name);
component.getStyle().setColor(TextFormatting.GRAY); component.getStyle().setColor(TextFormatting.GRAY);
component.appendSibling(shortDescComponent); component.appendSibling(shortDescComponent);
component.getStyle() component.getStyle()
@@ -88,7 +88,7 @@ public class HelpCommand extends Command {
logDirect(""); logDirect("");
command.getLongDesc().forEach(this::logDirect); command.getLongDesc().forEach(this::logDirect);
logDirect(""); logDirect("");
ITextComponent returnComponent = new TextComponentString("Click to return to the help menu"); ITextComponent returnComponent = new StringTextComponent("Click to return to the help menu");
returnComponent.getStyle().setClickEvent(new ClickEvent( returnComponent.getStyle().setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND, ClickEvent.Action.RUN_COMMAND,
FORCE_COMMAND_PREFIX + label FORCE_COMMAND_PREFIX + label
@@ -30,7 +30,7 @@ import baritone.api.utils.BlockOptionalMetaLookup;
import baritone.api.schematic.ISchematic; import baritone.api.schematic.ISchematic;
import baritone.api.command.Command; import baritone.api.command.Command;
import baritone.api.command.datatypes.ForBlockOptionalMeta; import baritone.api.command.datatypes.ForBlockOptionalMeta;
import baritone.api.command.datatypes.ForEnumFacing; import baritone.api.command.datatypes.ForDirection;
import baritone.api.command.datatypes.RelativeBlockPos; import baritone.api.command.datatypes.RelativeBlockPos;
import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidStateException; import baritone.api.command.exception.CommandInvalidStateException;
@@ -38,8 +38,8 @@ import baritone.api.command.exception.CommandInvalidTypeException;
import baritone.api.command.argument.IArgConsumer; import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.command.helpers.TabCompleteHelper;
import baritone.utils.IRenderer; import baritone.utils.IRenderer;
import net.minecraft.init.Blocks; import net.minecraft.block.Blocks;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
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.Vec3i; import net.minecraft.util.math.Vec3i;
@@ -165,7 +165,7 @@ public class SelCommand extends Command {
if (transformTarget == null) { if (transformTarget == null) {
throw new CommandInvalidStateException("Invalid transform type"); throw new CommandInvalidStateException("Invalid transform type");
} }
EnumFacing direction = args.getDatatypeFor(ForEnumFacing.INSTANCE); Direction direction = args.getDatatypeFor(ForDirection.INSTANCE);
int blocks = args.getAs(Integer.class); int blocks = args.getAs(Integer.class);
ISelection[] selections = manager.getSelections(); ISelection[] selections = manager.getSelections();
if (selections.length < 1) { if (selections.length < 1) {
@@ -217,7 +217,7 @@ public class SelCommand extends Command {
} else { } else {
TransformTarget target = TransformTarget.getByName(args.getString()); TransformTarget target = TransformTarget.getByName(args.getString());
if (target != null && args.hasExactlyOne()) { if (target != null && args.hasExactlyOne()) {
return args.tabCompleteDatatype(ForEnumFacing.INSTANCE); return args.tabCompleteDatatype(ForDirection.INSTANCE);
} }
} }
} }
@@ -28,7 +28,7 @@ import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.helpers.Paginator; import baritone.api.command.helpers.Paginator;
import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.util.text.event.HoverEvent; import net.minecraft.util.text.event.HoverEvent;
@@ -78,18 +78,18 @@ public class SetCommand extends Command {
: String.format("All %ssettings:", viewModified ? "modified " : "") : String.format("All %ssettings:", viewModified ? "modified " : "")
), ),
setting -> { setting -> {
ITextComponent typeComponent = new TextComponentString(String.format( ITextComponent typeComponent = new StringTextComponent(String.format(
" (%s)", " (%s)",
settingTypeToString(setting) settingTypeToString(setting)
)); ));
typeComponent.getStyle().setColor(TextFormatting.DARK_GRAY); typeComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
ITextComponent hoverComponent = new TextComponentString(""); ITextComponent hoverComponent = new StringTextComponent("");
hoverComponent.getStyle().setColor(TextFormatting.GRAY); hoverComponent.getStyle().setColor(TextFormatting.GRAY);
hoverComponent.appendText(setting.getName()); hoverComponent.appendText(setting.getName());
hoverComponent.appendText(String.format("\nType: %s", settingTypeToString(setting))); hoverComponent.appendText(String.format("\nType: %s", settingTypeToString(setting)));
hoverComponent.appendText(String.format("\n\nValue:\n%s", settingValueToString(setting))); hoverComponent.appendText(String.format("\n\nValue:\n%s", settingValueToString(setting)));
String commandSuggestion = Baritone.settings().prefix.value + String.format("set %s ", setting.getName()); String commandSuggestion = Baritone.settings().prefix.value + String.format("set %s ", setting.getName());
ITextComponent component = new TextComponentString(setting.getName()); ITextComponent component = new StringTextComponent(setting.getName());
component.getStyle().setColor(TextFormatting.GRAY); component.getStyle().setColor(TextFormatting.GRAY);
component.appendSibling(typeComponent); component.appendSibling(typeComponent);
component.getStyle() component.getStyle()
@@ -163,12 +163,12 @@ public class SetCommand extends Command {
settingValueToString(setting) settingValueToString(setting)
)); ));
} }
ITextComponent oldValueComponent = new TextComponentString(String.format("Old value: %s", oldValue)); ITextComponent oldValueComponent = new StringTextComponent(String.format("Old value: %s", oldValue));
oldValueComponent.getStyle() oldValueComponent.getStyle()
.setColor(TextFormatting.GRAY) .setColor(TextFormatting.GRAY)
.setHoverEvent(new HoverEvent( .setHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT, HoverEvent.Action.SHOW_TEXT,
new TextComponentString("Click to set the setting back to this value") new StringTextComponent("Click to set the setting back to this value")
)) ))
.setClickEvent(new ClickEvent( .setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND, ClickEvent.Action.RUN_COMMAND,
@@ -33,7 +33,7 @@ import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.helpers.Paginator; import baritone.api.command.helpers.Paginator;
import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.util.text.event.HoverEvent; import net.minecraft.util.text.event.HoverEvent;
@@ -58,13 +58,13 @@ public class WaypointsCommand extends Command {
throw new CommandInvalidTypeException(args.consumed(), "an action"); throw new CommandInvalidTypeException(args.consumed(), "an action");
} }
BiFunction<IWaypoint, Action, ITextComponent> toComponent = (waypoint, _action) -> { BiFunction<IWaypoint, Action, ITextComponent> toComponent = (waypoint, _action) -> {
ITextComponent component = new TextComponentString(""); ITextComponent component = new StringTextComponent("");
ITextComponent tagComponent = new TextComponentString(waypoint.getTag().name() + " "); ITextComponent tagComponent = new StringTextComponent(waypoint.getTag().name() + " ");
tagComponent.getStyle().setColor(TextFormatting.GRAY); tagComponent.getStyle().setColor(TextFormatting.GRAY);
String name = waypoint.getName(); String name = waypoint.getName();
ITextComponent nameComponent = new TextComponentString(!name.isEmpty() ? name : "<empty>"); ITextComponent nameComponent = new StringTextComponent(!name.isEmpty() ? name : "<empty>");
nameComponent.getStyle().setColor(!name.isEmpty() ? TextFormatting.GRAY : TextFormatting.DARK_GRAY); nameComponent.getStyle().setColor(!name.isEmpty() ? TextFormatting.GRAY : TextFormatting.DARK_GRAY);
ITextComponent timestamp = new TextComponentString(" @ " + new Date(waypoint.getCreationTimestamp())); ITextComponent timestamp = new StringTextComponent(" @ " + new Date(waypoint.getCreationTimestamp()));
timestamp.getStyle().setColor(TextFormatting.DARK_GRAY); timestamp.getStyle().setColor(TextFormatting.DARK_GRAY);
component.appendSibling(tagComponent); component.appendSibling(tagComponent);
component.appendSibling(nameComponent); component.appendSibling(nameComponent);
@@ -72,7 +72,7 @@ public class WaypointsCommand extends Command {
component.getStyle() component.getStyle()
.setHoverEvent(new HoverEvent( .setHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT, HoverEvent.Action.SHOW_TEXT,
new TextComponentString("Click to select") new StringTextComponent("Click to select")
)) ))
.setClickEvent(new ClickEvent( .setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND, ClickEvent.Action.RUN_COMMAND,
@@ -136,7 +136,7 @@ public class WaypointsCommand extends Command {
args.requireMax(0); args.requireMax(0);
IWaypoint waypoint = new Waypoint(name, tag, pos); IWaypoint waypoint = new Waypoint(name, tag, pos);
ForWaypoints.waypoints(this.baritone).addWaypoint(waypoint); ForWaypoints.waypoints(this.baritone).addWaypoint(waypoint);
ITextComponent component = new TextComponentString("Waypoint added: "); ITextComponent component = new StringTextComponent("Waypoint added: ");
component.getStyle().setColor(TextFormatting.GRAY); component.getStyle().setColor(TextFormatting.GRAY);
component.appendSibling(toComponent.apply(waypoint, Action.INFO)); component.appendSibling(toComponent.apply(waypoint, Action.INFO));
logDirect(component); logDirect(component);
@@ -194,7 +194,7 @@ public class WaypointsCommand extends Command {
if (action == Action.INFO) { if (action == Action.INFO) {
logDirect(transform.apply(waypoint)); logDirect(transform.apply(waypoint));
logDirect(String.format("Position: %s", waypoint.getLocation())); logDirect(String.format("Position: %s", waypoint.getLocation()));
ITextComponent deleteComponent = new TextComponentString("Click to delete this waypoint"); ITextComponent deleteComponent = new StringTextComponent("Click to delete this waypoint");
deleteComponent.getStyle().setClickEvent(new ClickEvent( deleteComponent.getStyle().setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND, ClickEvent.Action.RUN_COMMAND,
String.format( String.format(
@@ -205,7 +205,7 @@ public class WaypointsCommand extends Command {
waypoint.getCreationTimestamp() waypoint.getCreationTimestamp()
) )
)); ));
ITextComponent goalComponent = new TextComponentString("Click to set goal to this waypoint"); ITextComponent goalComponent = new StringTextComponent("Click to set goal to this waypoint");
goalComponent.getStyle().setClickEvent(new ClickEvent( goalComponent.getStyle().setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND, ClickEvent.Action.RUN_COMMAND,
String.format( String.format(
@@ -216,7 +216,7 @@ public class WaypointsCommand extends Command {
waypoint.getCreationTimestamp() waypoint.getCreationTimestamp()
) )
)); ));
ITextComponent backComponent = new TextComponentString("Click to return to the waypoints list"); ITextComponent backComponent = new StringTextComponent("Click to return to the waypoints list");
backComponent.getStyle().setClickEvent(new ClickEvent( backComponent.getStyle().setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND, ClickEvent.Action.RUN_COMMAND,
String.format( String.format(
@@ -51,6 +51,7 @@ public final class GameEventHandler implements IEventBus, Helper {
try { try {
baritone.bsi = new BlockStateInterface(baritone.getPlayerContext(), true); baritone.bsi = new BlockStateInterface(baritone.getPlayerContext(), true);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace();
baritone.bsi = null; baritone.bsi = null;
} }
} else { } else {
@@ -89,7 +90,7 @@ public final class GameEventHandler implements IEventBus, Helper {
// 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
&& world.getChunkProvider().getChunk(event.getX(), event.getZ(), false, false) != null; && world.getChunkProvider().getChunk(event.getX(), event.getZ(), null, false) != null;
if (isPostPopulate || isPreUnload) { if (isPostPopulate || isPreUnload) {
baritone.getWorldProvider().ifWorldLoaded(worldData -> { baritone.getWorldProvider().ifWorldLoaded(worldData -> {
@@ -25,12 +25,12 @@ import baritone.utils.BlockStateInterface;
import baritone.utils.ToolSet; import baritone.utils.ToolSet;
import baritone.utils.pathing.BetterWorldBorder; import baritone.utils.pathing.BetterWorldBorder;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World; import net.minecraft.world.World;
@@ -79,13 +79,13 @@ public class CalculationContext {
public CalculationContext(IBaritone baritone, boolean forUseOnAnotherThread) { public CalculationContext(IBaritone baritone, boolean forUseOnAnotherThread) {
this.safeForThreadedUse = forUseOnAnotherThread; this.safeForThreadedUse = forUseOnAnotherThread;
this.baritone = baritone; this.baritone = baritone;
EntityPlayerSP player = baritone.getPlayerContext().player(); ClientPlayerEntity player = baritone.getPlayerContext().player();
this.world = baritone.getPlayerContext().world(); this.world = baritone.getPlayerContext().world();
this.worldData = (WorldData) baritone.getWorldProvider().getCurrentWorld(); this.worldData = (WorldData) baritone.getWorldProvider().getCurrentWorld();
this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread);
this.toolSet = new ToolSet(player); this.toolSet = new ToolSet(player);
this.hasThrowaway = Baritone.settings().allowPlace.value && ((Baritone) baritone).getInventoryBehavior().hasGenericThrowaway(); this.hasThrowaway = Baritone.settings().allowPlace.value && ((Baritone) baritone).getInventoryBehavior().hasGenericThrowaway();
this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.value && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.getDimension().isNether(); this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.value && PlayerInventory.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.getDimension().isNether();
this.canSprint = Baritone.settings().allowSprint.value && player.getFoodStats().getFoodLevel() > 6; this.canSprint = Baritone.settings().allowSprint.value && player.getFoodStats().getFoodLevel() > 6;
this.placeBlockCost = Baritone.settings().blockPlacementPenalty.value; this.placeBlockCost = Baritone.settings().blockPlacementPenalty.value;
this.allowBreak = Baritone.settings().allowBreak.value; this.allowBreak = Baritone.settings().allowBreak.value;
@@ -119,7 +119,7 @@ public class CalculationContext {
return baritone; return baritone;
} }
public IBlockState get(int x, int y, int z) { public BlockState get(int x, int y, int z) {
return bsi.get0(x, y, z); // laughs maniacally return bsi.get0(x, y, z); // laughs maniacally
} }
@@ -127,7 +127,7 @@ public class CalculationContext {
return bsi.isLoaded(x, z); return bsi.isLoaded(x, z);
} }
public IBlockState get(BlockPos pos) { public BlockState get(BlockPos pos) {
return get(pos.getX(), pos.getY(), pos.getZ()); return get(pos.getX(), pos.getY(), pos.getZ());
} }
@@ -135,7 +135,7 @@ public class CalculationContext {
return get(x, y, z).getBlock(); return get(x, y, z).getBlock();
} }
public double costOfPlacingAt(int x, int y, int z, IBlockState current) { public double costOfPlacingAt(int x, int y, int z, BlockState current) {
if (!hasThrowaway) { // only true if allowPlace is true, see constructor if (!hasThrowaway) { // only true if allowPlace is true, see constructor
return COST_INF; return COST_INF;
} }
@@ -149,7 +149,7 @@ public class CalculationContext {
return placeBlockCost; return placeBlockCost;
} }
public double breakCostMultiplierAt(int x, int y, int z, IBlockState current) { public double breakCostMultiplierAt(int x, int y, int z, BlockState current) {
if (!allowBreak) { if (!allowBreak) {
return COST_INF; return COST_INF;
} }
@@ -25,8 +25,8 @@ import baritone.api.utils.*;
import baritone.api.utils.input.Input; import baritone.api.utils.input.Input;
import baritone.behavior.PathingBehavior; import baritone.behavior.PathingBehavior;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import net.minecraft.entity.item.EntityFallingBlock; import net.minecraft.entity.item.FallingBlockEntity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@@ -34,7 +34,7 @@ import java.util.*;
public abstract class Movement implements IMovement, MovementHelper { public abstract class Movement implements IMovement, MovementHelper {
public static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN}; public static final Direction[] HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP = {Direction.NORTH, Direction.SOUTH, Direction.EAST, Direction.WEST, Direction.DOWN};
protected final IBaritone baritone; protected final IBaritone baritone;
protected final IPlayerContext ctx; protected final IPlayerContext ctx;
@@ -157,7 +157,7 @@ public abstract class Movement implements IMovement, MovementHelper {
} }
boolean somethingInTheWay = false; boolean somethingInTheWay = false;
for (BetterBlockPos blockPos : positionsToBreak) { for (BetterBlockPos blockPos : positionsToBreak) {
if (!ctx.world().getEntitiesWithinAABB(EntityFallingBlock.class, new AxisAlignedBB(0, 0, 0, 1, 1.1, 1).offset(blockPos)).isEmpty() && Baritone.settings().pauseMiningForFallingBlocks.value) { if (!ctx.world().getEntitiesWithinAABB(FallingBlockEntity.class, new AxisAlignedBB(0, 0, 0, 1, 1.1, 1).offset(blockPos)).isEmpty() && Baritone.settings().pauseMiningForFallingBlocks.value) {
return false; return false;
} }
if (!MovementHelper.canWalkThrough(ctx, blockPos)) { // can't break air, so don't try if (!MovementHelper.canWalkThrough(ctx, blockPos)) { // can't break air, so don't try
@@ -28,18 +28,13 @@ import baritone.pathing.movement.MovementState.MovementTarget;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import baritone.utils.ToolSet; import baritone.utils.ToolSet;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState; import net.minecraft.fluid.*;
import net.minecraft.fluid.FlowingFluid;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.IFluidState;
import net.minecraft.fluid.WaterFluid;
import net.minecraft.init.Blocks;
import net.minecraft.init.Fluids;
import net.minecraft.pathfinding.PathType; import net.minecraft.pathfinding.PathType;
import net.minecraft.state.BooleanProperty; import net.minecraft.state.BooleanProperty;
import net.minecraft.state.properties.SlabType; import net.minecraft.state.properties.SlabType;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
@@ -54,10 +49,10 @@ import static baritone.pathing.movement.Movement.HORIZONTALS_BUT_ALSO_DOWN_____S
*/ */
public interface MovementHelper extends ActionCosts, Helper { public interface MovementHelper extends ActionCosts, Helper {
static boolean avoidBreaking(BlockStateInterface bsi, int x, int y, int z, IBlockState state) { static boolean avoidBreaking(BlockStateInterface bsi, int x, int y, int z, BlockState state) {
Block b = state.getBlock(); Block b = state.getBlock();
return b == Blocks.ICE // ice becomes water, and water can mess up the path return b == Blocks.ICE // ice becomes water, and water can mess up the path
|| b instanceof BlockSilverfish // obvious reasons || b instanceof SilverfishBlock // obvious reasons
// call context.get directly with x,y,z. no need to make 5 new BlockPos for no reason // call context.get directly with x,y,z. no need to make 5 new BlockPos for no reason
|| avoidAdjacentBreaking(bsi, x, y + 1, z, true) || avoidAdjacentBreaking(bsi, x, y + 1, z, true)
|| avoidAdjacentBreaking(bsi, x + 1, y, z, false) || avoidAdjacentBreaking(bsi, x + 1, y, z, false)
@@ -70,13 +65,13 @@ public interface MovementHelper extends ActionCosts, Helper {
// returns true if you should avoid breaking a block that's adjacent to this one (e.g. lava that will start flowing if you give it a path) // returns true if you should avoid breaking a block that's adjacent to this one (e.g. lava that will start flowing if you give it a path)
// this is only called for north, south, east, west, and up. this is NOT called for down. // this is only called for north, south, east, west, and up. this is NOT called for down.
// we assume that it's ALWAYS okay to break the block thats ABOVE liquid // we assume that it's ALWAYS okay to break the block thats ABOVE liquid
IBlockState state = bsi.get0(x, y, z); BlockState state = bsi.get0(x, y, z);
Block block = state.getBlock(); Block block = state.getBlock();
if (!directlyAbove // it is fine to mine a block that has a falling block directly above, this (the cost of breaking the stacked fallings) is included in cost calculations if (!directlyAbove // it is fine to mine a block that has a falling block directly above, this (the cost of breaking the stacked fallings) is included in cost calculations
// therefore if directlyAbove is true, we will actually ignore if this is falling // therefore if directlyAbove is true, we will actually ignore if this is falling
&& block instanceof BlockFalling // obviously, this check is only valid for falling blocks && block instanceof FallingBlock // obviously, this check is only valid for falling blocks
&& Baritone.settings().avoidUpdatingFallingBlocks.value // and if the setting is enabled && Baritone.settings().avoidUpdatingFallingBlocks.value // and if the setting is enabled
&& BlockFalling.canFallThrough(bsi.get0(x, y - 1, z))) { // and if it would fall (i.e. it's unsupported) && FallingBlock.canFallThrough(bsi.get0(x, y - 1, z))) { // and if it would fall (i.e. it's unsupported)
return true; // dont break a block that is adjacent to unsupported gravel because it can cause really weird stuff return true; // dont break a block that is adjacent to unsupported gravel because it can cause really weird stuff
} }
return !state.getFluidState().isEmpty(); return !state.getFluidState().isEmpty();
@@ -90,27 +85,27 @@ public interface MovementHelper extends ActionCosts, Helper {
return canWalkThrough(bsi, x, y, z, bsi.get0(x, y, z)); return canWalkThrough(bsi, x, y, z, bsi.get0(x, y, z));
} }
static boolean canWalkThrough(BlockStateInterface bsi, int x, int y, int z, IBlockState state) { static boolean canWalkThrough(BlockStateInterface bsi, int x, int y, int z, BlockState state) {
Block block = state.getBlock(); Block block = state.getBlock();
if (block instanceof BlockAir) { // early return for most common case if (block instanceof AirBlock) { // early return for most common case
return true; return true;
} }
if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.COBWEB || block == Blocks.END_PORTAL || block == Blocks.COCOA || block instanceof BlockAbstractSkull || block == Blocks.BUBBLE_COLUMN || block instanceof BlockShulkerBox || block instanceof BlockSlab || block instanceof BlockTrapDoor) { if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.COBWEB || block == Blocks.END_PORTAL || block == Blocks.COCOA || block instanceof AbstractSkullBlock || block == Blocks.BUBBLE_COLUMN || block instanceof ShulkerBoxBlock || block instanceof SlabBlock || block instanceof TrapDoorBlock) {
return false; return false;
} }
if (Baritone.settings().blocksToAvoid.value.contains(block)) { if (Baritone.settings().blocksToAvoid.value.contains(block)) {
return false; return false;
} }
if (block instanceof BlockDoor || block instanceof BlockFenceGate) { if (block instanceof DoorBlock || block instanceof FenceGateBlock) {
// Because there's no nice method in vanilla to check if a door is openable or not, we just have to assume // Because there's no nice method in vanilla to check if a door is openable or not, we just have to assume
// that anything that isn't an iron door isn't openable, ignoring that some doors introduced in mods can't // that anything that isn't an iron door isn't openable, ignoring that some doors introduced in mods can't
// be opened by just interacting. // be opened by just interacting.
return block != Blocks.IRON_DOOR; return block != Blocks.IRON_DOOR;
} }
if (block instanceof BlockCarpet) { if (block instanceof CarpetBlock) {
return canWalkOn(bsi, x, y - 1, z); return canWalkOn(bsi, x, y - 1, z);
} }
if (block instanceof BlockSnowLayer) { if (block instanceof SnowBlock) {
// we've already checked doors and fence gates // we've already checked doors and fence gates
// 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
@@ -120,7 +115,7 @@ public interface MovementHelper extends ActionCosts, Helper {
} }
// the check in BlockSnow.isPassable is layers < 5 // the check in BlockSnow.isPassable is layers < 5
// while actually, we want < 3 because 3 or greater makes it impassable in a 2 high ceiling // while actually, we want < 3 because 3 or greater makes it impassable in a 2 high ceiling
if (state.get(BlockSnowLayer.LAYERS) >= 3) { if (state.get(SnowBlock.LAYERS) >= 3) {
return false; return false;
} }
// ok, it's low enough we could walk through it, but is it supported? // ok, it's low enough we could walk through it, but is it supported?
@@ -134,8 +129,8 @@ public interface MovementHelper extends ActionCosts, Helper {
if (Baritone.settings().assumeWalkOnWater.value) { if (Baritone.settings().assumeWalkOnWater.value) {
return false; return false;
} }
IBlockState up = bsi.get0(x, y + 1, z); BlockState up = bsi.get0(x, y + 1, z);
if (!up.getFluidState().isEmpty() || up.getBlock() instanceof BlockLilyPad) { if (!up.getFluidState().isEmpty() || up.getBlock() instanceof LilyPadBlock) {
return false; return false;
} }
return true; return true;
@@ -143,7 +138,7 @@ public interface MovementHelper extends ActionCosts, Helper {
// every block that overrides isPassable with anything more complicated than a "return true;" or "return false;" // every block that overrides isPassable with anything more complicated than a "return true;" or "return false;"
// has already been accounted for above // has already been accounted for above
// therefore it's safe to not construct a blockpos from our x, y, z ints and instead just pass null // therefore it's safe to not construct a blockpos from our x, y, z ints and instead just pass null
return state.allowsMovement(null, BlockPos.ORIGIN, PathType.LAND); // workaround for future compatibility =P return state.allowsMovement(null, BlockPos.ZERO, PathType.LAND); // workaround for future compatibility =P
} }
/** /**
@@ -160,9 +155,9 @@ public interface MovementHelper extends ActionCosts, Helper {
return fullyPassable(context.get(x, y, z)); return fullyPassable(context.get(x, y, z));
} }
static boolean fullyPassable(IBlockState state) { static boolean fullyPassable(BlockState state) {
Block block = state.getBlock(); Block block = state.getBlock();
if (block instanceof BlockAir) { // early return for most common case if (block instanceof AirBlock) { // early return for most common case
return true; return true;
} }
// exceptions - blocks that are isPassable true, but we can't actually jump through // exceptions - blocks that are isPassable true, but we can't actually jump through
@@ -172,21 +167,21 @@ public interface MovementHelper extends ActionCosts, Helper {
|| block == Blocks.VINE || block == Blocks.VINE
|| block == Blocks.LADDER || block == Blocks.LADDER
|| block == Blocks.COCOA || block == Blocks.COCOA
|| block instanceof BlockDoor || block instanceof DoorBlock
|| block instanceof BlockFenceGate || block instanceof FenceGateBlock
|| block instanceof BlockSnow || block instanceof SnowBlock
|| !state.getFluidState().isEmpty() || !state.getFluidState().isEmpty()
|| block instanceof BlockTrapDoor || block instanceof TrapDoorBlock
|| block instanceof BlockEndPortal || block instanceof EndPortalBlock
|| block instanceof BlockSkull || block instanceof SkullBlock
|| block instanceof BlockShulkerBox) { || block instanceof ShulkerBoxBlock) {
return false; return false;
} }
// door, fence gate, liquid, trapdoor have been accounted for, nothing else uses the world or pos parameters // door, fence gate, liquid, trapdoor have been accounted for, nothing else uses the world or pos parameters
return state.allowsMovement(null, null, PathType.LAND); return state.allowsMovement(null, null, PathType.LAND);
} }
static boolean isReplaceable(int x, int y, int z, IBlockState state, BlockStateInterface bsi) { static boolean isReplaceable(int x, int y, int z, BlockState state, BlockStateInterface bsi) {
// 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
@@ -198,16 +193,16 @@ public interface MovementHelper extends ActionCosts, Helper {
* } * }
*/ */
Block block = state.getBlock(); Block block = state.getBlock();
if (block instanceof BlockAir) { if (block instanceof AirBlock) {
// early return for common cases hehe // early return for common cases hehe
return true; return true;
} }
if (block instanceof BlockSnowLayer) { if (block instanceof SnowBlock) {
// 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 (!bsi.worldContainsLoadedChunk(x, z)) { if (!bsi.worldContainsLoadedChunk(x, z)) {
return true; return true;
} }
return state.get(BlockSnowLayer.LAYERS) == 1; return state.get(SnowBlock.LAYERS) == 1;
} }
if (block == Blocks.LARGE_FERN || block == Blocks.TALL_GRASS) { if (block == Blocks.LARGE_FERN || block == Blocks.TALL_GRASS) {
return true; return true;
@@ -216,7 +211,7 @@ public interface MovementHelper extends ActionCosts, Helper {
} }
@Deprecated @Deprecated
static boolean isReplacable(int x, int y, int z, IBlockState state, BlockStateInterface bsi) { static boolean isReplacable(int x, int y, int z, BlockState state, BlockStateInterface bsi) {
return isReplaceable(x, y, z, state, bsi); return isReplaceable(x, y, z, state, bsi);
} }
@@ -225,12 +220,12 @@ public interface MovementHelper extends ActionCosts, Helper {
return false; return false;
} }
IBlockState state = BlockStateInterface.get(ctx, doorPos); BlockState state = BlockStateInterface.get(ctx, doorPos);
if (!(state.getBlock() instanceof BlockDoor)) { if (!(state.getBlock() instanceof DoorBlock)) {
return true; return true;
} }
return isHorizontalBlockPassable(doorPos, state, playerPos, BlockDoor.OPEN); return isHorizontalBlockPassable(doorPos, state, playerPos, DoorBlock.OPEN);
} }
static boolean isGatePassable(IPlayerContext ctx, BlockPos gatePos, BlockPos playerPos) { static boolean isGatePassable(IPlayerContext ctx, BlockPos gatePos, BlockPos playerPos) {
@@ -238,27 +233,27 @@ public interface MovementHelper extends ActionCosts, Helper {
return false; return false;
} }
IBlockState state = BlockStateInterface.get(ctx, gatePos); BlockState state = BlockStateInterface.get(ctx, gatePos);
if (!(state.getBlock() instanceof BlockFenceGate)) { if (!(state.getBlock() instanceof FenceGateBlock)) {
return true; return true;
} }
return state.get(BlockFenceGate.OPEN); return state.get(FenceGateBlock.OPEN);
} }
static boolean isHorizontalBlockPassable(BlockPos blockPos, IBlockState blockState, BlockPos playerPos, BooleanProperty propertyOpen) { static boolean isHorizontalBlockPassable(BlockPos blockPos, BlockState blockState, BlockPos playerPos, BooleanProperty propertyOpen) {
if (playerPos.equals(blockPos)) { if (playerPos.equals(blockPos)) {
return false; return false;
} }
EnumFacing.Axis facing = blockState.get(BlockHorizontal.HORIZONTAL_FACING).getAxis(); Direction.Axis facing = blockState.get(HorizontalBlock.HORIZONTAL_FACING).getAxis();
boolean open = blockState.get(propertyOpen); boolean open = blockState.get(propertyOpen);
EnumFacing.Axis playerFacing; Direction.Axis playerFacing;
if (playerPos.north().equals(blockPos) || playerPos.south().equals(blockPos)) { if (playerPos.north().equals(blockPos) || playerPos.south().equals(blockPos)) {
playerFacing = EnumFacing.Axis.Z; playerFacing = Direction.Axis.Z;
} else if (playerPos.east().equals(blockPos) || playerPos.west().equals(blockPos)) { } else if (playerPos.east().equals(blockPos) || playerPos.west().equals(blockPos)) {
playerFacing = EnumFacing.Axis.X; playerFacing = Direction.Axis.X;
} else { } else {
return true; return true;
} }
@@ -266,7 +261,7 @@ public interface MovementHelper extends ActionCosts, Helper {
return (facing == playerFacing) == open; return (facing == playerFacing) == open;
} }
static boolean avoidWalkingInto(IBlockState state) { static boolean avoidWalkingInto(BlockState state) {
Block block = state.getBlock(); Block block = state.getBlock();
return !state.getFluidState().isEmpty() return !state.getFluidState().isEmpty()
|| block == Blocks.MAGMA_BLOCK || block == Blocks.MAGMA_BLOCK
@@ -289,14 +284,14 @@ public interface MovementHelper extends ActionCosts, Helper {
* @param state The state of the block at the specified location * @param state The state of the block at the specified location
* @return Whether or not the specified block can be walked on * @return Whether or not the specified block can be walked on
*/ */
static boolean canWalkOn(BlockStateInterface bsi, int x, int y, int z, IBlockState state) { static boolean canWalkOn(BlockStateInterface bsi, int x, int y, int z, BlockState state) {
Block block = state.getBlock(); Block block = state.getBlock();
if (block instanceof BlockAir || block == Blocks.MAGMA_BLOCK || block == Blocks.BUBBLE_COLUMN) { if (block instanceof AirBlock || block == Blocks.MAGMA_BLOCK || block == Blocks.BUBBLE_COLUMN) {
// early return for most common case (air) // early return for most common case (air)
// plus magma, which is a normal cube but it hurts you // plus magma, which is a normal cube but it hurts you
return false; return false;
} }
if (state.isBlockNormalCube()) { if (isBlockNormalCube(state)) {
return true; return true;
} }
if (block == Blocks.LADDER || (block == Blocks.VINE && Baritone.settings().allowVines.value)) { // TODO reconsider this if (block == Blocks.LADDER || (block == Blocks.VINE && Baritone.settings().allowVines.value)) { // TODO reconsider this
@@ -311,9 +306,9 @@ public interface MovementHelper extends ActionCosts, Helper {
if (isWater(state)) { if (isWater(state)) {
// since this is called literally millions of times per second, the benefit of not allocating millions of useless "pos.up()" // since this is called literally millions of times per second, the benefit of not allocating millions of useless "pos.up()"
// BlockPos s that we'd just garbage collect immediately is actually noticeable. I don't even think its a decrease in readability // BlockPos s that we'd just garbage collect immediately is actually noticeable. I don't even think its a decrease in readability
IBlockState upState = bsi.get0(x, y + 1, z); BlockState upState = bsi.get0(x, y + 1, z);
Block up = upState.getBlock(); Block up = upState.getBlock();
if (up == Blocks.LILY_PAD || up instanceof BlockCarpet) { if (up == Blocks.LILY_PAD || up instanceof CarpetBlock) {
return true; return true;
} }
if (isFlowing(x, y, z, state, bsi) || upState.getFluidState().getFluid() == Fluids.FLOWING_WATER) { if (isFlowing(x, y, z, state, bsi) || upState.getFluidState().getFluid() == Fluids.FLOWING_WATER) {
@@ -327,19 +322,19 @@ public interface MovementHelper extends ActionCosts, Helper {
if (Baritone.settings().assumeWalkOnLava.value && isLava(state) && !isFlowing(x, y, z, state, bsi)) { if (Baritone.settings().assumeWalkOnLava.value && isLava(state) && !isFlowing(x, y, z, state, bsi)) {
return true; return true;
} }
if (block == Blocks.GLASS || block instanceof BlockStainedGlass) { if (block == Blocks.GLASS || block instanceof StainedGlassBlock) {
return true; return true;
} }
if (block instanceof BlockSlab) { if (block instanceof SlabBlock) {
if (!Baritone.settings().allowWalkOnBottomSlab.value) { if (!Baritone.settings().allowWalkOnBottomSlab.value) {
return state.isTopSolid(); return state.get(SlabBlock.TYPE) != SlabType.BOTTOM;
} }
return true; return true;
} }
return block instanceof BlockStairs; return block instanceof StairsBlock;
} }
static boolean canWalkOn(IPlayerContext ctx, BetterBlockPos pos, IBlockState state) { static boolean canWalkOn(IPlayerContext ctx, BetterBlockPos pos, BlockState state) {
return canWalkOn(new BlockStateInterface(ctx), pos.x, pos.y, pos.z, state); return canWalkOn(new BlockStateInterface(ctx), pos.x, pos.y, pos.z, state);
} }
@@ -367,18 +362,18 @@ public interface MovementHelper extends ActionCosts, Helper {
return canPlaceAgainst(new BlockStateInterface(ctx), pos); return canPlaceAgainst(new BlockStateInterface(ctx), pos);
} }
static boolean canPlaceAgainst(BlockStateInterface bsi, int x, int y, int z, IBlockState state) { static boolean canPlaceAgainst(BlockStateInterface bsi, int x, int y, int z, BlockState state) {
// can we look at the center of a side face of this block and likely be able to place? // can we look at the center of a side face of this block and likely be able to place?
// (thats how this check is used) // (thats how this check is used)
// therefore dont include weird things that we technically could place against (like carpet) but practically can't // therefore dont include weird things that we technically could place against (like carpet) but practically can't
return state.isBlockNormalCube() || state.isFullCube() || state.getBlock() == Blocks.GLASS || state.getBlock() instanceof BlockStainedGlass; return isBlockNormalCube(state) || state.getBlock() == Blocks.GLASS || state.getBlock() instanceof StainedGlassBlock;
} }
static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, boolean includeFalling) { static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, boolean includeFalling) {
return getMiningDurationTicks(context, x, y, z, context.get(x, y, z), includeFalling); return getMiningDurationTicks(context, x, y, z, context.get(x, y, z), includeFalling);
} }
static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, IBlockState state, boolean includeFalling) { static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, BlockState state, boolean includeFalling) {
Block block = state.getBlock(); Block block = state.getBlock();
if (!canWalkThrough(context.bsi, x, y, z, state)) { if (!canWalkThrough(context.bsi, x, y, z, state)) {
if (!state.getFluidState().isEmpty()) { if (!state.getFluidState().isEmpty()) {
@@ -399,8 +394,8 @@ public interface MovementHelper extends ActionCosts, Helper {
result += context.breakBlockAdditionalCost; result += context.breakBlockAdditionalCost;
result *= mult; result *= mult;
if (includeFalling) { if (includeFalling) {
IBlockState above = context.get(x, y + 1, z); BlockState above = context.get(x, y + 1, z);
if (above.getBlock() instanceof BlockFalling) { if (above.getBlock() instanceof FallingBlock) {
result += getMiningDurationTicks(context, x, y + 1, z, above, true); result += getMiningDurationTicks(context, x, y + 1, z, above, true);
} }
} }
@@ -409,9 +404,9 @@ public interface MovementHelper extends ActionCosts, Helper {
return 0; // we won't actually mine it, so don't check fallings above return 0; // we won't actually mine it, so don't check fallings above
} }
static boolean isBottomSlab(IBlockState state) { static boolean isBottomSlab(BlockState state) {
return state.getBlock() instanceof BlockSlab return state.getBlock() instanceof SlabBlock
&& state.get(BlockSlab.TYPE) == SlabType.BOTTOM; && state.get(SlabBlock.TYPE) == SlabType.BOTTOM;
} }
/** /**
@@ -420,7 +415,7 @@ public interface MovementHelper extends ActionCosts, Helper {
* @param ctx The player context * @param ctx The player context
* @param b the blockstate to mine * @param b the blockstate to mine
*/ */
static void switchToBestToolFor(IPlayerContext ctx, IBlockState b) { static void switchToBestToolFor(IPlayerContext ctx, BlockState b) {
switchToBestToolFor(ctx, b, new ToolSet(ctx.player()), BaritoneAPI.getSettings().preferSilkTouch.value); switchToBestToolFor(ctx, b, new ToolSet(ctx.player()), BaritoneAPI.getSettings().preferSilkTouch.value);
} }
@@ -431,7 +426,7 @@ public interface MovementHelper extends ActionCosts, Helper {
* @param b the blockstate to mine * @param b the blockstate to mine
* @param ts previously calculated ToolSet * @param ts previously calculated ToolSet
*/ */
static void switchToBestToolFor(IPlayerContext ctx, IBlockState b, ToolSet ts, boolean preferSilkTouch) { static void switchToBestToolFor(IPlayerContext ctx, BlockState b, ToolSet ts, boolean preferSilkTouch) {
ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock(), preferSilkTouch); ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock(), preferSilkTouch);
} }
@@ -451,7 +446,7 @@ public interface MovementHelper extends ActionCosts, Helper {
* @param state The block state * @param state The block state
* @return Whether or not the block is water * @return Whether or not the block is water
*/ */
static boolean isWater(IBlockState state) { static boolean isWater(BlockState state) {
Fluid f = state.getFluidState().getFluid(); Fluid f = state.getFluidState().getFluid();
return f == Fluids.WATER || f == Fluids.FLOWING_WATER; return f == Fluids.WATER || f == Fluids.FLOWING_WATER;
} }
@@ -468,7 +463,7 @@ public interface MovementHelper extends ActionCosts, Helper {
return isWater(BlockStateInterface.get(ctx, bp)); return isWater(BlockStateInterface.get(ctx, bp));
} }
static boolean isLava(IBlockState state) { static boolean isLava(BlockState state) {
Fluid f = state.getFluidState().getFluid(); Fluid f = state.getFluidState().getFluid();
return f == Fluids.LAVA || f == Fluids.FLOWING_LAVA; return f == Fluids.LAVA || f == Fluids.FLOWING_LAVA;
} }
@@ -484,17 +479,17 @@ public interface MovementHelper extends ActionCosts, Helper {
return isLiquid(BlockStateInterface.get(ctx, p)); return isLiquid(BlockStateInterface.get(ctx, p));
} }
static boolean isLiquid(IBlockState blockState) { static boolean isLiquid(BlockState blockState) {
return !blockState.getFluidState().isEmpty(); return !blockState.getFluidState().isEmpty();
} }
static boolean possiblyFlowing(IBlockState state) { static boolean possiblyFlowing(BlockState state) {
IFluidState fluidState = state.getFluidState(); IFluidState fluidState = state.getFluidState();
return fluidState.getFluid() instanceof FlowingFluid return fluidState.getFluid() instanceof FlowingFluid
&& fluidState.getFluid().getLevel(fluidState) != 8; && fluidState.getFluid().getLevel(fluidState) != 8;
} }
static boolean isFlowing(int x, int y, int z, IBlockState state, BlockStateInterface bsi) { static boolean isFlowing(int x, int y, int z, BlockState state, BlockStateInterface bsi) {
IFluidState fluidState = state.getFluidState(); IFluidState fluidState = state.getFluidState();
if (!(fluidState.getFluid() instanceof FlowingFluid)) { if (!(fluidState.getFluid() instanceof FlowingFluid)) {
return false; return false;
@@ -508,6 +503,16 @@ public interface MovementHelper extends ActionCosts, Helper {
|| possiblyFlowing(bsi.get0(x, y, z - 1)); || possiblyFlowing(bsi.get0(x, y, z - 1));
} }
static boolean isBlockNormalCube(BlockState state) {
Block block = state.getBlock();
if (block instanceof BambooBlock
|| block instanceof MovingPistonBlock
|| block instanceof ScaffoldingBlock
|| block instanceof ShulkerBoxBlock) {
return false;
}
return Block.isOpaque(state.getCollisionShape(null, null));
}
static PlaceResult attemptToPlaceABlock(MovementState state, IBaritone baritone, BlockPos placeAt, boolean preferDown) { static PlaceResult attemptToPlaceABlock(MovementState state, IBaritone baritone, BlockPos placeAt, boolean preferDown) {
IPlayerContext ctx = baritone.getPlayerContext(); IPlayerContext ctx = baritone.getPlayerContext();
@@ -530,7 +535,7 @@ public interface MovementHelper extends ActionCosts, Helper {
double faceZ = (placeAt.getZ() + against1.getZ() + 1.0D) * 0.5D; double faceZ = (placeAt.getZ() + against1.getZ() + 1.0D) * 0.5D;
Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations());
RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance()); RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance());
if (res != null && res.type == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(placeAt)) { if (res != null && res.getType() == RayTraceResult.Type.BLOCK && ((BlockRayTraceResult) res).getPos().equals(against1) && ((BlockRayTraceResult) res).getPos().offset(((BlockRayTraceResult) res).getFace()).equals(placeAt)) {
state.setTarget(new MovementState.MovementTarget(place, true)); state.setTarget(new MovementState.MovementTarget(place, true));
found = true; found = true;
@@ -544,7 +549,7 @@ public interface MovementHelper extends ActionCosts, Helper {
} }
if (ctx.getSelectedBlock().isPresent()) { if (ctx.getSelectedBlock().isPresent()) {
BlockPos selectedBlock = ctx.getSelectedBlock().get(); BlockPos selectedBlock = ctx.getSelectedBlock().get();
EnumFacing side = ctx.objectMouseOver().sideHit; Direction side = ((BlockRayTraceResult) ctx.objectMouseOver()).getFace();
// only way for selectedBlock.equals(placeAt) to be true is if it's replacable // only way for selectedBlock.equals(placeAt) to be true is if it's replacable
if (selectedBlock.equals(placeAt) || (MovementHelper.canPlaceAgainst(ctx, selectedBlock) && selectedBlock.offset(side).equals(placeAt))) { if (selectedBlock.equals(placeAt) || (MovementHelper.canPlaceAgainst(ctx, selectedBlock) && selectedBlock.offset(side).equals(placeAt))) {
((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(true, placeAt.getX(), placeAt.getY(), placeAt.getZ()); ((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(true, placeAt.getX(), placeAt.getY(), placeAt.getZ());
@@ -20,6 +20,8 @@ package baritone.pathing.movement;
import baritone.api.pathing.movement.MovementStatus; import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.Rotation; import baritone.api.utils.Rotation;
import baritone.api.utils.input.Input; import baritone.api.utils.input.Input;
import net.minecraft.client.Minecraft;
import net.minecraft.util.registry.Registry;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -20,7 +20,7 @@ package baritone.pathing.movement;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import baritone.pathing.movement.movements.*; import baritone.pathing.movement.movements.*;
import baritone.utils.pathing.MutableMoveResult; import baritone.utils.pathing.MutableMoveResult;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
/** /**
* An enum of all possible movements attached to all possible directions they could be taken in * An enum of all possible movements attached to all possible directions they could be taken in
@@ -225,7 +225,7 @@ public enum Moves {
public Movement apply0(CalculationContext context, BetterBlockPos src) { public Movement apply0(CalculationContext context, BetterBlockPos src) {
MutableMoveResult res = new MutableMoveResult(); MutableMoveResult res = new MutableMoveResult();
apply(context, src.x, src.y, src.z, res); apply(context, src.x, src.y, src.z, res);
return new MovementDiagonal(context.getBaritone(), src, EnumFacing.NORTH, EnumFacing.EAST, res.y - src.y); return new MovementDiagonal(context.getBaritone(), src, Direction.NORTH, Direction.EAST, res.y - src.y);
} }
@Override @Override
@@ -239,7 +239,7 @@ public enum Moves {
public Movement apply0(CalculationContext context, BetterBlockPos src) { public Movement apply0(CalculationContext context, BetterBlockPos src) {
MutableMoveResult res = new MutableMoveResult(); MutableMoveResult res = new MutableMoveResult();
apply(context, src.x, src.y, src.z, res); apply(context, src.x, src.y, src.z, res);
return new MovementDiagonal(context.getBaritone(), src, EnumFacing.NORTH, EnumFacing.WEST, res.y - src.y); return new MovementDiagonal(context.getBaritone(), src, Direction.NORTH, Direction.WEST, res.y - src.y);
} }
@Override @Override
@@ -253,7 +253,7 @@ public enum Moves {
public Movement apply0(CalculationContext context, BetterBlockPos src) { public Movement apply0(CalculationContext context, BetterBlockPos src) {
MutableMoveResult res = new MutableMoveResult(); MutableMoveResult res = new MutableMoveResult();
apply(context, src.x, src.y, src.z, res); apply(context, src.x, src.y, src.z, res);
return new MovementDiagonal(context.getBaritone(), src, EnumFacing.SOUTH, EnumFacing.EAST, res.y - src.y); return new MovementDiagonal(context.getBaritone(), src, Direction.SOUTH, Direction.EAST, res.y - src.y);
} }
@Override @Override
@@ -267,7 +267,7 @@ public enum Moves {
public Movement apply0(CalculationContext context, BetterBlockPos src) { public Movement apply0(CalculationContext context, BetterBlockPos src) {
MutableMoveResult res = new MutableMoveResult(); MutableMoveResult res = new MutableMoveResult();
apply(context, src.x, src.y, src.z, res); apply(context, src.x, src.y, src.z, res);
return new MovementDiagonal(context.getBaritone(), src, EnumFacing.SOUTH, EnumFacing.WEST, res.y - src.y); return new MovementDiagonal(context.getBaritone(), src, Direction.SOUTH, Direction.WEST, res.y - src.y);
} }
@Override @Override
@@ -279,48 +279,48 @@ public enum Moves {
PARKOUR_NORTH(0, 0, -4, true, true) { PARKOUR_NORTH(0, 0, -4, true, true) {
@Override @Override
public Movement apply0(CalculationContext context, BetterBlockPos src) { public Movement apply0(CalculationContext context, BetterBlockPos src) {
return MovementParkour.cost(context, src, EnumFacing.NORTH); return MovementParkour.cost(context, src, Direction.NORTH);
} }
@Override @Override
public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) {
MovementParkour.cost(context, x, y, z, EnumFacing.NORTH, result); MovementParkour.cost(context, x, y, z, Direction.NORTH, result);
} }
}, },
PARKOUR_SOUTH(0, 0, +4, true, true) { PARKOUR_SOUTH(0, 0, +4, true, true) {
@Override @Override
public Movement apply0(CalculationContext context, BetterBlockPos src) { public Movement apply0(CalculationContext context, BetterBlockPos src) {
return MovementParkour.cost(context, src, EnumFacing.SOUTH); return MovementParkour.cost(context, src, Direction.SOUTH);
} }
@Override @Override
public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) {
MovementParkour.cost(context, x, y, z, EnumFacing.SOUTH, result); MovementParkour.cost(context, x, y, z, Direction.SOUTH, result);
} }
}, },
PARKOUR_EAST(+4, 0, 0, true, true) { PARKOUR_EAST(+4, 0, 0, true, true) {
@Override @Override
public Movement apply0(CalculationContext context, BetterBlockPos src) { public Movement apply0(CalculationContext context, BetterBlockPos src) {
return MovementParkour.cost(context, src, EnumFacing.EAST); return MovementParkour.cost(context, src, Direction.EAST);
} }
@Override @Override
public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) {
MovementParkour.cost(context, x, y, z, EnumFacing.EAST, result); MovementParkour.cost(context, x, y, z, Direction.EAST, result);
} }
}, },
PARKOUR_WEST(-4, 0, 0, true, true) { PARKOUR_WEST(-4, 0, 0, true, true) {
@Override @Override
public Movement apply0(CalculationContext context, BetterBlockPos src) { public Movement apply0(CalculationContext context, BetterBlockPos src) {
return MovementParkour.cost(context, src, EnumFacing.WEST); return MovementParkour.cost(context, src, Direction.WEST);
} }
@Override @Override
public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) { public void apply(CalculationContext context, int x, int y, int z, MutableMoveResult result) {
MovementParkour.cost(context, x, y, z, EnumFacing.WEST, result); MovementParkour.cost(context, x, y, z, Direction.WEST, result);
} }
}; };
@@ -27,12 +27,11 @@ import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState; import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.FallingBlock;
import net.minecraft.util.Direction;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing;
import java.util.Set; import java.util.Set;
public class MovementAscend extends Movement { public class MovementAscend extends Movement {
@@ -66,7 +65,7 @@ public class MovementAscend extends Movement {
} }
public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) { public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) {
IBlockState toPlace = context.get(destX, y, destZ); BlockState toPlace = context.get(destX, y, destZ);
double additionalPlacementCost = 0; double additionalPlacementCost = 0;
if (!MovementHelper.canWalkOn(context.bsi, destX, y, destZ, toPlace)) { if (!MovementHelper.canWalkOn(context.bsi, destX, y, destZ, toPlace)) {
additionalPlacementCost = context.costOfPlacingAt(destX, y, destZ, toPlace); additionalPlacementCost = context.costOfPlacingAt(destX, y, destZ, toPlace);
@@ -93,26 +92,26 @@ public class MovementAscend extends Movement {
return COST_INF; return COST_INF;
} }
} }
IBlockState srcUp2 = context.get(x, y + 2, z); // used lower down anyway BlockState srcUp2 = context.get(x, y + 2, z); // used lower down anyway
if (context.get(x, y + 3, z).getBlock() instanceof BlockFalling && (MovementHelper.canWalkThrough(context.bsi, x, y + 1, z) || !(srcUp2.getBlock() instanceof BlockFalling))) {//it would fall on us and possibly suffocate us if (context.get(x, y + 3, z).getBlock() instanceof FallingBlock && (MovementHelper.canWalkThrough(context.bsi, x, y + 1, z) || !(srcUp2.getBlock() instanceof FallingBlock))) {//it would fall on us and possibly suffocate us
// HOWEVER, we assume that we're standing in the start position // HOWEVER, we assume that we're standing in the start position
// that means that src and src.up(1) are both air // that means that src and src.up(1) are both air
// maybe they aren't now, but they will be by the time this starts // maybe they aren't now, but they will be by the time this starts
// if the lower one is can't walk through and the upper one is falling, that means that by standing on src // if the lower one is can't walk through and the upper one is falling, that means that by standing on src
// (the presupposition of this Movement) // (the presupposition of this Movement)
// we have necessarily already cleared the entire BlockFalling stack // we have necessarily already cleared the entire FallingBlock stack
// on top of our head // on top of our head
// as in, if we have a block, then two BlockFallings on top of it // as in, if we have a block, then two FallingBlocks on top of it
// and that block is x, y+1, z, and we'd have to clear it to even start this movement // and that block is x, y+1, z, and we'd have to clear it to even start this movement
// we don't need to worry about those BlockFallings because we've already cleared them // we don't need to worry about those FallingBlocks because we've already cleared them
return COST_INF; return COST_INF;
// you may think we only need to check srcUp2, not srcUp // you may think we only need to check srcUp2, not srcUp
// however, in the scenario where glitchy world gen where unsupported sand / gravel generates // however, in the scenario where glitchy world gen where unsupported sand / gravel generates
// it's possible srcUp is AIR from the start, and srcUp2 is falling // it's possible srcUp is AIR from the start, and srcUp2 is falling
// and in that scenario, when we arrive and break srcUp2, that lets srcUp3 fall on us and suffocate us // and in that scenario, when we arrive and break srcUp2, that lets srcUp3 fall on us and suffocate us
} }
IBlockState srcDown = context.get(x, y - 1, z); BlockState srcDown = context.get(x, y - 1, z);
if (srcDown.getBlock() == Blocks.LADDER || srcDown.getBlock() == Blocks.VINE) { if (srcDown.getBlock() == Blocks.LADDER || srcDown.getBlock() == Blocks.VINE) {
return COST_INF; return COST_INF;
} }
@@ -172,7 +171,7 @@ public class MovementAscend extends Movement {
return state.setStatus(MovementStatus.SUCCESS); return state.setStatus(MovementStatus.SUCCESS);
} }
IBlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace); BlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace);
if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) { if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) {
ticksWithoutPlacement++; ticksWithoutPlacement++;
if (MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false) == PlaceResult.READY_TO_PLACE) { if (MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false) == PlaceResult.READY_TO_PLACE) {
@@ -203,7 +202,7 @@ public class MovementAscend extends Movement {
double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ); double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ); double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
double lateralMotion = xAxis * ctx.player().motionZ + zAxis * ctx.player().motionX; double lateralMotion = xAxis * ctx.player().getMotion().z + zAxis * ctx.player().getMotion().x;
if (Math.abs(lateralMotion) > 0.1) { if (Math.abs(lateralMotion) > 0.1) {
return state; return state;
} }
@@ -225,7 +224,7 @@ public class MovementAscend extends Movement {
public boolean headBonkClear() { public boolean headBonkClear() {
BetterBlockPos startUp = src.up(2); BetterBlockPos startUp = src.up(2);
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
BetterBlockPos check = startUp.offset(EnumFacing.byHorizontalIndex(i)); BetterBlockPos check = startUp.offset(Direction.byHorizontalIndex(i));
if (!MovementHelper.canWalkThrough(ctx, check)) { if (!MovementHelper.canWalkThrough(ctx, check)) {
// We might bonk our head // We might bonk our head
return false; return false;
@@ -31,10 +31,10 @@ import baritone.utils.BlockStateInterface;
import baritone.utils.pathing.MutableMoveResult; import baritone.utils.pathing.MutableMoveResult;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockFalling; import net.minecraft.block.BlockState;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.Blocks;
import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.block.FallingBlock;
import net.minecraft.init.Blocks; import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
@@ -71,7 +71,7 @@ public class MovementDescend extends Movement {
public static void cost(CalculationContext context, int x, int y, int z, int destX, int destZ, MutableMoveResult res) { public static void cost(CalculationContext context, int x, int y, int z, int destX, int destZ, MutableMoveResult res) {
double totalCost = 0; double totalCost = 0;
IBlockState destDown = context.get(destX, y - 1, destZ); BlockState destDown = context.get(destX, y - 1, destZ);
totalCost += MovementHelper.getMiningDurationTicks(context, destX, y - 1, destZ, destDown, false); totalCost += MovementHelper.getMiningDurationTicks(context, destX, y - 1, destZ, destDown, false);
if (totalCost >= COST_INF) { if (totalCost >= COST_INF) {
return; return;
@@ -100,7 +100,7 @@ public class MovementDescend extends Movement {
//A is plausibly breakable by either descend or fall //A is plausibly breakable by either descend or fall
//C, D, etc determine the length of the fall //C, D, etc determine the length of the fall
IBlockState below = context.get(destX, y - 2, destZ); BlockState below = context.get(destX, y - 2, destZ);
if (!MovementHelper.canWalkOn(context.bsi, destX, y - 2, destZ, below)) { if (!MovementHelper.canWalkOn(context.bsi, destX, y - 2, destZ, below)) {
dynamicFallCost(context, x, y, z, destX, destZ, totalCost, below, res); dynamicFallCost(context, x, y, z, destX, destZ, totalCost, below, res);
return; return;
@@ -123,8 +123,8 @@ public class MovementDescend extends Movement {
res.cost = totalCost; res.cost = totalCost;
} }
public static boolean dynamicFallCost(CalculationContext context, int x, int y, int z, int destX, int destZ, double frontBreak, IBlockState below, MutableMoveResult res) { public static boolean dynamicFallCost(CalculationContext context, int x, int y, int z, int destX, int destZ, double frontBreak, BlockState below, MutableMoveResult res) {
if (frontBreak != 0 && context.get(destX, y + 2, destZ).getBlock() instanceof BlockFalling) { if (frontBreak != 0 && context.get(destX, y + 2, destZ).getBlock() instanceof FallingBlock) {
// if frontBreak is 0 we can actually get through this without updating the falling block and making it actually fall // if frontBreak is 0 we can actually get through this without updating the falling block and making it actually fall
// but if frontBreak is nonzero, we're breaking blocks in front, so don't let anything fall through this column, // but if frontBreak is nonzero, we're breaking blocks in front, so don't let anything fall through this column,
// and potentially replace the water we're going to fall into // and potentially replace the water we're going to fall into
@@ -142,7 +142,7 @@ public class MovementDescend extends Movement {
// this check prevents it from getting the block at y=-1 and crashing // this check prevents it from getting the block at y=-1 and crashing
return false; return false;
} }
IBlockState ontoBlock = context.get(destX, newY, destZ); BlockState ontoBlock = context.get(destX, newY, destZ);
int unprotectedFallHeight = fallHeight - (y - effectiveStartHeight); // equal to fallHeight - y + effectiveFallHeight, which is equal to -newY + effectiveFallHeight, which is equal to effectiveFallHeight - newY int unprotectedFallHeight = fallHeight - (y - effectiveStartHeight); // equal to fallHeight - y + effectiveFallHeight, which is equal to -newY + effectiveFallHeight, which is equal to effectiveFallHeight - newY
double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[unprotectedFallHeight] + frontBreak + costSoFar; double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[unprotectedFallHeight] + frontBreak + costSoFar;
if (MovementHelper.isWater(ontoBlock)) { if (MovementHelper.isWater(ontoBlock)) {
@@ -222,7 +222,7 @@ public class MovementDescend extends Movement {
if (safeMode()) { if (safeMode()) {
double destX = (src.getX() + 0.5) * 0.17 + (dest.getX() + 0.5) * 0.83; double destX = (src.getX() + 0.5) * 0.17 + (dest.getX() + 0.5) * 0.83;
double destZ = (src.getZ() + 0.5) * 0.17 + (dest.getZ() + 0.5) * 0.83; double destZ = (src.getZ() + 0.5) * 0.17 + (dest.getZ() + 0.5) * 0.83;
EntityPlayerSP player = ctx.player(); ClientPlayerEntity player = ctx.player();
state.setTarget(new MovementState.MovementTarget( state.setTarget(new MovementState.MovementTarget(
new Rotation(RotationUtils.calcRotationFromVec3d(player.getEyePosition(1.0F), new Rotation(RotationUtils.calcRotationFromVec3d(player.getEyePosition(1.0F),
new Vec3d(destX, dest.getY(), destZ), new Vec3d(destX, dest.getY(), destZ),
@@ -30,9 +30,9 @@ import baritone.utils.BlockStateInterface;
import baritone.utils.pathing.MutableMoveResult; import baritone.utils.pathing.MutableMoveResult;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.init.Blocks; import net.minecraft.block.Blocks;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import java.util.ArrayList; import java.util.ArrayList;
@@ -43,12 +43,12 @@ public class MovementDiagonal extends Movement {
private static final double SQRT_2 = Math.sqrt(2); private static final double SQRT_2 = Math.sqrt(2);
public MovementDiagonal(IBaritone baritone, BetterBlockPos start, EnumFacing dir1, EnumFacing dir2, int dy) { public MovementDiagonal(IBaritone baritone, BetterBlockPos start, Direction dir1, Direction dir2, int dy) {
this(baritone, start, start.offset(dir1), start.offset(dir2), dir2, dy); this(baritone, start, start.offset(dir1), start.offset(dir2), dir2, dy);
// super(start, start.offset(dir1).offset(dir2), new BlockPos[]{start.offset(dir1), start.offset(dir1).up(), start.offset(dir2), start.offset(dir2).up(), start.offset(dir1).offset(dir2), start.offset(dir1).offset(dir2).up()}, new BlockPos[]{start.offset(dir1).offset(dir2).down()}); // super(start, start.offset(dir1).offset(dir2), new BlockPos[]{start.offset(dir1), start.offset(dir1).up(), start.offset(dir2), start.offset(dir2).up(), start.offset(dir1).offset(dir2), start.offset(dir1).offset(dir2).up()}, new BlockPos[]{start.offset(dir1).offset(dir2).down()});
} }
private MovementDiagonal(IBaritone baritone, BetterBlockPos start, BetterBlockPos dir1, BetterBlockPos dir2, EnumFacing drr2, int dy) { private MovementDiagonal(IBaritone baritone, BetterBlockPos start, BetterBlockPos dir1, BetterBlockPos dir2, Direction drr2, int dy) {
this(baritone, start, dir1.offset(drr2).up(dy), dir1, dir2); this(baritone, start, dir1.offset(drr2).up(dy), dir1, dir2);
} }
@@ -83,9 +83,9 @@ public class MovementDiagonal extends Movement {
if (!MovementHelper.canWalkThrough(context.bsi, destX, y + 1, destZ)) { if (!MovementHelper.canWalkThrough(context.bsi, destX, y + 1, destZ)) {
return; return;
} }
IBlockState destInto = context.get(destX, y, destZ); BlockState destInto = context.get(destX, y, destZ);
boolean ascend = false; boolean ascend = false;
IBlockState destWalkOn; BlockState destWalkOn;
boolean descend = false; boolean descend = false;
if (!MovementHelper.canWalkThrough(context.bsi, destX, y, destZ, destInto)) { if (!MovementHelper.canWalkThrough(context.bsi, destX, y, destZ, destInto)) {
ascend = true; ascend = true;
@@ -116,16 +116,16 @@ public class MovementDiagonal extends Movement {
if (fromDown == Blocks.SOUL_SAND) { if (fromDown == Blocks.SOUL_SAND) {
multiplier += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2; multiplier += (WALK_ONE_OVER_SOUL_SAND_COST - WALK_ONE_BLOCK_COST) / 2;
} }
IBlockState cuttingOver1 = context.get(x, y - 1, destZ); BlockState cuttingOver1 = context.get(x, y - 1, destZ);
if (cuttingOver1.getBlock() == Blocks.MAGMA_BLOCK || MovementHelper.isLava(cuttingOver1)) { if (cuttingOver1.getBlock() == Blocks.MAGMA_BLOCK || MovementHelper.isLava(cuttingOver1)) {
return; return;
} }
IBlockState cuttingOver2 = context.get(destX, y - 1, z); BlockState cuttingOver2 = context.get(destX, y - 1, z);
if (cuttingOver2.getBlock() == Blocks.MAGMA_BLOCK || MovementHelper.isLava(cuttingOver2)) { if (cuttingOver2.getBlock() == Blocks.MAGMA_BLOCK || MovementHelper.isLava(cuttingOver2)) {
return; return;
} }
boolean water = false; boolean water = false;
IBlockState startState = context.get(x, y, z); BlockState startState = context.get(x, y, z);
Block startIn = startState.getBlock(); Block startIn = startState.getBlock();
if (MovementHelper.isWater(startState) || MovementHelper.isWater(destInto)) { if (MovementHelper.isWater(startState) || MovementHelper.isWater(destInto)) {
if (ascend) { if (ascend) {
@@ -137,8 +137,8 @@ public class MovementDiagonal extends Movement {
multiplier = context.waterWalkSpeed; multiplier = context.waterWalkSpeed;
water = true; water = true;
} }
IBlockState pb0 = context.get(x, y, destZ); BlockState pb0 = context.get(x, y, destZ);
IBlockState pb2 = context.get(destX, y, z); BlockState pb2 = context.get(destX, y, z);
if (ascend) { if (ascend) {
boolean ATop = MovementHelper.canWalkThrough(context.bsi, x, y + 2, destZ); boolean ATop = MovementHelper.canWalkThrough(context.bsi, x, y + 2, destZ);
boolean AMid = MovementHelper.canWalkThrough(context.bsi, x, y + 1, destZ); boolean AMid = MovementHelper.canWalkThrough(context.bsi, x, y + 1, destZ);
@@ -168,13 +168,13 @@ public class MovementDiagonal extends Movement {
// so no need to check pb1 as well, might as well return early here // so no need to check pb1 as well, might as well return early here
return; return;
} }
IBlockState pb1 = context.get(x, y + 1, destZ); BlockState pb1 = context.get(x, y + 1, destZ);
optionA += MovementHelper.getMiningDurationTicks(context, x, y + 1, destZ, pb1, true); optionA += MovementHelper.getMiningDurationTicks(context, x, y + 1, destZ, pb1, true);
if (optionA != 0 && optionB != 0) { if (optionA != 0 && optionB != 0) {
// same deal, if pb1 makes optionA nonzero and option B already was nonzero, pb3 can't affect the result // same deal, if pb1 makes optionA nonzero and option B already was nonzero, pb3 can't affect the result
return; return;
} }
IBlockState pb3 = context.get(destX, y + 1, z); BlockState pb3 = context.get(destX, y + 1, z);
if (optionA == 0 && ((MovementHelper.avoidWalkingInto(pb2) && pb2.getBlock() != Blocks.WATER) || MovementHelper.avoidWalkingInto(pb3))) { if (optionA == 0 && ((MovementHelper.avoidWalkingInto(pb2) && pb2.getBlock() != Blocks.WATER) || MovementHelper.avoidWalkingInto(pb3))) {
// at this point we're done calculating optionA, so we can check if it's actually possible to edge around in that direction // at this point we're done calculating optionA, so we can check if it's actually possible to edge around in that direction
return; return;
@@ -26,8 +26,8 @@ import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState; import baritone.pathing.movement.MovementState;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.init.Blocks; import net.minecraft.block.Blocks;
import java.util.Set; import java.util.Set;
@@ -62,7 +62,7 @@ public class MovementDownward extends Movement {
if (!MovementHelper.canWalkOn(context.bsi, x, y - 2, z)) { if (!MovementHelper.canWalkOn(context.bsi, x, y - 2, z)) {
return COST_INF; return COST_INF;
} }
IBlockState down = context.get(x, y - 1, z); BlockState down = context.get(x, y - 1, z);
Block downBlock = down.getBlock(); Block downBlock = down.getBlock();
if (downBlock == Blocks.LADDER || downBlock == Blocks.VINE) { if (downBlock == Blocks.LADDER || downBlock == Blocks.VINE) {
return LADDER_DOWN_ONE_COST; return LADDER_DOWN_ONE_COST;
@@ -31,14 +31,14 @@ import baritone.pathing.movement.MovementState;
import baritone.pathing.movement.MovementState.MovementTarget; import baritone.pathing.movement.MovementState.MovementTarget;
import baritone.utils.pathing.MutableMoveResult; import baritone.utils.pathing.MutableMoveResult;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockLadder; import net.minecraft.block.BlockState;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.Blocks;
import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.block.LadderBlock;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.fluid.WaterFluid; import net.minecraft.fluid.WaterFluid;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.item.Items;
import net.minecraft.util.Direction;
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.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
@@ -92,11 +92,11 @@ public class MovementFall extends Movement {
BlockPos playerFeet = ctx.playerFeet(); BlockPos playerFeet = ctx.playerFeet();
Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()); Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations());
Rotation targetRotation = null; Rotation targetRotation = null;
IBlockState destState = ctx.world().getBlockState(dest); BlockState destState = ctx.world().getBlockState(dest);
Block destBlock = destState.getBlock(); Block destBlock = destState.getBlock();
boolean isWater = destState.getFluidState().getFluid() instanceof WaterFluid; boolean isWater = destState.getFluidState().getFluid() instanceof WaterFluid;
if (!isWater && willPlaceBucket() && !playerFeet.equals(dest)) { if (!isWater && willPlaceBucket() && !playerFeet.equals(dest)) {
if (!InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER)) || ctx.world().getDimension().isNether()) { if (!PlayerInventory.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER)) || ctx.world().getDimension().isNether()) {
return state.setStatus(MovementStatus.UNREACHABLE); return state.setStatus(MovementStatus.UNREACHABLE);
} }
@@ -117,15 +117,15 @@ public class MovementFall extends Movement {
} }
if (playerFeet.equals(dest) && (ctx.player().posY - playerFeet.getY() < 0.094 || isWater)) { // 0.094 because lilypads if (playerFeet.equals(dest) && (ctx.player().posY - playerFeet.getY() < 0.094 || isWater)) { // 0.094 because lilypads
if (isWater) { // only match water, not flowing water (which we cannot pick up with a bucket) if (isWater) { // only match water, not flowing water (which we cannot pick up with a bucket)
if (InventoryPlayer.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) { if (PlayerInventory.isHotbar(ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY))) {
ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY); ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_EMPTY);
if (ctx.player().motionY >= 0) { if (ctx.player().getMotion().y >= 0) {
return state.setInput(Input.CLICK_RIGHT, true); return state.setInput(Input.CLICK_RIGHT, true);
} else { } else {
return state; return state;
} }
} else { } else {
if (ctx.player().motionY >= 0) { if (ctx.player().getMotion().y >= 0) {
return state.setStatus(MovementStatus.SUCCESS); return state.setStatus(MovementStatus.SUCCESS);
} // don't else return state; we need to stay centered because this water might be flowing under the surface } // don't else return state; we need to stay centered because this water might be flowing under the surface
} }
@@ -134,13 +134,13 @@ public class MovementFall extends Movement {
} }
} }
Vec3d destCenter = VecUtils.getBlockPosCenter(dest); // we are moving to the 0.5 center not the edge (like if we were falling on a ladder) Vec3d destCenter = VecUtils.getBlockPosCenter(dest); // we are moving to the 0.5 center not the edge (like if we were falling on a ladder)
if (Math.abs(ctx.player().posX + ctx.player().motionX - destCenter.x) > 0.1 || Math.abs(ctx.player().posZ + ctx.player().motionZ - destCenter.z) > 0.1) { if (Math.abs(ctx.player().posX + ctx.player().getMotion().x - destCenter.x) > 0.1 || Math.abs(ctx.player().posZ + ctx.player().getMotion().z - destCenter.z) > 0.1) {
if (!ctx.player().onGround && Math.abs(ctx.player().motionY) > 0.4) { if (!ctx.player().onGround && Math.abs(ctx.player().getMotion().y) > 0.4) {
state.setInput(Input.SNEAK, true); state.setInput(Input.SNEAK, true);
} }
state.setInput(Input.MOVE_FORWARD, true); state.setInput(Input.MOVE_FORWARD, true);
} }
Vec3i avoid = Optional.ofNullable(avoid()).map(EnumFacing::getDirectionVec).orElse(null); Vec3i avoid = Optional.ofNullable(avoid()).map(Direction::getDirectionVec).orElse(null);
if (avoid == null) { if (avoid == null) {
avoid = src.subtract(dest); avoid = src.subtract(dest);
} else { } else {
@@ -158,11 +158,11 @@ public class MovementFall extends Movement {
return state; return state;
} }
private EnumFacing avoid() { private Direction avoid() {
for (int i = 0; i < 15; i++) { for (int i = 0; i < 15; i++) {
IBlockState state = ctx.world().getBlockState(ctx.playerFeet().down(i)); BlockState state = ctx.world().getBlockState(ctx.playerFeet().down(i));
if (state.getBlock() == Blocks.LADDER) { if (state.getBlock() == Blocks.LADDER) {
return state.get(BlockLadder.FACING); return state.get(LadderBlock.FACING);
} }
} }
return null; return null;
@@ -28,12 +28,12 @@ import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import baritone.utils.pathing.MutableMoveResult; import baritone.utils.pathing.MutableMoveResult;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockStairs; import net.minecraft.block.BlockState;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.Blocks;
import net.minecraft.block.StairsBlock;
import net.minecraft.fluid.Fluids;
import net.minecraft.fluid.WaterFluid; import net.minecraft.fluid.WaterFluid;
import net.minecraft.init.Blocks; import net.minecraft.util.Direction;
import net.minecraft.init.Fluids;
import net.minecraft.util.EnumFacing;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
@@ -42,25 +42,25 @@ public class MovementParkour extends Movement {
private static final BetterBlockPos[] EMPTY = new BetterBlockPos[]{}; private static final BetterBlockPos[] EMPTY = new BetterBlockPos[]{};
private final EnumFacing direction; private final Direction direction;
private final int dist; private final int dist;
private final boolean ascend; private final boolean ascend;
private MovementParkour(IBaritone baritone, BetterBlockPos src, int dist, EnumFacing dir, boolean ascend) { private MovementParkour(IBaritone baritone, BetterBlockPos src, int dist, Direction dir, boolean ascend) {
super(baritone, src, src.offset(dir, dist).up(ascend ? 1 : 0), EMPTY, src.offset(dir, dist).down(ascend ? 0 : 1)); super(baritone, src, src.offset(dir, dist).up(ascend ? 1 : 0), EMPTY, src.offset(dir, dist).down(ascend ? 0 : 1));
this.direction = dir; this.direction = dir;
this.dist = dist; this.dist = dist;
this.ascend = ascend; this.ascend = ascend;
} }
public static MovementParkour cost(CalculationContext context, BetterBlockPos src, EnumFacing direction) { public static MovementParkour cost(CalculationContext context, BetterBlockPos src, Direction direction) {
MutableMoveResult res = new MutableMoveResult(); MutableMoveResult res = new MutableMoveResult();
cost(context, src.x, src.y, src.z, direction, res); cost(context, src.x, src.y, src.z, direction, res);
int dist = Math.abs(res.x - src.x) + Math.abs(res.z - src.z); int dist = Math.abs(res.x - src.x) + Math.abs(res.z - src.z);
return new MovementParkour(context.getBaritone(), src, dist, direction, res.y > src.y); return new MovementParkour(context.getBaritone(), src, dist, direction, res.y > src.y);
} }
public static void cost(CalculationContext context, int x, int y, int z, EnumFacing dir, MutableMoveResult res) { public static void cost(CalculationContext context, int x, int y, int z, Direction dir, MutableMoveResult res) {
if (!context.allowParkour) { if (!context.allowParkour) {
return; return;
} }
@@ -74,7 +74,7 @@ public class MovementParkour extends Movement {
// most common case at the top -- the adjacent block isn't air // most common case at the top -- the adjacent block isn't air
return; return;
} }
IBlockState adj = context.get(x + xDiff, y - 1, z + zDiff); BlockState adj = context.get(x + xDiff, y - 1, z + zDiff);
if (MovementHelper.canWalkOn(context.bsi, x + xDiff, y - 1, z + zDiff, adj)) { // don't parkour if we could just traverse (for now) if (MovementHelper.canWalkOn(context.bsi, x + xDiff, y - 1, z + zDiff, adj)) { // don't parkour if we could just traverse (for now)
// second most common case -- we could just traverse not parkour // second most common case -- we could just traverse not parkour
return; return;
@@ -91,8 +91,8 @@ public class MovementParkour extends Movement {
if (!MovementHelper.fullyPassable(context, x, y + 2, z)) { if (!MovementHelper.fullyPassable(context, x, y + 2, z)) {
return; return;
} }
IBlockState standingOn = context.get(x, y - 1, z); BlockState standingOn = context.get(x, y - 1, z);
if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || standingOn.getBlock() instanceof BlockStairs || MovementHelper.isBottomSlab(standingOn) || standingOn.getFluidState().getFluid() != Fluids.EMPTY) { if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || standingOn.getBlock() instanceof StairsBlock || MovementHelper.isBottomSlab(standingOn) || standingOn.getFluidState().getFluid() != Fluids.EMPTY) {
return; return;
} }
int maxJump; int maxJump;
@@ -114,7 +114,7 @@ public class MovementParkour extends Movement {
if (!MovementHelper.fullyPassable(context, destX, y + 2, destZ)) { if (!MovementHelper.fullyPassable(context, destX, y + 2, destZ)) {
return; return;
} }
IBlockState destInto = context.bsi.get0(destX, y, destZ); BlockState destInto = context.bsi.get0(destX, y, destZ);
if (!MovementHelper.fullyPassable(destInto)) { if (!MovementHelper.fullyPassable(destInto)) {
if (i <= 3 && context.allowParkourAscend && context.canSprint && MovementHelper.canWalkOn(context.bsi, destX, y, destZ, destInto) && checkOvershootSafety(context.bsi, destX + xDiff, y + 1, destZ + zDiff)) { if (i <= 3 && context.allowParkourAscend && context.canSprint && MovementHelper.canWalkOn(context.bsi, destX, y, destZ, destInto) && checkOvershootSafety(context.bsi, destX + xDiff, y + 1, destZ + zDiff)) {
res.x = destX; res.x = destX;
@@ -124,7 +124,7 @@ public class MovementParkour extends Movement {
} }
return; return;
} }
IBlockState landingOn = context.bsi.get0(destX, y - 1, destZ); BlockState landingOn = context.bsi.get0(destX, y - 1, destZ);
// farmland needs to be canwalkon otherwise farm can never work at all, but we want to specifically disallow ending a jumy on farmland haha // farmland needs to be canwalkon otherwise farm can never work at all, but we want to specifically disallow ending a jumy on farmland haha
if (landingOn.getBlock() != Blocks.FARMLAND && MovementHelper.canWalkOn(context.bsi, destX, y - 1, destZ, landingOn)) { if (landingOn.getBlock() != Blocks.FARMLAND && MovementHelper.canWalkOn(context.bsi, destX, y - 1, destZ, landingOn)) {
if (checkOvershootSafety(context.bsi, destX + xDiff, y, destZ + zDiff)) { if (checkOvershootSafety(context.bsi, destX + xDiff, y, destZ + zDiff)) {
@@ -148,7 +148,7 @@ public class MovementParkour extends Movement {
// time 2 pop off with that dank skynet parkour place // time 2 pop off with that dank skynet parkour place
int destX = x + 4 * xDiff; int destX = x + 4 * xDiff;
int destZ = z + 4 * zDiff; int destZ = z + 4 * zDiff;
IBlockState toReplace = context.get(destX, y - 1, destZ); BlockState toReplace = context.get(destX, y - 1, destZ);
double placeCost = context.costOfPlacingAt(destX, y - 1, destZ, toReplace); double placeCost = context.costOfPlacingAt(destX, y - 1, destZ, toReplace);
if (placeCost >= COST_INF) { if (placeCost >= COST_INF) {
return; return;
@@ -32,12 +32,10 @@ import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState; import net.minecraft.state.properties.SlabType;
import net.minecraft.init.Blocks;
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 java.util.Objects;
import java.util.Set; import java.util.Set;
public class MovementPillar extends Movement { public class MovementPillar extends Movement {
@@ -57,27 +55,27 @@ public class MovementPillar extends Movement {
} }
public static double cost(CalculationContext context, int x, int y, int z) { public static double cost(CalculationContext context, int x, int y, int z) {
IBlockState fromState = context.get(x, y, z); BlockState fromState = context.get(x, y, z);
Block from = fromState.getBlock(); Block from = fromState.getBlock();
boolean ladder = from == Blocks.LADDER || from == Blocks.VINE; boolean ladder = from == Blocks.LADDER || from == Blocks.VINE;
IBlockState fromDown = context.get(x, y - 1, z); BlockState fromDown = context.get(x, y - 1, z);
if (!ladder) { if (!ladder) {
if (fromDown.getBlock() == Blocks.LADDER || fromDown.getBlock() == Blocks.VINE) { if (fromDown.getBlock() == Blocks.LADDER || fromDown.getBlock() == Blocks.VINE) {
return COST_INF; // can't pillar from a ladder or vine onto something that isn't also climbable return COST_INF; // can't pillar from a ladder or vine onto something that isn't also climbable
} }
if (fromDown.getBlock() instanceof BlockSlab && !fromDown.isTopSolid()) { if (fromDown.getBlock() instanceof SlabBlock && fromDown.get(SlabBlock.TYPE) == SlabType.BOTTOM) {
return COST_INF; // can't pillar up from a bottom slab onto a non ladder return COST_INF; // can't pillar up from a bottom slab onto a non ladder
} }
} }
if (from == Blocks.VINE && !hasAgainst(context, x, y, z)) { // TODO this vine can't be climbed, but we could place a pillar still since vines are replacable, no? perhaps the pillar jump would be impossible because of the slowdown actually. if (from == Blocks.VINE && !hasAgainst(context, x, y, z)) { // TODO this vine can't be climbed, but we could place a pillar still since vines are replacable, no? perhaps the pillar jump would be impossible because of the slowdown actually.
return COST_INF; return COST_INF;
} }
IBlockState toBreak = context.get(x, y + 2, z); BlockState toBreak = context.get(x, y + 2, z);
Block toBreakBlock = toBreak.getBlock(); Block toBreakBlock = toBreak.getBlock();
if (toBreakBlock instanceof BlockFenceGate) { // see issue #172 if (toBreakBlock instanceof FenceGateBlock) { // see issue #172
return COST_INF; return COST_INF;
} }
IBlockState srcUp = null; BlockState srcUp = null;
if (MovementHelper.isWater(toBreak) && MovementHelper.isWater(fromState)) { // TODO should this also be allowed if toBreakBlock is air? if (MovementHelper.isWater(toBreak) && MovementHelper.isWater(fromState)) { // TODO should this also be allowed if toBreakBlock is air?
srcUp = context.get(x, y + 1, z); srcUp = context.get(x, y + 1, z);
if (MovementHelper.isWater(srcUp)) { if (MovementHelper.isWater(srcUp)) {
@@ -91,7 +89,7 @@ public class MovementPillar extends Movement {
if (placeCost >= COST_INF) { if (placeCost >= COST_INF) {
return COST_INF; return COST_INF;
} }
if (fromDown.getBlock() instanceof BlockAir) { if (fromDown.getBlock() instanceof AirBlock) {
placeCost += 0.1; // slightly (1/200th of a second) penalize pillaring on what's currently air placeCost += 0.1; // slightly (1/200th of a second) penalize pillaring on what's currently air
} }
} }
@@ -109,20 +107,20 @@ public class MovementPillar extends Movement {
if (toBreakBlock == Blocks.LADDER || toBreakBlock == Blocks.VINE) { if (toBreakBlock == Blocks.LADDER || toBreakBlock == Blocks.VINE) {
hardness = 0; // we won't actually need to break the ladder / vine because we're going to use it hardness = 0; // we won't actually need to break the ladder / vine because we're going to use it
} else { } else {
IBlockState check = context.get(x, y + 3, z); // the block on top of the one we're going to break, could it fall on us? BlockState check = context.get(x, y + 3, z); // the block on top of the one we're going to break, could it fall on us?
if (check.getBlock() instanceof BlockFalling) { if (check.getBlock() instanceof FallingBlock) {
// see MovementAscend's identical check for breaking a falling block above our head // see MovementAscend's identical check for breaking a falling block above our head
if (srcUp == null) { if (srcUp == null) {
srcUp = context.get(x, y + 1, z); srcUp = context.get(x, y + 1, z);
} }
if (!(toBreakBlock instanceof BlockFalling) || !(srcUp.getBlock() instanceof BlockFalling)) { if (!(toBreakBlock instanceof FallingBlock) || !(srcUp.getBlock() instanceof FallingBlock)) {
return COST_INF; return COST_INF;
} }
} }
// this is commented because it may have had a purpose, but it's very unclear what it was. it's from the minebot era. // this is commented because it may have had a purpose, but it's very unclear what it was. it's from the minebot era.
//if (!MovementHelper.canWalkOn(chkPos, check) || MovementHelper.canWalkThrough(chkPos, check)) {//if the block above where we want to break is not a full block, don't do it //if (!MovementHelper.canWalkOn(chkPos, check) || MovementHelper.canWalkThrough(chkPos, check)) {//if the block above where we want to break is not a full block, don't do it
// TODO why does canWalkThrough mean this action is COST_INF? // TODO why does canWalkThrough mean this action is COST_INF?
// BlockFalling makes sense, and !canWalkOn deals with weird cases like if it were lava // FallingBlock makes sense, and !canWalkOn deals with weird cases like if it were lava
// but I don't understand why canWalkThrough makes it impossible // but I don't understand why canWalkThrough makes it impossible
// return COST_INF; // return COST_INF;
//} //}
@@ -136,23 +134,23 @@ public class MovementPillar extends Movement {
} }
public static boolean hasAgainst(CalculationContext context, int x, int y, int z) { public static boolean hasAgainst(CalculationContext context, int x, int y, int z) {
return context.get(x + 1, y, z).isBlockNormalCube() || return MovementHelper.isBlockNormalCube(context.get(x + 1, y, z)) ||
context.get(x - 1, y, z).isBlockNormalCube() || MovementHelper.isBlockNormalCube(context.get(x - 1, y, z)) ||
context.get(x, y, z + 1).isBlockNormalCube() || MovementHelper.isBlockNormalCube(context.get(x, y, z + 1)) ||
context.get(x, y, z - 1).isBlockNormalCube(); MovementHelper.isBlockNormalCube(context.get(x, y, z - 1));
} }
public static BlockPos getAgainst(CalculationContext context, BetterBlockPos vine) { public static BlockPos getAgainst(CalculationContext context, BetterBlockPos vine) {
if (context.get(vine.north()).isBlockNormalCube()) { if (MovementHelper.isBlockNormalCube(context.get(vine.north()))) {
return vine.north(); return vine.north();
} }
if (context.get(vine.south()).isBlockNormalCube()) { if (MovementHelper.isBlockNormalCube(context.get(vine.south()))) {
return vine.south(); return vine.south();
} }
if (context.get(vine.east()).isBlockNormalCube()) { if (MovementHelper.isBlockNormalCube(context.get(vine.east()))) {
return vine.east(); return vine.east();
} }
if (context.get(vine.west()).isBlockNormalCube()) { if (MovementHelper.isBlockNormalCube(context.get(vine.west()))) {
return vine.west(); return vine.west();
} }
return null; return null;
@@ -169,7 +167,7 @@ public class MovementPillar extends Movement {
return state.setStatus(MovementStatus.UNREACHABLE); return state.setStatus(MovementStatus.UNREACHABLE);
} }
IBlockState fromDown = BlockStateInterface.get(ctx, src); BlockState fromDown = BlockStateInterface.get(ctx, src);
if (MovementHelper.isWater(fromDown) && MovementHelper.isWater(ctx, dest)) { if (MovementHelper.isWater(fromDown) && MovementHelper.isWater(ctx, dest)) {
// stay centered while swimming up a water column // stay centered while swimming up a water column
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()), false)); state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()), false));
@@ -193,7 +191,7 @@ public class MovementPillar extends Movement {
boolean blockIsThere = MovementHelper.canWalkOn(ctx, src) || ladder; boolean blockIsThere = MovementHelper.canWalkOn(ctx, src) || ladder;
if (ladder) { if (ladder) {
BlockPos against = vine ? getAgainst(new CalculationContext(baritone), src) : src.offset(fromDown.get(BlockLadder.FACING).getOpposite()); BlockPos against = vine ? getAgainst(new CalculationContext(baritone), src) : src.offset(fromDown.get(LadderBlock.FACING).getOpposite());
if (against == null) { if (against == null) {
logDirect("Unable to climb vines. Consider disabling allowVines."); logDirect("Unable to climb vines. Consider disabling allowVines.");
return state.setStatus(MovementStatus.UNREACHABLE); return state.setStatus(MovementStatus.UNREACHABLE);
@@ -226,7 +224,7 @@ public class MovementPillar extends Movement {
double diffX = ctx.player().posX - (dest.getX() + 0.5); double diffX = ctx.player().posX - (dest.getX() + 0.5);
double diffZ = ctx.player().posZ - (dest.getZ() + 0.5); double diffZ = ctx.player().posZ - (dest.getZ() + 0.5);
double dist = Math.sqrt(diffX * diffX + diffZ * diffZ); double dist = Math.sqrt(diffX * diffX + diffZ * diffZ);
double flatMotion = Math.sqrt(ctx.player().motionX * ctx.player().motionX + ctx.player().motionZ * ctx.player().motionZ); double flatMotion = Math.sqrt(ctx.player().getMotion().x * ctx.player().getMotion().x + ctx.player().getMotion().z * ctx.player().getMotion().z);
if (dist > 0.17) {//why 0.17? because it seemed like a good number, that's why if (dist > 0.17) {//why 0.17? because it seemed like a good number, that's why
//[explanation added after baritone port lol] also because it needs to be less than 0.2 because of the 0.3 sneak limit //[explanation added after baritone port lol] also because it needs to be less than 0.2 because of the 0.3 sneak limit
//and 0.17 is reasonably less than 0.2 //and 0.17 is reasonably less than 0.2
@@ -243,17 +241,17 @@ public class MovementPillar extends Movement {
if (!blockIsThere) { if (!blockIsThere) {
IBlockState frState = BlockStateInterface.get(ctx, src); BlockState frState = BlockStateInterface.get(ctx, src);
Block fr = frState.getBlock(); Block fr = frState.getBlock();
// TODO: Evaluate usage of getMaterial().isReplaceable() // TODO: Evaluate usage of getMaterial().isReplaceable()
if (!(fr instanceof BlockAir || frState.getMaterial().isReplaceable())) { if (!(fr instanceof AirBlock || frState.getMaterial().isReplaceable())) {
RotationUtils.reachable(ctx.player(), src, ctx.playerController().getBlockReachDistance()) RotationUtils.reachable(ctx.player(), src, ctx.playerController().getBlockReachDistance())
.map(rot -> new MovementState.MovementTarget(rot, true)) .map(rot -> new MovementState.MovementTarget(rot, true))
.ifPresent(state::setTarget); .ifPresent(state::setTarget);
state.setInput(Input.JUMP, false); // breaking is like 5x slower when you're jumping state.setInput(Input.JUMP, false); // breaking is like 5x slower when you're jumping
state.setInput(Input.CLICK_LEFT, true); state.setInput(Input.CLICK_LEFT, true);
blockIsThere = false; blockIsThere = false;
} else if (ctx.player().isSneaking() && (Objects.equals(src.down(), ctx.objectMouseOver().getBlockPos()) || Objects.equals(src, ctx.objectMouseOver().getBlockPos())) && ctx.player().posY > dest.getY() + 0.1) { } else if (ctx.player().isSneaking() && (ctx.isLookingAt(src.down()) || ctx.isLookingAt(src)) && ctx.player().posY > dest.getY() + 0.1) {
state.setInput(Input.CLICK_RIGHT, true); state.setInput(Input.CLICK_RIGHT, true);
} }
} }
@@ -32,9 +32,7 @@ import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.fluid.WaterFluid; import net.minecraft.fluid.WaterFluid;
import net.minecraft.init.Blocks;
import net.minecraft.state.properties.SlabType; import net.minecraft.state.properties.SlabType;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
@@ -70,10 +68,10 @@ public class MovementTraverse extends Movement {
} }
public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) { public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) {
IBlockState pb0 = context.get(destX, y + 1, destZ); BlockState pb0 = context.get(destX, y + 1, destZ);
IBlockState pb1 = context.get(destX, y, destZ); BlockState pb1 = context.get(destX, y, destZ);
IBlockState destOn = context.get(destX, y - 1, destZ); BlockState destOn = context.get(destX, y - 1, destZ);
IBlockState down = context.get(x, y - 1, z); BlockState down = context.get(x, y - 1, z);
Block srcDown = down.getBlock(); Block srcDown = down.getBlock();
if (MovementHelper.canWalkOn(context.bsi, destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge if (MovementHelper.canWalkOn(context.bsi, destX, y - 1, destZ, destOn)) {//this is a walk, not a bridge
double WC = WALK_ONE_BLOCK_COST; double WC = WALK_ONE_BLOCK_COST;
@@ -142,7 +140,7 @@ public class MovementTraverse extends Movement {
} }
} }
// now that we've checked all possible directions to side place, we actually need to backplace // now that we've checked all possible directions to side place, we actually need to backplace
if (srcDown == Blocks.SOUL_SAND || (srcDown instanceof BlockSlab && down.get(BlockSlab.TYPE) != SlabType.DOUBLE)) { if (srcDown == Blocks.SOUL_SAND || (srcDown instanceof SlabBlock && down.get(SlabBlock.TYPE) != SlabType.DOUBLE)) {
return COST_INF; // can't sneak and backplace against soul sand or half slabs (regardless of whether it's top half or bottom half) =/ return COST_INF; // can't sneak and backplace against soul sand or half slabs (regardless of whether it's top half or bottom half) =/
} }
if (down.getFluidState() instanceof WaterFluid) { if (down.getFluidState() instanceof WaterFluid) {
@@ -158,8 +156,8 @@ public class MovementTraverse extends Movement {
@Override @Override
public MovementState updateState(MovementState state) { public MovementState updateState(MovementState state) {
super.updateState(state); super.updateState(state);
IBlockState pb0 = BlockStateInterface.get(ctx, positionsToBreak[0]); BlockState pb0 = BlockStateInterface.get(ctx, positionsToBreak[0]);
IBlockState pb1 = BlockStateInterface.get(ctx, positionsToBreak[1]); BlockState pb1 = BlockStateInterface.get(ctx, positionsToBreak[1]);
if (state.getStatus() != MovementStatus.RUNNING) { if (state.getStatus() != MovementStatus.RUNNING) {
// if the setting is enabled // if the setting is enabled
if (!Baritone.settings().walkWhileBreaking.value) { if (!Baritone.settings().walkWhileBreaking.value) {
@@ -190,7 +188,7 @@ public class MovementTraverse extends Movement {
// 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(ctx.world(), dest), ctx.playerRotations()).getYaw(); float yawToDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.calculateBlockCenter(ctx.world(), dest), ctx.playerRotations()).getYaw();
float pitchToBreak = state.getTarget().getRotation().get().getPitch(); float pitchToBreak = state.getTarget().getRotation().get().getPitch();
if ((pb0.isFullCube() || pb0.getBlock() instanceof BlockAir && (pb1.isFullCube() || pb1.getBlock() instanceof BlockAir))) { if ((MovementHelper.isBlockNormalCube(pb0) || pb0.getBlock() instanceof AirBlock && (MovementHelper.isBlockNormalCube(pb1) || pb1.getBlock() instanceof AirBlock))) {
// in the meantime, before we're right up against the block, we can break efficiently at this angle // in the meantime, before we're right up against the block, we can break efficiently at this angle
pitchToBreak = 26; pitchToBreak = 26;
} }
@@ -206,9 +204,8 @@ public class MovementTraverse extends Movement {
Block fd = BlockStateInterface.get(ctx, src.down()).getBlock(); Block fd = BlockStateInterface.get(ctx, src.down()).getBlock();
boolean ladder = fd == Blocks.LADDER || fd == Blocks.VINE; boolean ladder = fd == Blocks.LADDER || fd == Blocks.VINE;
if (pb0.getBlock() instanceof BlockDoor || pb1.getBlock() instanceof BlockDoor) { if (pb0.getBlock() instanceof DoorBlock || pb1.getBlock() instanceof DoorBlock) {
boolean notPassable = pb0.getBlock() instanceof DoorBlock && !MovementHelper.isDoorPassable(ctx, src, dest) || pb1.getBlock() instanceof DoorBlock && !MovementHelper.isDoorPassable(ctx, dest, src);
boolean notPassable = pb0.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, src, dest) || pb1.getBlock() instanceof BlockDoor && !MovementHelper.isDoorPassable(ctx, dest, src);
boolean canOpen = !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock())); boolean canOpen = !(Blocks.IRON_DOOR.equals(pb0.getBlock()) || Blocks.IRON_DOOR.equals(pb1.getBlock()));
if (notPassable && canOpen) { if (notPassable && canOpen) {
@@ -217,7 +214,7 @@ public class MovementTraverse extends Movement {
} }
} }
if (pb0.getBlock() instanceof BlockFenceGate || pb1.getBlock() instanceof BlockFenceGate) { if (pb0.getBlock() instanceof FenceGateBlock || pb1.getBlock() instanceof FenceGateBlock) {
BlockPos blocked = !MovementHelper.isGatePassable(ctx, positionsToBreak[0], src.up()) ? positionsToBreak[0] BlockPos blocked = !MovementHelper.isGatePassable(ctx, positionsToBreak[0], src.up()) ? positionsToBreak[0]
: !MovementHelper.isGatePassable(ctx, positionsToBreak[1], src) ? positionsToBreak[1] : !MovementHelper.isGatePassable(ctx, positionsToBreak[1], src) ? positionsToBreak[1]
: null; : null;
@@ -254,16 +251,16 @@ public class MovementTraverse extends Movement {
return state; return state;
} }
BlockPos into = dest.subtract(src).add(dest); BlockPos into = dest.subtract(src).add(dest);
IBlockState intoBelow = BlockStateInterface.get(ctx, into); BlockState intoBelow = BlockStateInterface.get(ctx, into);
IBlockState intoAbove = BlockStateInterface.get(ctx, into.up()); BlockState intoAbove = BlockStateInterface.get(ctx, into.up());
if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, feet) || Baritone.settings().sprintInWater.value) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) { if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, feet) || Baritone.settings().sprintInWater.value) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) {
state.setInput(Input.SPRINT, true); state.setInput(Input.SPRINT, true);
} }
IBlockState destDown = BlockStateInterface.get(ctx, dest.down()); BlockState destDown = BlockStateInterface.get(ctx, dest.down());
BlockPos against = positionsToBreak[0]; BlockPos against = positionsToBreak[0];
if (feet.getY() != dest.getY() && ladder && (destDown.getBlock() == Blocks.VINE || destDown.getBlock() == Blocks.LADDER)) { if (feet.getY() != dest.getY() && ladder && (destDown.getBlock() == Blocks.VINE || destDown.getBlock() == Blocks.LADDER)) {
against = destDown.getBlock() == Blocks.VINE ? MovementPillar.getAgainst(new CalculationContext(baritone), dest.down()) : dest.offset(destDown.get(BlockLadder.FACING).getOpposite()); against = destDown.getBlock() == Blocks.VINE ? MovementPillar.getAgainst(new CalculationContext(baritone), dest.down()) : dest.offset(destDown.get(LadderBlock.FACING).getOpposite());
if (against == null) { if (against == null) {
logDirect("Unable to climb vines. Consider disabling allowVines."); logDirect("Unable to climb vines. Consider disabling allowVines.");
return state.setStatus(MovementStatus.UNREACHABLE); return state.setStatus(MovementStatus.UNREACHABLE);
@@ -274,7 +271,7 @@ public class MovementTraverse extends Movement {
} else { } else {
wasTheBridgeBlockAlwaysThere = false; wasTheBridgeBlockAlwaysThere = false;
Block standingOn = BlockStateInterface.get(ctx, feet.down()).getBlock(); Block standingOn = BlockStateInterface.get(ctx, feet.down()).getBlock();
if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof SlabBlock) { // see issue #118
double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ));
if (dist < 0.85) { // 0.5 + 0.3 + epsilon if (dist < 0.85) { // 0.5 + 0.3 + epsilon
MovementHelper.moveTowards(ctx, state, dest); MovementHelper.moveTowards(ctx, state, dest);
@@ -32,6 +32,7 @@ import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.movements.*; import baritone.pathing.movement.movements.*;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import net.minecraft.block.Blocks;
import net.minecraft.util.Tuple; import net.minecraft.util.Tuple;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
@@ -327,7 +328,7 @@ public class PathExecutor implements IPathExecutor, Helper {
return false; return false;
} else { } else {
// we are either onGround or in liquid // we are either onGround or in liquid
if (ctx.player().motionY < -0.1) { if (ctx.player().getMotion().y < -0.1) {
// if we are strictly moving downwards (not stationary) // if we are strictly moving downwards (not stationary)
// we could be falling through water, which could be unsafe to splice // we could be falling through water, which could be unsafe to splice
return false; // so don't return false; // so don't
@@ -26,8 +26,8 @@ import baritone.pathing.movement.MovementHelper;
import baritone.pathing.movement.MovementState; import baritone.pathing.movement.MovementState;
import baritone.pathing.path.PathExecutor; import baritone.pathing.path.PathExecutor;
import baritone.utils.BaritoneProcessHelper; import baritone.utils.BaritoneProcessHelper;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.BlockState;
import net.minecraft.init.Blocks; import net.minecraft.block.Blocks;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.EmptyChunk; import net.minecraft.world.chunk.EmptyChunk;
@@ -36,7 +36,7 @@ import java.util.stream.Collectors;
public final class BackfillProcess extends BaritoneProcessHelper { public final class BackfillProcess extends BaritoneProcessHelper {
public HashMap<BlockPos, IBlockState> blocksToReplace = new HashMap<>(); public HashMap<BlockPos, BlockState> blocksToReplace = new HashMap<>();
public BackfillProcess(Baritone baritone) { public BackfillProcess(Baritone baritone) {
super(baritone); super(baritone);
@@ -105,7 +105,7 @@ public final class BackfillProcess extends BaritoneProcessHelper {
.filter(pos -> ctx.world().getBlockState(pos).getBlock() == Blocks.AIR) .filter(pos -> ctx.world().getBlockState(pos).getBlock() == Blocks.AIR)
.filter(pos -> baritone.getBuilderProcess().placementPlausible(pos, Blocks.DIRT.getDefaultState())) .filter(pos -> baritone.getBuilderProcess().placementPlausible(pos, Blocks.DIRT.getDefaultState()))
.filter(pos -> !partOfCurrentMovement(pos)) .filter(pos -> !partOfCurrentMovement(pos))
.sorted(Comparator.<BlockPos>comparingDouble(ctx.player()::getDistanceSq).reversed()) .sorted(Comparator.<BlockPos>comparingDouble(ctx.playerFeet()::distanceSq).reversed())
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@@ -39,17 +39,18 @@ import baritone.utils.schematic.MapArtSchematic;
import baritone.utils.schematic.Schematic; import baritone.utils.schematic.Schematic;
import baritone.utils.schematic.schematica.SchematicaHelper; import baritone.utils.schematic.schematica.SchematicaHelper;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import net.minecraft.block.BlockAir; import net.minecraft.block.AirBlock;
import net.minecraft.block.BlockFlowingFluid; import net.minecraft.block.BlockState;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.Blocks;
import net.minecraft.init.Blocks; import net.minecraft.block.FlowingFluidBlock;
import net.minecraft.item.BlockItem;
import net.minecraft.item.BlockItemUseContext; import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUseContext; import net.minecraft.item.ItemUseContext;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Direction;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Hand;
import net.minecraft.util.Tuple; import net.minecraft.util.Tuple;
import net.minecraft.util.math.*; import net.minecraft.util.math.*;
import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.math.shapes.VoxelShape;
@@ -72,7 +73,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
private int ticks; private int ticks;
private boolean paused; private boolean paused;
private int layer; private int layer;
private List<IBlockState> approxPlaceable; private List<BlockState> approxPlaceable;
public BuilderProcess(Baritone baritone) { public BuilderProcess(Baritone baritone) {
super(baritone); super(baritone);
@@ -116,7 +117,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
@Override @Override
public boolean build(String name, File schematic, Vec3i origin) { public boolean build(String name, File schematic, Vec3i origin) {
NBTTagCompound tag; CompoundNBT tag;
try (FileInputStream fileIn = new FileInputStream(schematic)) { try (FileInputStream fileIn = new FileInputStream(schematic)) {
tag = CompressedStreamTools.readCompressed(fileIn); tag = CompressedStreamTools.readCompressed(fileIn);
} catch (IOException e) { } catch (IOException e) {
@@ -154,11 +155,11 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
@Override @Override
public List<IBlockState> getApproxPlaceable() { public List<BlockState> getApproxPlaceable() {
return new ArrayList<>(approxPlaceable); return new ArrayList<>(approxPlaceable);
} }
private static ISchematic parse(NBTTagCompound schematic) { private static ISchematic parse(CompoundNBT schematic) {
return Baritone.settings().mapArtMode.value ? new MapArtSchematic(schematic) : new Schematic(schematic); return Baritone.settings().mapArtMode.value ? new MapArtSchematic(schematic) : new Schematic(schematic);
} }
@@ -167,15 +168,15 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return schematic != null; return schematic != null;
} }
public IBlockState placeAt(int x, int y, int z, IBlockState current) { public BlockState placeAt(int x, int y, int z, BlockState current) {
if (!isActive()) { if (!isActive()) {
return null; return null;
} }
if (!schematic.inSchematic(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current)) { if (!schematic.inSchematic(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current)) {
return null; return null;
} }
IBlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current, this.approxPlaceable); BlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current, this.approxPlaceable);
if (state.getBlock() instanceof BlockAir) { if (state.getBlock() instanceof AirBlock) {
return null; return null;
} }
return state; return state;
@@ -193,12 +194,12 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (dy == -1 && x == pathStart.x && z == pathStart.z) { if (dy == -1 && x == pathStart.x && z == pathStart.z) {
continue; // dont mine what we're supported by, but not directly standing on continue; // dont mine what we're supported by, but not directly standing on
} }
IBlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z)); BlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z));
if (desired == null) { if (desired == null) {
continue; // irrelevant continue; // irrelevant
} }
IBlockState curr = bcc.bsi.get0(x, y, z); BlockState curr = bcc.bsi.get0(x, y, z);
if (!(curr.getBlock() instanceof BlockAir) && !(curr.getBlock() == Blocks.WATER || curr.getBlock() == Blocks.LAVA) && !valid(curr, desired)) { if (!(curr.getBlock() instanceof AirBlock) && !(curr.getBlock() == Blocks.WATER || curr.getBlock() == Blocks.LAVA) && !valid(curr, desired)) {
BetterBlockPos pos = new BetterBlockPos(x, y, z); BetterBlockPos pos = new BetterBlockPos(x, y, z);
Optional<Rotation> rot = RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()); Optional<Rotation> rot = RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance());
if (rot.isPresent()) { if (rot.isPresent()) {
@@ -215,10 +216,10 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
private final int hotbarSelection; private final int hotbarSelection;
private final BlockPos placeAgainst; private final BlockPos placeAgainst;
private final EnumFacing side; private final Direction side;
private final Rotation rot; private final Rotation rot;
public Placement(int hotbarSelection, BlockPos placeAgainst, EnumFacing side, Rotation rot) { public Placement(int hotbarSelection, BlockPos placeAgainst, Direction side, Rotation rot) {
this.hotbarSelection = hotbarSelection; this.hotbarSelection = hotbarSelection;
this.placeAgainst = placeAgainst; this.placeAgainst = placeAgainst;
this.side = side; this.side = side;
@@ -226,7 +227,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
} }
private Optional<Placement> searchForPlaceables(BuilderCalculationContext bcc, List<IBlockState> desirableOnHotbar) { private Optional<Placement> searchForPlacables(BuilderCalculationContext bcc, List<BlockState> desirableOnHotbar) {
BetterBlockPos center = ctx.playerFeet(); BetterBlockPos center = ctx.playerFeet();
for (int dx = -5; dx <= 5; dx++) { for (int dx = -5; dx <= 5; dx++) {
for (int dy = -5; dy <= 1; dy++) { for (int dy = -5; dy <= 1; dy++) {
@@ -234,13 +235,13 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
int x = center.x + dx; int x = center.x + dx;
int y = center.y + dy; int y = center.y + dy;
int z = center.z + dz; int z = center.z + dz;
IBlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z)); BlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z));
if (desired == null) { if (desired == null) {
continue; // irrelevant continue; // irrelevant
} }
IBlockState curr = bcc.bsi.get0(x, y, z); BlockState curr = bcc.bsi.get0(x, y, z);
if (MovementHelper.isReplaceable(x, y, z, curr, bcc.bsi) && !valid(curr, desired)) { if (MovementHelper.isReplaceable(x, y, z, curr, bcc.bsi) && !valid(curr, desired)) {
if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() instanceof BlockAir) { if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() instanceof AirBlock) {
continue; continue;
} }
desirableOnHotbar.add(desired); desirableOnHotbar.add(desired);
@@ -255,15 +256,15 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return Optional.empty(); return Optional.empty();
} }
public boolean placementPlausible(BlockPos pos, IBlockState state) { public boolean placementPlausible(BlockPos pos, BlockState state) {
VoxelShape voxelshape = state.getCollisionShape(ctx.world(), pos); VoxelShape voxelshape = state.getCollisionShape(ctx.world(), pos);
return voxelshape.isEmpty() || ctx.world().checkNoEntityCollision(null, voxelshape.withOffset(pos.getX(), pos.getY(), pos.getZ())); return voxelshape.isEmpty() || ctx.world().checkNoEntityCollision(null, voxelshape.withOffset(pos.getX(), pos.getY(), pos.getZ()));
} }
private Optional<Placement> possibleToPlace(IBlockState toPlace, int x, int y, int z, BlockStateInterface bsi) { private Optional<Placement> possibleToPlace(BlockState toPlace, int x, int y, int z, BlockStateInterface bsi) {
for (EnumFacing against : EnumFacing.values()) { for (Direction against : Direction.values()) {
BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against); BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against);
IBlockState placeAgainstState = bsi.get0(placeAgainstPos); BlockState placeAgainstState = bsi.get0(placeAgainstPos);
if (MovementHelper.isReplaceable(placeAgainstPos.x, placeAgainstPos.y, placeAgainstPos.z, placeAgainstState, bsi)) { if (MovementHelper.isReplaceable(placeAgainstPos.x, placeAgainstPos.y, placeAgainstPos.z, placeAgainstState, bsi)) {
continue; continue;
} }
@@ -280,7 +281,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
double placeZ = placeAgainstPos.z + aabb.minZ * placementMultiplier.z + aabb.maxZ * (1 - placementMultiplier.z); double placeZ = placeAgainstPos.z + aabb.minZ * placementMultiplier.z + aabb.maxZ * (1 - placementMultiplier.z);
Rotation rot = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(placeX, placeY, placeZ), ctx.playerRotations()); Rotation rot = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(placeX, placeY, placeZ), ctx.playerRotations());
RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot, ctx.playerController().getBlockReachDistance()); RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot, ctx.playerController().getBlockReachDistance());
if (result != null && result.type == RayTraceResult.Type.BLOCK && result.getBlockPos().equals(placeAgainstPos) && result.sideHit == against.getOpposite()) { if (result != null && result.getType() == RayTraceResult.Type.BLOCK && ((BlockRayTraceResult) result).getPos().equals(placeAgainstPos) && ((BlockRayTraceResult) result).getFace() == against.getOpposite()) {
OptionalInt hotbar = hasAnyItemThatWouldPlace(toPlace, result, rot); OptionalInt hotbar = hasAnyItemThatWouldPlace(toPlace, result, rot);
if (hotbar.isPresent()) { if (hotbar.isPresent()) {
return Optional.of(new Placement(hotbar.getAsInt(), placeAgainstPos, against.getOpposite(), rot)); return Optional.of(new Placement(hotbar.getAsInt(), placeAgainstPos, against.getOpposite(), rot));
@@ -291,10 +292,10 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return Optional.empty(); return Optional.empty();
} }
private OptionalInt hasAnyItemThatWouldPlace(IBlockState desired, RayTraceResult result, Rotation rot) { private OptionalInt hasAnyItemThatWouldPlace(BlockState desired, RayTraceResult result, Rotation rot) {
for (int i = 0; i < 9; i++) { for (int i = 0; i < 9; i++) {
ItemStack stack = ctx.player().inventory.mainInventory.get(i); ItemStack stack = ctx.player().inventory.mainInventory.get(i);
if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) { if (stack.isEmpty() || !(stack.getItem() instanceof BlockItem)) {
continue; continue;
} }
float originalYaw = ctx.player().rotationYaw; float originalYaw = ctx.player().rotationYaw;
@@ -303,15 +304,13 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
ctx.player().rotationYaw = rot.getYaw(); ctx.player().rotationYaw = rot.getYaw();
ctx.player().rotationPitch = rot.getPitch(); ctx.player().rotationPitch = rot.getPitch();
BlockItemUseContext meme = new BlockItemUseContext(new ItemUseContext( BlockItemUseContext meme = new BlockItemUseContext(new ItemUseContext(
ctx.world(),
ctx.player(), ctx.player(),
Hand.MAIN_HAND,
stack, stack,
result.getBlockPos().offset(result.sideHit), (BlockRayTraceResult) result
result.sideHit, ) {}); // that {} gives us access to a protected constructor lmfao
(float) result.hitVec.x - result.getBlockPos().getX(), BlockState wouldBePlaced = ((BlockItem) stack.getItem()).getBlock().getStateForPlacement(meme);
(float) result.hitVec.y - result.getBlockPos().getY(),
(float) result.hitVec.z - result.getBlockPos().getZ()
));
IBlockState wouldBePlaced = ((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(meme);
ctx.player().rotationYaw = originalYaw; ctx.player().rotationYaw = originalYaw;
ctx.player().rotationPitch = originalPitch; ctx.player().rotationPitch = originalPitch;
if (wouldBePlaced == null) { if (wouldBePlaced == null) {
@@ -327,7 +326,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return OptionalInt.empty(); return OptionalInt.empty();
} }
private static Vec3d[] aabbSideMultipliers(EnumFacing side) { private static Vec3d[] aabbSideMultipliers(Direction side) {
switch (side) { switch (side) {
case UP: case UP:
return new Vec3d[]{new Vec3d(0.5, 1, 0.5), new Vec3d(0.1, 1, 0.5), new Vec3d(0.9, 1, 0.5), new Vec3d(0.5, 1, 0.1), new Vec3d(0.5, 1, 0.9)}; return new Vec3d[]{new Vec3d(0.5, 1, 0.5), new Vec3d(0.1, 1, 0.5), new Vec3d(0.9, 1, 0.5), new Vec3d(0.5, 1, 0.1), new Vec3d(0.5, 1, 0.9)};
@@ -375,12 +374,12 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
schematic = new ISchematic() { schematic = new ISchematic() {
@Override @Override
public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) { public BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) {
return realSchematic.desiredState(x, y, z, current, BuilderProcess.this.approxPlaceable); return realSchematic.desiredState(x, y, z, current, BuilderProcess.this.approxPlaceable);
} }
@Override @Override
public boolean inSchematic(int x, int y, int z, IBlockState currentState) { public boolean inSchematic(int x, int y, int z, BlockState currentState) {
return ISchematic.super.inSchematic(x, y, z, currentState) && y >= minYInclusive && y <= maxYInclusive && realSchematic.inSchematic(x, y, z, currentState); return ISchematic.super.inSchematic(x, y, z, currentState) && y >= minYInclusive && y <= maxYInclusive && realSchematic.inSchematic(x, y, z, currentState);
} }
@@ -442,14 +441,14 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
} }
List<IBlockState> desirableOnHotbar = new ArrayList<>(); List<BlockState> desirableOnHotbar = new ArrayList<>();
Optional<Placement> toPlace = searchForPlaceables(bcc, desirableOnHotbar); Optional<Placement> toPlace = searchForPlacables(bcc, desirableOnHotbar);
if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround && ticks <= 0) { if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround && ticks <= 0) {
Rotation rot = toPlace.get().rot; Rotation rot = toPlace.get().rot;
baritone.getLookBehavior().updateTarget(rot, true); baritone.getLookBehavior().updateTarget(rot, true);
ctx.player().inventory.currentItem = toPlace.get().hotbarSelection; ctx.player().inventory.currentItem = toPlace.get().hotbarSelection;
baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true); baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true);
if ((ctx.isLookingAt(toPlace.get().placeAgainst) && ctx.objectMouseOver().sideHit.equals(toPlace.get().side)) || ctx.playerRotations().isReallyCloseTo(rot)) { if ((ctx.isLookingAt(toPlace.get().placeAgainst) && ((BlockRayTraceResult) ctx.objectMouseOver()).getFace().equals(toPlace.get().side)) || ctx.playerRotations().isReallyCloseTo(rot)) {
baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true);
} }
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL); return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
@@ -457,9 +456,9 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
if (Baritone.settings().allowInventory.value) { if (Baritone.settings().allowInventory.value) {
ArrayList<Integer> usefulSlots = new ArrayList<>(); ArrayList<Integer> usefulSlots = new ArrayList<>();
List<IBlockState> noValidHotbarOption = new ArrayList<>(); List<BlockState> noValidHotbarOption = new ArrayList<>();
outer: outer:
for (IBlockState desired : desirableOnHotbar) { for (BlockState desired : desirableOnHotbar) {
for (int i = 0; i < 9; i++) { for (int i = 0; i < 9; i++) {
if (valid(approxPlaceable.get(i), desired)) { if (valid(approxPlaceable.get(i), desired)) {
usefulSlots.add(i); usefulSlots.add(i);
@@ -471,7 +470,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
outer: outer:
for (int i = 9; i < 36; i++) { for (int i = 9; i < 36; i++) {
for (IBlockState desired : noValidHotbarOption) { for (BlockState desired : noValidHotbarOption) {
if (valid(approxPlaceable.get(i), desired)) { if (valid(approxPlaceable.get(i), desired)) {
baritone.getInventoryBehavior().attemptToPutOnHotbar(i, usefulSlots::contains); baritone.getInventoryBehavior().attemptToPutOnHotbar(i, usefulSlots::contains);
break outer; break outer;
@@ -509,7 +508,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
private void trim() { private void trim() {
HashSet<BetterBlockPos> copy = new HashSet<>(incorrectPositions); HashSet<BetterBlockPos> copy = new HashSet<>(incorrectPositions);
copy.removeIf(pos -> pos.distanceSq(ctx.player().posX, ctx.player().posY, ctx.player().posZ) > 200); copy.removeIf(pos -> pos.distanceSq(new BlockPos(ctx.player())) > 200);
if (!copy.isEmpty()) { if (!copy.isEmpty()) {
incorrectPositions = copy; incorrectPositions = copy;
} }
@@ -524,7 +523,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
int x = center.x + dx; int x = center.x + dx;
int y = center.y + dy; int y = center.y + dy;
int z = center.z + dz; int z = center.z + dz;
IBlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z)); BlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z));
if (desired != null) { if (desired != null) {
// we care about this position // we care about this position
BetterBlockPos pos = new BetterBlockPos(x, y, z); BetterBlockPos pos = new BetterBlockPos(x, y, z);
@@ -549,7 +548,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
int blockX = x + origin.getX(); int blockX = x + origin.getX();
int blockY = y + origin.getY(); int blockY = y + origin.getY();
int blockZ = z + origin.getZ(); int blockZ = z + origin.getZ();
IBlockState current = bcc.bsi.get0(blockX, blockY, blockZ); BlockState current = bcc.bsi.get0(blockX, blockY, blockZ);
if (!schematic.inSchematic(x, y, z, current)) { if (!schematic.inSchematic(x, y, z, current)) {
continue; continue;
} }
@@ -580,18 +579,18 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
} }
private Goal assemble(BuilderCalculationContext bcc, List<IBlockState> approxPlaceable) { private Goal assemble(BuilderCalculationContext bcc, List<BlockState> approxPlaceable) {
List<BetterBlockPos> placeable = new ArrayList<>(); List<BetterBlockPos> placeable = new ArrayList<>();
List<BetterBlockPos> breakable = new ArrayList<>(); List<BetterBlockPos> breakable = new ArrayList<>();
List<BetterBlockPos> sourceLiquids = new ArrayList<>(); List<BetterBlockPos> sourceLiquids = new ArrayList<>();
incorrectPositions.forEach(pos -> { incorrectPositions.forEach(pos -> {
IBlockState state = bcc.bsi.get0(pos); BlockState state = bcc.bsi.get0(pos);
if (state.getBlock() instanceof BlockAir) { if (state.getBlock() instanceof AirBlock) {
if (approxPlaceable.contains(bcc.getSchematic(pos.x, pos.y, pos.z, state))) { if (approxPlaceable.contains(bcc.getSchematic(pos.x, pos.y, pos.z, state))) {
placeable.add(pos); placeable.add(pos);
} }
} else { } else {
if (state.getBlock() instanceof BlockFlowingFluid) { if (state.getBlock() instanceof FlowingFluidBlock) {
// if the block itself is JUST a liquid (i.e. not just a waterlogged block), we CANNOT break it // if the block itself is JUST a liquid (i.e. not just a waterlogged block), we CANNOT break it
// TODO for 1.13 make sure that this only matches pure water, not waterlogged blocks // TODO for 1.13 make sure that this only matches pure water, not waterlogged blocks
if (!MovementHelper.possiblyFlowing(state)) { if (!MovementHelper.possiblyFlowing(state)) {
@@ -667,12 +666,12 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
private Goal placementGoal(BlockPos pos, BuilderCalculationContext bcc) { private Goal placementGoal(BlockPos pos, BuilderCalculationContext bcc) {
if (!(ctx.world().getBlockState(pos).getBlock() instanceof BlockAir)) { // TODO can this even happen? if (!(ctx.world().getBlockState(pos).getBlock() instanceof AirBlock)) { // TODO can this even happen?
return new GoalPlace(pos); return new GoalPlace(pos);
} }
boolean allowSameLevel = !(ctx.world().getBlockState(pos.up()).getBlock() instanceof BlockAir); boolean allowSameLevel = !(ctx.world().getBlockState(pos.up()).getBlock() instanceof AirBlock);
IBlockState current = ctx.world().getBlockState(pos); BlockState current = ctx.world().getBlockState(pos);
for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP) { for (Direction facing : Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP) {
//noinspection ConstantConditions //noinspection ConstantConditions
if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && placementPlausible(pos, bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ(), current))) { if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && placementPlausible(pos, bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ(), current))) {
return new GoalAdjacent(pos, pos.offset(facing), allowSameLevel); return new GoalAdjacent(pos, pos.offset(facing), allowSameLevel);
@@ -682,7 +681,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
private Goal breakGoal(BlockPos pos, BuilderCalculationContext bcc) { private Goal breakGoal(BlockPos pos, BuilderCalculationContext bcc) {
if (Baritone.settings().goalBreakFromAbove.value && bcc.bsi.get0(pos.up()).getBlock() instanceof BlockAir && bcc.bsi.get0(pos.up(2)).getBlock() instanceof BlockAir) { // TODO maybe possible without the up(2) check? if (Baritone.settings().goalBreakFromAbove.value && bcc.bsi.get0(pos.up()).getBlock() instanceof AirBlock && bcc.bsi.get0(pos.up(2)).getBlock() instanceof AirBlock) { // TODO maybe possible without the up(2) check?
return new JankyGoalComposite(new GoalBreak(pos), new GoalGetToBlock(pos.up()) { return new JankyGoalComposite(new GoalBreak(pos), new GoalGetToBlock(pos.up()) {
@Override @Override
public boolean isInGoal(int x, int y, int z) { public boolean isInGoal(int x, int y, int z) {
@@ -757,26 +756,26 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
return paused ? "Builder Paused" : "Building " + name; return paused ? "Builder Paused" : "Building " + name;
} }
private List<IBlockState> approxPlaceable(int size) { private List<BlockState> approxPlaceable(int size) {
List<IBlockState> result = new ArrayList<>(); List<BlockState> result = new ArrayList<>();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
ItemStack stack = ctx.player().inventory.mainInventory.get(i); ItemStack stack = ctx.player().inventory.mainInventory.get(i);
if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) { if (stack.isEmpty() || !(stack.getItem() instanceof BlockItem)) {
result.add(Blocks.AIR.getDefaultState()); result.add(Blocks.AIR.getDefaultState());
continue; continue;
} }
// <toxic cloud> // <toxic cloud>
result.add(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(new BlockItemUseContext(new ItemUseContext(ctx.player(), stack, ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ)))); result.add(((BlockItem) stack.getItem()).getBlock().getStateForPlacement(new BlockItemUseContext(new ItemUseContext(ctx.world(), ctx.player(), Hand.MAIN_HAND, stack, new BlockRayTraceResult(new Vec3d(ctx.player().posX, ctx.player().posY, ctx.player().posZ), Direction.UP, ctx.playerFeet(), false)) {})));
// </toxic cloud> // </toxic cloud>
} }
return result; return result;
} }
private boolean valid(IBlockState current, IBlockState desired) { private boolean valid(BlockState current, BlockState desired) {
if (desired == null) { if (desired == null) {
return true; return true;
} }
if (current.getBlock() instanceof BlockAir && desired.getBlock() instanceof BlockAir) { if (current.getBlock() instanceof AirBlock && desired.getBlock() instanceof AirBlock) {
return true; return true;
} }
if ((current.getBlock() == Blocks.WATER || current.getBlock() == Blocks.LAVA) && Baritone.settings().okIfWater.value) { if ((current.getBlock() == Blocks.WATER || current.getBlock() == Blocks.LAVA) && Baritone.settings().okIfWater.value) {
@@ -788,7 +787,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
public class BuilderCalculationContext extends CalculationContext { public class BuilderCalculationContext extends CalculationContext {
private final List<IBlockState> placeable; private final List<BlockState> placeable;
private final ISchematic schematic; private final ISchematic schematic;
private final int originX; private final int originX;
private final int originY; private final int originY;
@@ -806,7 +805,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
this.backtrackCostFavoringCoefficient = 1; this.backtrackCostFavoringCoefficient = 1;
} }
private IBlockState getSchematic(int x, int y, int z, IBlockState current) { private BlockState getSchematic(int x, int y, int z, BlockState current) {
if (schematic.inSchematic(x - originX, y - originY, z - originZ, current)) { if (schematic.inSchematic(x - originX, y - originY, z - originZ, current)) {
return schematic.desiredState(x - originX, y - originY, z - originZ, current, BuilderProcess.this.approxPlaceable); return schematic.desiredState(x - originX, y - originY, z - originZ, current, BuilderProcess.this.approxPlaceable);
} else { } else {
@@ -815,14 +814,14 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
@Override @Override
public double costOfPlacingAt(int x, int y, int z, IBlockState current) { public double costOfPlacingAt(int x, int y, int z, BlockState current) {
if (isPossiblyProtected(x, y, z) || !worldBorder.canPlaceAt(x, z)) { // make calculation fail properly if we can't build if (isPossiblyProtected(x, y, z) || !worldBorder.canPlaceAt(x, z)) { // make calculation fail properly if we can't build
return COST_INF; return COST_INF;
} }
IBlockState sch = getSchematic(x, y, z, current); BlockState sch = getSchematic(x, y, z, current);
if (sch != null) { if (sch != null) {
// TODO this can return true even when allowPlace is off.... is that an issue? // TODO this can return true even when allowPlace is off.... is that an issue?
if (sch.getBlock() instanceof BlockAir) { if (sch.getBlock() instanceof AirBlock) {
// we want this to be air, but they're asking if they can place here // we want this to be air, but they're asking if they can place here
// this won't be a schematic block, this will be a throwaway // this won't be a schematic block, this will be a throwaway
return placeBlockCost * 2; // we're going to have to break it eventually return placeBlockCost * 2; // we're going to have to break it eventually
@@ -849,13 +848,13 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
} }
@Override @Override
public double breakCostMultiplierAt(int x, int y, int z, IBlockState current) { public double breakCostMultiplierAt(int x, int y, int z, BlockState current) {
if (!allowBreak || isPossiblyProtected(x, y, z)) { if (!allowBreak || isPossiblyProtected(x, y, z)) {
return COST_INF; return COST_INF;
} }
IBlockState sch = getSchematic(x, y, z, current); BlockState sch = getSchematic(x, y, z, current);
if (sch != null) { if (sch != null) {
if (sch.getBlock() instanceof BlockAir) { if (sch.getBlock() instanceof AirBlock) {
// it should be air // it should be air
// regardless of current contents, we can break it // regardless of current contents, we can break it
return 1; return 1;
+24 -25
View File
@@ -32,15 +32,14 @@ import baritone.cache.WorldScanner;
import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementHelper;
import baritone.utils.BaritoneProcessHelper; import baritone.utils.BaritoneProcessHelper;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.ItemEntity;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing; import net.minecraft.item.Items;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
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 net.minecraft.world.World; import net.minecraft.world.World;
@@ -100,50 +99,50 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
} }
private enum Harvest { private enum Harvest {
WHEAT((BlockCrops) Blocks.WHEAT), WHEAT((CropsBlock) Blocks.WHEAT),
CARROTS((BlockCrops) Blocks.CARROTS), CARROTS((CropsBlock) Blocks.CARROTS),
POTATOES((BlockCrops) Blocks.POTATOES), POTATOES((CropsBlock) Blocks.POTATOES),
BEETROOT((BlockCrops) Blocks.BEETROOTS), BEETROOT((CropsBlock) Blocks.BEETROOTS),
PUMPKIN(Blocks.PUMPKIN, state -> true), PUMPKIN(Blocks.PUMPKIN, state -> true),
MELON(Blocks.MELON, state -> true), MELON(Blocks.MELON, state -> true),
NETHERWART(Blocks.NETHER_WART, state -> state.get(BlockNetherWart.AGE) >= 3), NETHERWART(Blocks.NETHER_WART, state -> state.get(NetherWartBlock.AGE) >= 3),
SUGARCANE(Blocks.SUGAR_CANE, null) { SUGARCANE(Blocks.SUGAR_CANE, null) {
@Override @Override
public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { public boolean readyToHarvest(World world, BlockPos pos, BlockState state) {
if (Baritone.settings().replantCrops.value) { if (Baritone.settings().replantCrops.value) {
return world.getBlockState(pos.down()).getBlock() instanceof BlockReed; return world.getBlockState(pos.down()).getBlock() instanceof SugarCaneBlock;
} }
return true; return true;
} }
}, },
CACTUS(Blocks.CACTUS, null) { CACTUS(Blocks.CACTUS, null) {
@Override @Override
public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { public boolean readyToHarvest(World world, BlockPos pos, BlockState state) {
if (Baritone.settings().replantCrops.value) { if (Baritone.settings().replantCrops.value) {
return world.getBlockState(pos.down()).getBlock() instanceof BlockCactus; return world.getBlockState(pos.down()).getBlock() instanceof CactusBlock;
} }
return true; return true;
} }
}; };
public final Block block; public final Block block;
public final Predicate<IBlockState> readyToHarvest; public final Predicate<BlockState> readyToHarvest;
Harvest(BlockCrops blockCrops) { Harvest(CropsBlock blockCrops) {
this(blockCrops, blockCrops::isMaxAge); this(blockCrops, blockCrops::isMaxAge);
// max age is 7 for wheat, carrots, and potatoes, but 3 for beetroot // max age is 7 for wheat, carrots, and potatoes, but 3 for beetroot
} }
Harvest(Block block, Predicate<IBlockState> readyToHarvest) { Harvest(Block block, Predicate<BlockState> readyToHarvest) {
this.block = block; this.block = block;
this.readyToHarvest = readyToHarvest; this.readyToHarvest = readyToHarvest;
} }
public boolean readyToHarvest(World world, BlockPos pos, IBlockState state) { public boolean readyToHarvest(World world, BlockPos pos, BlockState state) {
return readyToHarvest.test(state); return readyToHarvest.test(state);
} }
} }
private boolean readyForHarvest(World world, BlockPos pos, IBlockState state) { private boolean readyForHarvest(World world, BlockPos pos, BlockState state) {
for (Harvest harvest : Harvest.values()) { for (Harvest harvest : Harvest.values()) {
if (harvest.block == state.getBlock()) { if (harvest.block == state.getBlock()) {
return harvest.readyToHarvest(world, pos, state); return harvest.readyToHarvest(world, pos, state);
@@ -188,8 +187,8 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
List<BlockPos> bonemealable = new ArrayList<>(); List<BlockPos> bonemealable = new ArrayList<>();
List<BlockPos> openSoulsand = new ArrayList<>(); List<BlockPos> openSoulsand = new ArrayList<>();
for (BlockPos pos : locations) { for (BlockPos pos : locations) {
IBlockState state = ctx.world().getBlockState(pos); BlockState state = ctx.world().getBlockState(pos);
boolean airAbove = ctx.world().getBlockState(pos.up()).getBlock() instanceof BlockAir; boolean airAbove = ctx.world().getBlockState(pos.up()).getBlock() instanceof AirBlock;
if (state.getBlock() == Blocks.FARMLAND) { if (state.getBlock() == Blocks.FARMLAND) {
if (airAbove) { if (airAbove) {
openFarmland.add(pos); openFarmland.add(pos);
@@ -233,7 +232,7 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
Optional<Rotation> rot = RotationUtils.reachableOffset(ctx.player(), pos, new Vec3d(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), ctx.playerController().getBlockReachDistance()); Optional<Rotation> rot = RotationUtils.reachableOffset(ctx.player(), pos, new Vec3d(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5), ctx.playerController().getBlockReachDistance());
if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, soulsand ? this::isNetherWart : this::isPlantable)) { if (rot.isPresent() && isSafeToCancel && baritone.getInventoryBehavior().throwaway(true, soulsand ? this::isNetherWart : this::isPlantable)) {
RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance()); RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot.get(), ctx.playerController().getBlockReachDistance());
if (result.type == RayTraceResult.Type.BLOCK && result.sideHit == EnumFacing.UP) { if (result instanceof BlockRayTraceResult && ((BlockRayTraceResult) result).getFace() == Direction.UP) {
baritone.getLookBehavior().updateTarget(rot.get(), true); baritone.getLookBehavior().updateTarget(rot.get(), true);
if (ctx.isLookingAt(pos)) { if (ctx.isLookingAt(pos)) {
baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true);
@@ -278,9 +277,9 @@ public final class FarmProcess extends BaritoneProcessHelper implements IFarmPro
goalz.add(new GoalBlock(pos)); goalz.add(new GoalBlock(pos));
} }
} }
for (Entity entity : ctx.world().loadedEntityList) { for (Entity entity : ctx.entities()) {
if (entity instanceof EntityItem && entity.onGround) { if (entity instanceof ItemEntity && entity.onGround) {
EntityItem ei = (EntityItem) entity; ItemEntity ei = (ItemEntity) entity;
if (PICKUP_DROPPED.contains(ei.getItem().getItem())) { if (PICKUP_DROPPED.contains(ei.getItem().getItem())) {
// +0.1 because of farmland's 0.9375 dummy height lol // +0.1 because of farmland's 0.9375 dummy height lol
goalz.add(new GoalBlock(new BlockPos(entity.posX, entity.posY + 0.1, entity.posZ))); goalz.add(new GoalBlock(new BlockPos(entity.posX, entity.posY + 0.1, entity.posZ)));
@@ -32,7 +32,6 @@ import net.minecraft.util.math.BlockPos;
import java.util.List; import java.util.List;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
/** /**
* Follow an entity * Follow an entity
@@ -77,12 +76,11 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo
if (entity.equals(ctx.player())) { if (entity.equals(ctx.player())) {
return false; return false;
} }
return ctx.world().loadedEntityList.contains(entity); return ctx.entitiesStream().anyMatch(entity::equals);
} }
private void scanWorld() { private void scanWorld() {
cache = Stream.of(ctx.world().loadedEntityList, ctx.world().playerEntities) cache = ctx.entitiesStream()
.flatMap(List::stream)
.filter(this::followable) .filter(this::followable)
.filter(this.filter) .filter(this.filter)
.distinct() .distinct()
@@ -28,10 +28,11 @@ import baritone.api.utils.Rotation;
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;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.BaritoneProcessHelper; import baritone.utils.BaritoneProcessHelper;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.init.Blocks; import net.minecraft.block.Blocks;
import net.minecraft.inventory.ContainerPlayer; import net.minecraft.inventory.container.PlayerContainer;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import java.util.*; import java.util.*;
@@ -123,7 +124,7 @@ public final class GetToBlockProcess extends BaritoneProcessHelper implements IG
// blacklist the closest block and its adjacent blocks // blacklist the closest block and its adjacent blocks
public synchronized boolean blacklistClosest() { public synchronized boolean blacklistClosest() {
List<BlockPos> newBlacklist = new ArrayList<>(); List<BlockPos> newBlacklist = new ArrayList<>();
knownLocations.stream().min(Comparator.comparingDouble(ctx.player()::getDistanceSq)).ifPresent(newBlacklist::add); knownLocations.stream().min(Comparator.comparingDouble(ctx.playerFeet()::distanceSq)).ifPresent(newBlacklist::add);
outer: outer:
while (true) { while (true) {
for (BlockPos known : knownLocations) { for (BlockPos known : knownLocations) {
@@ -182,7 +183,7 @@ public final class GetToBlockProcess extends BaritoneProcessHelper implements IG
if (walkIntoInsteadOfAdjacent(gettingTo.getBlock())) { if (walkIntoInsteadOfAdjacent(gettingTo.getBlock())) {
return new GoalTwoBlocks(pos); return new GoalTwoBlocks(pos);
} }
if (blockOnTopMustBeRemoved(gettingTo.getBlock()) && baritone.bsi.get0(pos.up()).isBlockNormalCube()) { if (blockOnTopMustBeRemoved(gettingTo.getBlock()) && MovementHelper.isBlockNormalCube(baritone.bsi.get0(pos.up()))) { // TODO this should be the check for chest openability
return new GoalBlock(pos.up()); return new GoalBlock(pos.up());
} }
return new GoalGetToBlock(pos); return new GoalGetToBlock(pos);
@@ -196,7 +197,7 @@ public final class GetToBlockProcess extends BaritoneProcessHelper implements IG
if (knownLocations.contains(ctx.getSelectedBlock().orElse(null))) { if (knownLocations.contains(ctx.getSelectedBlock().orElse(null))) {
baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); // TODO find some way to right click even if we're in an ESC menu baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); // TODO find some way to right click even if we're in an ESC menu
System.out.println(ctx.player().openContainer); System.out.println(ctx.player().openContainer);
if (!(ctx.player().openContainer instanceof ContainerPlayer)) { if (!(ctx.player().openContainer instanceof PlayerContainer)) {
return true; return true;
} }
} }
+15 -17
View File
@@ -30,13 +30,10 @@ import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementHelper;
import baritone.utils.BaritoneProcessHelper; import baritone.utils.BaritoneProcessHelper;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import net.minecraft.block.Block; import net.minecraft.block.*;
import net.minecraft.block.BlockAir; import net.minecraft.client.world.ClientWorld;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.ItemEntity;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@@ -88,7 +85,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
if (calcFailed) { if (calcFailed) {
if (!knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) { if (!knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) {
logDirect("Unable to find any path to " + filter + ", blacklisting presumably unreachable closest instance..."); logDirect("Unable to find any path to " + filter + ", blacklisting presumably unreachable closest instance...");
knownOreLocations.stream().min(Comparator.comparingDouble(ctx.player()::getDistanceSq)).ifPresent(blacklist::add); knownOreLocations.stream().min(Comparator.comparingDouble(ctx.playerFeet()::distanceSq)).ifPresent(blacklist::add);
knownOreLocations.removeIf(blacklist::contains); knownOreLocations.removeIf(blacklist::contains);
} else { } else {
logDirect("Unable to find any path to " + filter + ", canceling mine"); logDirect("Unable to find any path to " + filter + ", canceling mine");
@@ -114,12 +111,12 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
Optional<BlockPos> shaft = curr.stream() Optional<BlockPos> shaft = curr.stream()
.filter(pos -> pos.getX() == ctx.playerFeet().getX() && pos.getZ() == ctx.playerFeet().getZ()) .filter(pos -> pos.getX() == ctx.playerFeet().getX() && pos.getZ() == ctx.playerFeet().getZ())
.filter(pos -> pos.getY() >= ctx.playerFeet().getY()) .filter(pos -> pos.getY() >= ctx.playerFeet().getY())
.filter(pos -> !(BlockStateInterface.get(ctx, pos).getBlock() instanceof BlockAir)) // after breaking a block, it takes mineGoalUpdateInterval ticks for it to actually update this list =( .filter(pos -> !(BlockStateInterface.get(ctx, pos).getBlock() instanceof AirBlock)) // after breaking a block, it takes mineGoalUpdateInterval ticks for it to actually update this list =(
.min(Comparator.comparingDouble(ctx.player()::getDistanceSq)); .min(Comparator.comparingDouble(ctx.playerFeet()::distanceSq));
baritone.getInputOverrideHandler().clearAllKeys(); baritone.getInputOverrideHandler().clearAllKeys();
if (shaft.isPresent() && ctx.player().onGround) { if (shaft.isPresent() && ctx.player().onGround) {
BlockPos pos = shaft.get(); BlockPos pos = shaft.get();
IBlockState state = baritone.bsi.get0(pos); BlockState state = baritone.bsi.get0(pos);
if (!MovementHelper.avoidBreaking(baritone.bsi, pos.getX(), pos.getY(), pos.getZ(), state)) { if (!MovementHelper.avoidBreaking(baritone.bsi, pos.getX(), pos.getY(), pos.getZ(), state)) {
Optional<Rotation> rot = RotationUtils.reachable(ctx, pos); Optional<Rotation> rot = RotationUtils.reachable(ctx, pos);
if (rot.isPresent() && isSafeToCancel) { if (rot.isPresent() && isSafeToCancel) {
@@ -142,6 +139,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
return command; return command;
} }
private void updateLoucaSystem() { private void updateLoucaSystem() {
Map<BlockPos, Long> copy = new HashMap<>(anticipatedDrops); Map<BlockPos, Long> copy = new HashMap<>(anticipatedDrops);
ctx.getSelectedBlock().ifPresent(pos -> { ctx.getSelectedBlock().ifPresent(pos -> {
@@ -232,15 +230,15 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
if (locs.contains(pos)) { if (locs.contains(pos)) {
return true; return true;
} }
IBlockState state = context.bsi.get0(pos); BlockState state = context.bsi.get0(pos);
if (Baritone.settings().internalMiningAirException.value && state.getBlock() instanceof BlockAir) { if (Baritone.settings().internalMiningAirException.value && state.getBlock() instanceof AirBlock) {
return true; return true;
} }
return filter.has(state) && plausibleToBreak(context, pos); return filter.has(state) && plausibleToBreak(context, pos);
} }
private Goal coalesce(BlockPos loc, List<BlockPos> locs, CalculationContext context) { private Goal coalesce(BlockPos loc, List<BlockPos> locs, CalculationContext context) {
boolean assumeVerticalShaftMine = !(baritone.bsi.get0(loc.up()).getBlock() instanceof BlockFalling); boolean assumeVerticalShaftMine = !(baritone.bsi.get0(loc.up()).getBlock() instanceof FallingBlock);
if (!Baritone.settings().forceInternalMining.value) { if (!Baritone.settings().forceInternalMining.value) {
if (assumeVerticalShaftMine) { if (assumeVerticalShaftMine) {
// we can get directly below the block // we can get directly below the block
@@ -306,9 +304,9 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
return Collections.emptyList(); return Collections.emptyList();
} }
List<BlockPos> ret = new ArrayList<>(); List<BlockPos> ret = new ArrayList<>();
for (Entity entity : ctx.world().loadedEntityList) { for (Entity entity : ((ClientWorld) ctx.world()).getAllEntities()) {
if (entity instanceof EntityItem) { if (entity instanceof ItemEntity) {
EntityItem ei = (EntityItem) entity; ItemEntity ei = (ItemEntity) entity;
if (filter.has(ei.getItem())) { if (filter.has(ei.getItem())) {
ret.add(new BlockPos(entity)); ret.add(new BlockPos(entity));
} }
@@ -401,7 +399,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
.filter(pos -> !blacklist.contains(pos)) .filter(pos -> !blacklist.contains(pos))
.sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().player()::getDistanceSq)) .sorted(Comparator.comparingDouble(new BlockPos(ctx.getBaritone().getPlayerContext().player())::distanceSq))
.collect(Collectors.toList()); .collect(Collectors.toList());
if (locs.size() > max) { if (locs.size() > max) {
@@ -2,7 +2,7 @@ package baritone.selection;
import baritone.api.selection.ISelection; import baritone.api.selection.ISelection;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
@@ -83,14 +83,14 @@ public class Selection implements ISelection {
/** /**
* Since it might not be immediately obvious what this does, let me explain. * Since it might not be immediately obvious what this does, let me explain.
* <p> * <p>
* Let's say you specify EnumFacing.UP, this functions returns if pos2 is the highest BlockPos. * Let's say you specify Direction.UP, this functions returns if pos2 is the highest BlockPos.
* If you specify EnumFacing.DOWN, it returns if pos2 is the lowest BlockPos. * If you specify Direction.DOWN, it returns if pos2 is the lowest BlockPos.
* *
* @param facing The direction to check. * @param facing The direction to check.
* @return {@code true} if pos2 is further in that direction than pos1, {@code false} if it isn't, and something * @return {@code true} if pos2 is further in that direction than pos1, {@code false} if it isn't, and something
* else if they're both at the same position on that axis (it really doesn't matter) * else if they're both at the same position on that axis (it really doesn't matter)
*/ */
private boolean isPos2(EnumFacing facing) { private boolean isPos2(Direction facing) {
boolean negative = facing.getAxisDirection().getOffset() < 0; boolean negative = facing.getAxisDirection().getOffset() < 0;
switch (facing.getAxis()) { switch (facing.getAxis()) {
@@ -101,12 +101,12 @@ public class Selection implements ISelection {
case Z: case Z:
return (pos2.z > pos1.z) ^ negative; return (pos2.z > pos1.z) ^ negative;
default: default:
throw new IllegalStateException("Bad EnumFacing.Axis"); throw new IllegalStateException("Bad Direction.Axis");
} }
} }
@Override @Override
public ISelection expand(EnumFacing direction, int blocks) { public ISelection expand(Direction direction, int blocks) {
if (isPos2(direction)) { if (isPos2(direction)) {
return new Selection(pos1, pos2.offset(direction, blocks)); return new Selection(pos1, pos2.offset(direction, blocks));
} else { } else {
@@ -115,7 +115,7 @@ public class Selection implements ISelection {
} }
@Override @Override
public ISelection contract(EnumFacing direction, int blocks) { public ISelection contract(Direction direction, int blocks) {
if (isPos2(direction)) { if (isPos2(direction)) {
return new Selection(pos1.offset(direction, blocks), pos2); return new Selection(pos1.offset(direction, blocks), pos2);
} else { } else {
@@ -124,7 +124,7 @@ public class Selection implements ISelection {
} }
@Override @Override
public ISelection shift(EnumFacing direction, int blocks) { public ISelection shift(Direction direction, int blocks) {
return new Selection(pos1.offset(direction, blocks), pos2.offset(direction, blocks)); return new Selection(pos1.offset(direction, blocks), pos2.offset(direction, blocks));
} }
} }
@@ -4,7 +4,7 @@ import baritone.Baritone;
import baritone.api.selection.ISelection; import baritone.api.selection.ISelection;
import baritone.api.selection.ISelectionManager; import baritone.api.selection.ISelectionManager;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import net.minecraft.util.EnumFacing; import net.minecraft.util.Direction;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.ListIterator; import java.util.ListIterator;
@@ -69,7 +69,7 @@ public class SelectionManager implements ISelectionManager {
} }
@Override @Override
public synchronized ISelection expand(ISelection selection, EnumFacing direction, int blocks) { public synchronized ISelection expand(ISelection selection, Direction direction, int blocks) {
for (ListIterator<ISelection> it = selections.listIterator(); it.hasNext(); ) { for (ListIterator<ISelection> it = selections.listIterator(); it.hasNext(); ) {
ISelection current = it.next(); ISelection current = it.next();
@@ -85,7 +85,7 @@ public class SelectionManager implements ISelectionManager {
} }
@Override @Override
public synchronized ISelection contract(ISelection selection, EnumFacing direction, int blocks) { public synchronized ISelection contract(ISelection selection, Direction direction, int blocks) {
for (ListIterator<ISelection> it = selections.listIterator(); it.hasNext(); ) { for (ListIterator<ISelection> it = selections.listIterator(); it.hasNext(); ) {
ISelection current = it.next(); ISelection current = it.next();
@@ -101,7 +101,7 @@ public class SelectionManager implements ISelectionManager {
} }
@Override @Override
public synchronized ISelection shift(ISelection selection, EnumFacing direction, int blocks) { public synchronized ISelection shift(ISelection selection, Direction direction, int blocks) {
for (ListIterator<ISelection> it = selections.listIterator(); it.hasNext(); ) { for (ListIterator<ISelection> it = selections.listIterator(); it.hasNext(); ) {
ISelection current = it.next(); ISelection current = it.next();
@@ -26,10 +26,13 @@ import baritone.api.utils.Helper;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import net.minecraft.client.GameSettings; import net.minecraft.client.GameSettings;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.screen.MainMenuScreen;
import net.minecraft.client.settings.AmbientOcclusionStatus;
import net.minecraft.client.settings.CloudOption;
import net.minecraft.client.settings.ParticleStatus;
import net.minecraft.client.tutorial.TutorialSteps; import net.minecraft.client.tutorial.TutorialSteps;
import net.minecraft.server.integrated.IntegratedServer; import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.util.HttpUtil; import net.minecraft.util.HTTPUtil;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.GameType; import net.minecraft.world.GameType;
import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldSettings;
@@ -69,27 +72,27 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
System.out.println("Optimizing Game Settings"); System.out.println("Optimizing Game Settings");
GameSettings s = mc.gameSettings; GameSettings s = mc.gameSettings;
s.limitFramerate = 20; s.framerateLimit = 20;
s.mipmapLevels = 0; s.mipmapLevels = 0;
s.particleSetting = 2; s.particles = ParticleStatus.MINIMAL;
s.overrideWidth = 128; s.overrideWidth = 128;
s.overrideHeight = 128; s.overrideHeight = 128;
s.heldItemTooltips = false; s.heldItemTooltips = false;
s.entityShadows = false; s.entityShadows = false;
s.chatScale = 0.0F; s.chatScale = 0.0F;
s.ambientOcclusion = 0; s.ambientOcclusionStatus = AmbientOcclusionStatus.OFF;
s.clouds = 0; s.cloudOption = CloudOption.OFF;
s.fancyGraphics = false; s.fancyGraphics = false;
s.tutorialStep = TutorialSteps.NONE; s.tutorialStep = TutorialSteps.NONE;
s.hideGUI = true; s.hideGUI = true;
s.fovSetting = 30.0F; s.fov = 30.0F;
} }
@Override @Override
public void onTick(TickEvent event) { public void onTick(TickEvent event) {
IPlayerContext ctx = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext(); IPlayerContext ctx = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext();
// If we're on the main menu then create the test world and launch the integrated server // If 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 MainMenuScreen) {
System.out.println("Beginning Baritone automatic test routine"); System.out.println("Beginning Baritone automatic test routine");
mc.displayGuiScreen(null); mc.displayGuiScreen(null);
WorldSettings worldsettings = new WorldSettings(TEST_SEED, GameType.getByName("survival"), true, false, WorldType.DEFAULT); WorldSettings worldsettings = new WorldSettings(TEST_SEED, GameType.getByName("survival"), true, false, WorldType.DEFAULT);
@@ -101,8 +104,16 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
// If the integrated server is launched and the world has initialized, set the spawn point // If the integrated server is launched and the world has initialized, set the spawn point
// to our defined starting position // to our defined starting position
if (server != null && server.getWorld(DimensionType.OVERWORLD) != null) { if (server != null && server.getWorld(DimensionType.OVERWORLD) != null) {
server.getWorld(DimensionType.OVERWORLD).setSpawnPoint(STARTING_POSITION); if (mc.player == null) {
server.getWorld(DimensionType.OVERWORLD).getGameRules().setOrCreateGameRule("spawnRadius", "0", server); server.execute(() -> {
server.getWorld(DimensionType.OVERWORLD).setSpawnPoint(STARTING_POSITION);
server.getCommandManager().handleCommand(server.getCommandSource(), "/difficulty peaceful");
int result = server.getCommandManager().handleCommand(server.getCommandSource(), "/gamerule spawnRadius 0");
if (result != 0) {
throw new IllegalStateException(result + "");
}
});
}
} }
if (event.getType() == TickEvent.Type.IN) { // If we're in-game if (event.getType() == TickEvent.Type.IN) { // If we're in-game
@@ -110,7 +121,7 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
// Force the integrated server to share the world to LAN so that // Force the integrated server to share the world to LAN so that
// the ingame pause menu gui doesn't actually pause our game // the ingame pause menu gui doesn't actually pause our game
if (mc.isSingleplayer() && !mc.getIntegratedServer().getPublic()) { if (mc.isSingleplayer() && !mc.getIntegratedServer().getPublic()) {
mc.getIntegratedServer().shareToLAN(GameType.getByName("survival"), false, HttpUtil.getSuitableLanPort()); mc.getIntegratedServer().shareToLAN(GameType.getByName("survival"), false, HTTPUtil.getSuitableLanPort());
} }
// For the first 200 ticks, wait for the world to generate // For the first 200 ticks, wait for the world to generate
@@ -19,7 +19,8 @@ package baritone.utils;
import baritone.api.utils.Helper; import baritone.api.utils.Helper;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import net.minecraft.util.EnumHand; import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.RayTraceResult;
/** /**
@@ -49,18 +50,18 @@ public final class BlockBreakHelper implements Helper {
public void tick(boolean isLeftClick) { public void tick(boolean isLeftClick) {
RayTraceResult trace = ctx.objectMouseOver(); RayTraceResult trace = ctx.objectMouseOver();
boolean isBlockTrace = trace != null && trace.type == RayTraceResult.Type.BLOCK; boolean isBlockTrace = trace != null && trace.getType() == RayTraceResult.Type.BLOCK;
if (isLeftClick && isBlockTrace) { if (isLeftClick && isBlockTrace) {
if (!didBreakLastTick) { if (!didBreakLastTick) {
ctx.playerController().syncHeldItem(); ctx.playerController().syncHeldItem();
ctx.playerController().clickBlock(trace.getBlockPos(), trace.sideHit); ctx.playerController().clickBlock(((BlockRayTraceResult) trace).getPos(), ((BlockRayTraceResult) trace).getFace());
ctx.player().swingArm(EnumHand.MAIN_HAND); ctx.player().swingArm(Hand.MAIN_HAND);
} }
// Attempt to break the block // Attempt to break the block
if (ctx.playerController().onPlayerDamageBlock(trace.getBlockPos(), trace.sideHit)) { if (ctx.playerController().onPlayerDamageBlock(((BlockRayTraceResult) trace).getPos(), ((BlockRayTraceResult) trace).getFace())) {
ctx.player().swingArm(EnumHand.MAIN_HAND); ctx.player().swingArm(Hand.MAIN_HAND);
} }
ctx.playerController().setHittingBlock(false); ctx.playerController().setHittingBlock(false);

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