Compare commits

...

113 Commits

Author SHA1 Message Date
Hykilpikonna efa7fec3ae [F] Use json instead of js to store presets 2020-02-21 15:50:48 -05:00
Hykilpikonna a73f2ccbd9 [F] Fix access issue 2020-02-21 15:46:59 -05:00
Hykilpikonna 136f175b12 [+] Create waitfor task 2020-02-21 14:49:56 -05:00
Hykilpikonna 0515a34b63 [+] Create replay task 2020-02-21 14:49:47 -05:00
Hykilpikonna 392ca87a66 [+] Create interaction task 2020-02-21 14:49:37 -05:00
Hykilpikonna c7260580d5 [+] Create delay task 2020-02-21 14:49:27 -05:00
Hykilpikonna f5d49af0a1 [+] Create condition task 2020-02-21 14:49:16 -05:00
Hykilpikonna 5d300244ea [M] Rename package util to utils 2020-02-21 14:41:22 -05:00
Hykilpikonna 2b27d3e03d [+] Create task manager 2020-02-21 14:39:39 -05:00
Hykilpikonna bddc598e88 [+] Create other util methods 2020-02-21 14:39:13 -05:00
Hykilpikonna d3f677d82d [+] Create rotateToBlock() 2020-02-21 14:38:59 -05:00
Hykilpikonna a00255d4b0 [+] Create rotate() 2020-02-21 14:38:33 -05:00
Hykilpikonna b77e7651e7 [+] Create getNeededRotations() 2020-02-21 14:38:15 -05:00
Hykilpikonna 88b8b88474 [+] Create getEyePos() 2020-02-21 14:38:02 -05:00
Hykilpikonna dc010b07a2 [+] Create PlayerUtils 2020-02-21 14:37:46 -05:00
Hykilpikonna bd084ee100 [+] Add lombok dependency 2020-02-21 14:37:19 -05:00
Hykilpikonna 866a704100 [+] Implement mouse mixin 2020-02-21 13:59:44 -05:00
Hykilpikonna 0e228149f6 [+] Create sleep() method 2020-02-21 13:59:22 -05:00
Hykilpikonna ad254f9364 [+] Create duck interface for mouse mixin 2020-02-21 13:59:10 -05:00
Hykilpikonna 94fd115734 [O] Specify username instead of generating random usernames 2020-02-21 13:46:18 -05:00
Hykilpikonna 5d148e56e6 [M] Use proper package names 2020-02-21 13:46:00 -05:00
Hykilpikonna 90a388f04c [O] Reset settings on command stop 2020-02-19 23:08:45 -05:00
Hykilpikonna 2024f31def [F] Fix thread locking 2020-02-19 23:07:42 -05:00
Hykilpikonna ec063cc955 [O] Remove initial delay 2020-02-19 23:07:22 -05:00
Hykilpikonna 12f6f1e846 [O] Actually use the blockToFind var 2020-02-19 23:07:06 -05:00
Hykilpikonna 0f94b958bc [F] Remove air block when pruning 2020-02-19 23:06:45 -05:00
Hykilpikonna 9753b3e3ba [F] Fix mutable pos toString issue 2020-02-19 21:41:33 -05:00
Hykilpikonna c0e4061c45 [O] Send remove block async 2020-02-19 21:28:19 -05:00
Hykilpikonna 386dbf84dd [-] Remove unnecessary debug msg 2020-02-19 21:16:59 -05:00
Hykilpikonna 8df51839d1 [O] Automatically enable mine with seed on command 2020-02-19 21:16:44 -05:00
Hykilpikonna c2671c38b0 [F] Also remove block in map when breaking 2020-02-19 21:16:28 -05:00
Hykilpikonna f553078672 [F] Fix GSON issue on actual client 2020-02-19 21:16:12 -05:00
Hykilpikonna 61aac18212 [F] Replace get block state if mining with seed 2020-02-19 21:15:38 -05:00
Hykilpikonna 78ba6a7aae [O] Only remove block from the server if it is a targeted block 2020-02-19 21:14:25 -05:00
Hykilpikonna 71c0e5c36f [O] Remove block from server on break 2020-02-19 21:12:24 -05:00
Hykilpikonna 4a800dc3ee [O] Prune without removing blocks 2020-02-19 21:10:22 -05:00
Hykilpikonna b38d2c9680 [+] Read seed server cache when scanning 2020-02-19 21:09:47 -05:00
Hykilpikonna 24a3034514 [+] Create block map 2020-02-19 21:08:01 -05:00
Hykilpikonna 90e41977a7 [O] Remove unnecessary outer loop 2020-02-19 21:07:04 -05:00
Hykilpikonna f57899838a [O] Check exited outside the loop 2020-02-19 20:58:01 -05:00
Hykilpikonna 09c8799eb4 [-] Remove loadChunks 2020-02-19 20:55:22 -05:00
Hykilpikonna a776cabb24 [O] Use timeout for updateCache 2020-02-19 20:53:56 -05:00
Hykilpikonna c268e0523f [F] Fix calling onTick when not in game 2020-02-19 20:53:38 -05:00
Hykilpikonna 24a8435c61 [F] Use cacheLocation 2020-02-19 20:53:13 -05:00
Hykilpikonna 0105b5046e [+] Create mine with seed setting 2020-02-19 18:06:19 -05:00
Hykilpikonna ea75b6f0b9 [O] Optimize user response 2020-02-19 18:05:48 -05:00
Hykilpikonna 73b4b09b67 [F] Fix chunk preloading 2020-02-19 18:05:18 -05:00
Hykilpikonna 3973a2eb4e [F] Fix concurrent modification error 2020-02-19 18:05:06 -05:00
Hykilpikonna 5a0f23c150 [+] Add Hyritone message prefix 2020-02-19 18:00:20 -05:00
Hykilpikonna b51760360a [+] Create hyritone field in baritone 2020-02-19 17:39:38 -05:00
Hykilpikonna d4a4de62ba [+] Create hyritone class 2020-02-19 17:39:26 -05:00
Hykilpikonna da0c0fd0d0 [+] Register command 2020-02-19 17:39:05 -05:00
Hykilpikonna 886a60ae61 [O] Optimize render lag 2020-02-19 17:38:44 -05:00
Hykilpikonna fef0182991 [+] Create seed xray command 2020-02-19 17:38:18 -05:00
Hykilpikonna 0309de04ef [+] Create utility to print message 2020-02-19 17:36:38 -05:00
Hykilpikonna 2afd0ddc03 [+] Create class to cache seed server responses 2020-02-19 17:36:15 -05:00
Hykilpikonna eddbb9eba2 [+] Add block destroy listener 2020-02-19 17:35:40 -05:00
Hykilpikonna 05a5d89376 Revert "[+] #2: Add settings for search distances"
This reverts commit 12fa664052.
2020-02-17 11:13:00 -05:00
Hykilpikonna 953414933b Revert "[+] #2 Use search distances for mining"
This reverts commit 5256f2a6a4.
2020-02-17 11:12:38 -05:00
Hykilpikonna 5256f2a6a4 [+] #2 Use search distances for mining 2020-02-17 11:04:22 -05:00
Hykilpikonna 12fa664052 [+] #2: Add settings for search distances 2020-02-17 11:02:39 -05:00
Hykilpikonna d63f8d9f83 [P] Patch #1: Remove allowBreak check for mining 2020-02-17 10:29:22 -05:00
Leijurv 606e9bf97c v1.5.1 2020-02-14 15:28:37 -08:00
Leijurv 47ae75a9d6 Merge branch '1.14.4' into 1.15.2 2020-02-14 15:26:34 -08:00
Leijurv 25587e317a fix link click crash 2020-02-14 15:26:03 -08:00
Leijurv b3ba129fc5 honey is stupid lets just not 2020-02-13 18:59:08 -08:00
Leijurv 746b7b5c88 not unscuffed, just differently scuffed 2020-02-13 18:57:32 -08:00
Brady db2f6ec78d Update mappings to 20200213-1.15.1 2020-02-13 14:44:29 -06:00
Leijurv 96bcabff8b v1.5.0 2020-02-13 12:04:29 -08:00
Leijurv 0a1fe857dc cant walk through honey blocks 2020-02-13 12:03:09 -08:00
Brady 49aaa55172 Fix click 2020-02-09 13:38:46 -06:00
Leijurv e03e251541 fix crouching 2020-02-05 17:45:22 -08:00
Leijurv f5380881f4 brady fix mixins im incompetent 2020-02-05 16:10:55 -08:00
Leijurv a022778fb6 cursed but fixes blockoptionalmeta 2020-02-05 15:14:32 -08:00
Leijurv 8543a99fba compiles and can path 2020-02-05 14:54:03 -08:00
Brady 997888fe85 Merge branch '1.14.4' into 1.15.1 2020-01-10 20:15:43 -06:00
Brady 94a2e13561 Merge branch '1.13.2' into 1.14.4 2020-01-10 20:14:46 -06:00
Brady 2d2030ecdf Fix renderGoalXZBeacon 2020-01-10 20:07:33 -06:00
Brady a3dec3a47e Render stuff should be fixed now.
There is likely a better solution, but I think this is fine in order to keep things in-line with the development over at Mojang.
2020-01-10 19:37:00 -06:00
Brady eb348120d9 Fix Mixins 2020-01-10 18:59:57 -06:00
Brady 27cb708d40 Fix some render stuff but it's still broken 2020-01-09 20:09:49 -06:00
Leijurv 36bbe430d4 add fixmes 2020-01-09 17:27:28 -08:00
Leijurv 80952e091d comment out anything that isn't instantly obvious how to fix (e.g. anything involving rendering) 2020-01-09 17:15:05 -08:00
Leijurv 760ac5dd8f v1.4.4 2020-01-04 21:58:55 -08:00
Brady 92966dc57c Merge branch '1.13.2' into 1.14.4 2019-12-31 21:57:55 -06:00
Leijurv 214225c08d v1.4.3 2019-10-13 22:53:05 -07:00
Leijurv 05b5894348 a much better way to deal with this 2019-10-13 10:53:25 -07:00
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
150 changed files with 2987 additions and 2042 deletions
+6 -3
View File
@@ -16,7 +16,7 @@
*/ */
group 'baritone' group 'baritone'
version '1.3.6' version '1.5.1'
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: '20200213-1.15.1'
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.15.2'
runtime launchCompile('net.minecraft:launchwrapper:1.12') { runtime launchCompile('net.minecraft:launchwrapper:1.12') {
exclude module: 'lwjgl' exclude module: 'lwjgl'
@@ -155,6 +155,9 @@ dependencies {
} }
testImplementation 'junit:junit:4.12' testImplementation 'junit:junit:4.12'
compileOnly 'org.projectlombok:lombok:1.18.12'
annotationProcessor 'org.projectlombok:lombok:1.18.12'
} }
mixin { mixin {
@@ -20,8 +20,8 @@ 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.player.ClientPlayerEntity;
import baritone.api.schematic.ISchematicSystem; import baritone.api.schematic.ISchematicSystem;
import net.minecraft.client.entity.EntityPlayerSP;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -47,19 +47,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;
+15 -5
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;
@@ -30,8 +30,8 @@ import java.awt.*;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.*;
import java.util.List; import java.util.List;
import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
/** /**
@@ -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
))); )));
/** /**
@@ -832,6 +830,13 @@ public final class Settings {
*/ */
public final Setting<Boolean> mineScanDroppedItems = new Setting<>(true); public final Setting<Boolean> mineScanDroppedItems = new Setting<>(true);
// Hyritone start
/**
* Detect ore locations with a separate world seed.
*/
public final Setting<Boolean> mineWithSeed = new Setting<>(false);
// Hyritone end
/** /**
* While mining, wait this number of milliseconds after mining an ore to see if it will drop an item * While mining, wait this number of milliseconds after mining an ore to see if it will drop an item
* instead of immediately going onto the next one * instead of immediately going onto the next one
@@ -960,6 +965,11 @@ public final class Settings {
*/ */
public final Setting<Consumer<ITextComponent>> logger = new Setting<>(Minecraft.getInstance().ingameGUI.getChatGUI()::printChatMessage); public final Setting<Consumer<ITextComponent>> logger = new Setting<>(Minecraft.getInstance().ingameGUI.getChatGUI()::printChatMessage);
/**
* Print out ALL command exceptions as a stack trace to stdout, even simple syntax errors
*/
public final Setting<Boolean> verboseCommandExceptions = new Setting<>(false);
/** /**
* The size of the box that is rendered when the current goal is a GoalYLevel * The size of the box that is rendered when the current goal is a GoalYLevel
*/ */
+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;
} }
} }
@@ -17,6 +17,9 @@
package baritone.api.event.events; package baritone.api.event.events;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.renderer.Matrix4f;
/** /**
* @author Brady * @author Brady
* @since 8/5/2018 * @since 8/5/2018
@@ -28,8 +31,13 @@ public final class RenderEvent {
*/ */
private final float partialTicks; private final float partialTicks;
public RenderEvent(float partialTicks) { private final Matrix4f projectionMatrix;
private final MatrixStack modelViewStack;
public RenderEvent(float partialTicks, MatrixStack modelViewStack, Matrix4f projectionMatrix) {
this.partialTicks = partialTicks; this.partialTicks = partialTicks;
this.modelViewStack = modelViewStack;
this.projectionMatrix = projectionMatrix;
} }
/** /**
@@ -38,4 +46,12 @@ public final class RenderEvent {
public final float getPartialTicks() { public final float getPartialTicks() {
return this.partialTicks; return this.partialTicks;
} }
public MatrixStack getModelViewStack() {
return this.modelViewStack;
}
public Matrix4f getProjectionMatrix() {
return this.projectionMatrix;
}
} }
@@ -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;
} }
@@ -18,6 +18,7 @@
package baritone.api.event.listener; package baritone.api.event.listener;
import baritone.api.event.events.*; import baritone.api.event.events.*;
import net.minecraft.util.math.BlockPos;
/** /**
* An implementation of {@link IGameEventListener} that has all methods * An implementation of {@link IGameEventListener} that has all methods
@@ -71,4 +72,7 @@ public interface AbstractGameEventListener extends IGameEventListener {
@Override @Override
default void onPathEvent(PathEvent event) {} default void onPathEvent(PathEvent event) {}
@Override
default void onBlockBreak(BlockPos pos) {}
} }
@@ -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.Screen;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.world.ClientWorld;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.network.Packet; import net.minecraft.util.math.BlockPos;
/** /**
* @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);
@@ -138,4 +137,11 @@ public interface IGameEventListener {
* @param event The event * @param event The event
*/ */
void onPathEvent(PathEvent event); void onPathEvent(PathEvent event);
/**
* This is called when the player breaks blocks.
*
* @param pos Block position
*/
void onBlockBreak(BlockPos pos);
} }
@@ -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;
@@ -32,7 +32,7 @@ public class FillSchematic extends AbstractSchematic {
this.bom = bom; this.bom = bom;
} }
public FillSchematic(int x, int y, int z, IBlockState state) { public FillSchematic(int x, int y, int z, BlockState state) {
this(x, y, z, new BlockOptionalMeta(state.getBlock())); this(x, y, z, new BlockOptionalMeta(state.getBlock()));
} }
@@ -41,13 +41,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;
/** /**
* A static schematic is capable of providing the desired state at a given position without * A static schematic is capable of providing the desired state at a given position without
@@ -31,7 +31,7 @@ import net.minecraft.block.state.IBlockState;
public interface IStaticSchematic extends ISchematic { public interface IStaticSchematic extends ISchematic {
/** /**
* Gets the {@link IBlockState} for a given position in this schematic. It should be guaranteed * Gets the {@link BlockState} for a given position in this schematic. It should be guaranteed
* that the return value of this method will not change given that the parameters are the same. * that the return value of this method will not change given that the parameters are the same.
* *
* @param x The X block position * @param x The X block position
@@ -39,19 +39,19 @@ public interface IStaticSchematic extends ISchematic {
* @param z The Z block position * @param z The Z block position
* @return The desired state at the specified position. * @return The desired state at the specified position.
*/ */
IBlockState getDirect(int x, int y, int z); BlockState getDirect(int x, int y, int z);
/** /**
* Returns an {@link IBlockState} array of size {@link #heightY()} which contains all * Returns an {@link BlockState} array of size {@link #heightY()} which contains all
* desired block states in the specified vertical column. The index of {@link IBlockState}s * desired block states in the specified vertical column. The index of {@link BlockState}s
* in the array are equivalent to their Y position in the schematic. * in the array are equivalent to their Y position in the schematic.
* *
* @param x The X column position * @param x The X column position
* @param z The Z column position * @param z The Z column position
* @return An {@link IBlockState} array * @return An {@link BlockState} array
*/ */
default IBlockState[] getColumn(int x, int z) { default BlockState[] getColumn(int x, int z) {
IBlockState[] column = new IBlockState[this.heightY()]; BlockState[] column = new BlockState[this.heightY()];
for (int i = 0; i < this.heightY(); i++) { for (int i = 0; i < this.heightY(); i++) {
column[i] = getDirect(x, i, z); column[i] = getDirect(x, i, z);
} }
@@ -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,29 +19,35 @@ 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 net.minecraft.block.*; import io.netty.util.concurrent.ThreadPerTaskExecutor;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.state.IProperty; import net.minecraft.resources.*;
import net.minecraft.state.properties.*;
import net.minecraft.util.EnumFacing;
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.world.storage.loot.*;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.*; import java.util.*;
import java.util.function.Consumer; import java.util.concurrent.CompletableFuture;
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 LootTableManager manager;
private static LootPredicateManager predicate = new LootPredicateManager();
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;
@@ -59,38 +65,32 @@ public final class BlockOptionalMeta {
MatchResult matchResult = matcher.toMatchResult(); MatchResult matchResult = matcher.toMatchResult();
ResourceLocation id = new ResourceLocation(matchResult.group(1)); block = BlockUtils.stringToBlockRequired(matchResult.group(1));
if (!IRegistry.BLOCK.containsKey(id)) {
throw new IllegalArgumentException("Invalid block ID");
}
block = IRegistry.BLOCK.get(id);
blockstates = getStates(block); blockstates = getStates(block);
stateHashes = getStateHashes(blockstates); stateHashes = getStateHashes(blockstates);
stackHashes = getStackHashes(blockstates); stackHashes = getStackHashes(blockstates);
} }
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)
); );
@@ -104,7 +104,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());
} }
@@ -123,11 +123,44 @@ 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(predicate);
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;
}
public static LootPredicateManager getPredicateManager() {
return predicate;
}
private static synchronized List<Item> drops(Block b) {
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,19 +35,28 @@ 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();
default BetterBlockPos playerFeet() { default BetterBlockPos playerFeet() {
// TODO find a better way to deal with soul sand!!!!! // TODO find a better way to deal with soul sand!!!!!
BetterBlockPos feet = new BetterBlockPos(player().posX, player().posY + 0.1251, player().posZ); BetterBlockPos feet = new BetterBlockPos(player().getPositionVec().x, player().getPositionVec().y + 0.1251, player().getPositionVec().z);
// sometimes when calling this from another thread or while world is null, it'll throw a NullPointerException // sometimes when calling this from another thread or while world is null, it'll throw a NullPointerException
// that causes the game to immediately crash // that causes the game to immediately crash
@@ -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) {}
@@ -66,11 +76,11 @@ public interface IPlayerContext {
} }
default Vec3d playerFeetAsVec() { default Vec3d playerFeetAsVec() {
return new Vec3d(player().posX, player().posY, player().posZ); return new Vec3d(player().getPositionVec().x, player().getPositionVec().y, player().getPositionVec().z);
} }
default Vec3d playerHead() { default Vec3d playerHead() {
return new Vec3d(player().posX, player().posY + player().getEyeHeight(), player().posZ); return new Vec3d(player().getPositionVec().x, player().getPositionVec().y + player().getEyeHeight(), player().getPositionVec().z);
} }
default Rotation playerRotations() { default Rotation playerRotations() {
@@ -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,16 +17,16 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.container.ClickType;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.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;
@@ -40,19 +40,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
+10 -10
View File
@@ -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(
@@ -105,7 +105,7 @@ public final class VecUtils {
* @see #getBlockPosCenter(BlockPos) * @see #getBlockPosCenter(BlockPos)
*/ */
public static double entityDistanceToCenter(Entity entity, BlockPos pos) { public static double entityDistanceToCenter(Entity entity, BlockPos pos) {
return distanceToCenter(pos, entity.posX, entity.posY, entity.posZ); return distanceToCenter(pos, entity.getPositionVec().x, entity.getPositionVec().y, entity.getPositionVec().z);
} }
/** /**
@@ -118,6 +118,6 @@ public final class VecUtils {
* @see #getBlockPosCenter(BlockPos) * @see #getBlockPosCenter(BlockPos)
*/ */
public static double entityFlatDistanceToCenter(Entity entity, BlockPos pos) { public static double entityFlatDistanceToCenter(Entity entity, BlockPos pos) {
return distanceToCenter(pos, entity.posX, pos.getY() + 0.5, entity.posZ); return distanceToCenter(pos, entity.getPositionVec().x, pos.getY() + 0.5, entity.getPositionVec().z);
} }
} }
@@ -57,6 +57,9 @@ public class LaunchTesting {
attemptLogin(arguments, System.getenv("username"), System.getenv("password")); attemptLogin(arguments, System.getenv("username"), System.getenv("password"));
} }
// TODO: Remove
arguments.put("username", "TestUser");
List<String> argsArray = new ArrayList<>(); List<String> argsArray = new ArrayList<>();
arguments.forEach((k, v) -> { arguments.forEach((k, v) -> {
argsArray.add("--" + k); argsArray.add("--" + k);
@@ -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();
} }
@@ -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.CommandSuggestionHelper;
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,27 +40,28 @@ import java.util.stream.Stream;
* @author Brady * @author Brady
* @since 10/9/2019 * @since 10/9/2019
*/ */
@Mixin(GuiChat.class) @Mixin(CommandSuggestionHelper.class)
public class MixinGuiChat { public class MixinCommandSuggestionHelper {
@Shadow
protected GuiTextField inputField;
@Shadow @Shadow
@Final @Final
protected List<String> commandUsage; private TextFieldWidget field_228095_d_;
@Shadow @Shadow
private CompletableFuture<Suggestions> pendingSuggestions; @Final
private List<String> field_228103_l_;
@Shadow
private CompletableFuture<Suggestions> field_228107_p_;
@Inject( @Inject(
method = "updateSuggestion", method = "func_228111_a_",
at = @At("HEAD"), at = @At("HEAD"),
cancellable = true cancellable = true
) )
private void preUpdateSuggestion(CallbackInfo ci) { private void preUpdateSuggestion(CallbackInfo ci) {
// Anything that is present in the input text before the cursor position // Anything that is present in the input text before the cursor position
String prefix = this.inputField.getText().substring(0, Math.min(this.inputField.getText().length(), this.inputField.getCursorPosition())); String prefix = this.field_228095_d_.getText().substring(0, Math.min(this.field_228095_d_.getText().length(), this.field_228095_d_.getCursorPosition()));
TabCompleteEvent event = new TabCompleteEvent(prefix); TabCompleteEvent event = new TabCompleteEvent(prefix);
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onPreTabComplete(event); BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onPreTabComplete(event);
@@ -74,14 +75,14 @@ public class MixinGuiChat {
ci.cancel(); ci.cancel();
// TODO: Support populating the command usage // TODO: Support populating the command usage
this.commandUsage.clear(); this.field_228103_l_.clear();
if (event.completions.length == 0) { if (event.completions.length == 0) {
this.pendingSuggestions = Suggestions.empty(); this.field_228107_p_ = Suggestions.empty();
} else { } else {
int offset = this.inputField.getText().endsWith(" ") int offset = this.field_228095_d_.getText().endsWith(" ")
? this.inputField.getCursorPosition() ? this.field_228095_d_.getCursorPosition()
: this.inputField.getText().lastIndexOf(" ") + 1; // If there is no space this is still 0 haha yes : this.field_228095_d_.getText().lastIndexOf(" ") + 1; // If there is no space this is still 0 haha yes
List<Suggestion> suggestionList = Stream.of(event.completions) List<Suggestion> suggestionList = Stream.of(event.completions)
.map(s -> new Suggestion(StringRange.between(offset, offset + s.length()), s)) .map(s -> new Suggestion(StringRange.between(offset, offset + s.length()), s))
@@ -91,8 +92,8 @@ public class MixinGuiChat {
StringRange.between(offset, offset + suggestionList.stream().mapToInt(s -> s.getText().length()).max().orElse(0)), StringRange.between(offset, offset + suggestionList.stream().mapToInt(s -> s.getText().length()).max().orElse(0)),
suggestionList); suggestionList);
this.pendingSuggestions = new CompletableFuture<>(); this.field_228107_p_ = new CompletableFuture<>();
this.pendingSuggestions.complete(suggestions); this.field_228107_p_.complete(suggestions);
} }
} }
} }
@@ -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,25 +17,26 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.utils.accessor.IPlayerControllerMP; import baritone.utils.accessor.IEntityRenderManager;
import net.minecraft.client.multiplayer.PlayerControllerMP; import net.minecraft.client.renderer.entity.EntityRendererManager;
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.Invoker;
@Mixin(PlayerControllerMP.class) @Mixin(EntityRendererManager.class)
public abstract class MixinPlayerControllerMP implements IPlayerControllerMP { public class MixinEntityRenderManager implements IEntityRenderManager {
@Accessor
@Override @Override
public abstract void setIsHittingBlock(boolean isHittingBlock); public double renderPosX() {
return ((EntityRendererManager) (Object) this).info.getProjectedView().x;
}
@Accessor
@Override @Override
public abstract BlockPos getCurrentBlock(); public double renderPosY() {
return ((EntityRendererManager) (Object) this).info.getProjectedView().y;
}
@Invoker
@Override @Override
public abstract void callSyncCurrentPlayItem(); public double renderPosZ() {
return ((EntityRendererManager) (Object) this).info.getProjectedView().z;
}
} }
@@ -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,74 @@
/*
* 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.LootPredicateManager;
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();
}
@Redirect(
method = "build",
at = @At(
value = "INVOKE",
target = "net/minecraft/server/MinecraftServer.func_229736_aP_()Lnet/minecraft/world/storage/loot/LootPredicateManager;"
)
)
private LootPredicateManager getLootPredicateManager(MinecraftServer server) {
if (server == null) {
return BlockOptionalMeta.getPredicateManager();
}
return server.func_229736_aP_();
}
}
@@ -19,19 +19,14 @@ 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.BlockInteractEvent;
import baritone.api.event.events.TickEvent; import baritone.api.event.events.TickEvent;
import baritone.api.event.events.WorldEvent; import baritone.api.event.events.WorldEvent;
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.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
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;
@@ -39,7 +34,6 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import java.util.function.BiFunction; import java.util.function.BiFunction;
@@ -51,12 +45,12 @@ import java.util.function.BiFunction;
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>",
at = @At("RETURN") at = @At("RETURN")
) )
private void postInit(CallbackInfo ci) { private void postInit(CallbackInfo ci) {
@@ -64,11 +58,8 @@ public class MixinMinecraft {
} }
@Inject( @Inject(
method = "init", method = "startTimerHackThread",
at = @At( at = @At("HEAD")
value = "INVOKE",
target = "net/minecraft/client/Minecraft.startTimerHackThread()V"
)
) )
private void preInit(CallbackInfo ci) { private void preInit(CallbackInfo ci) {
BaritoneAutoTest.INSTANCE.onPreInit(); BaritoneAutoTest.INSTANCE.onPreInit();
@@ -79,7 +70,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
@@ -100,10 +91,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;
@@ -120,10 +111,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
@@ -140,37 +131,32 @@ 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( // TODO
method = "clickMouse", // FIXME
at = @At( // bradyfix
value = "INVOKE", // i cant mixin
target = "net/minecraft/client/multiplayer/PlayerControllerMP.clickBlock(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/EnumFacing;)Z" // lol
), // https://discordapp.com/channels/208753003996512258/503692253881958400/674760939681349652
locals = LocalCapture.CAPTURE_FAILHARD // https://discordapp.com/channels/208753003996512258/503692253881958400/674756457966862376
) /*@Inject(
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(
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",
ordinal = 1
), ),
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, EntityRayTraceResult rt, Entity ent, ActionResultType art, 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));
} }*/
} }
@@ -0,0 +1,99 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.utils.accessor.IMouse;
import net.minecraft.client.Minecraft;
import net.minecraft.client.MouseHelper;
import org.spongepowered.asm.mixin.Final;
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;
import static org.hydev.hyritone.utils.MiscUtils.sleep;
/**
* Mixin to control mouse operations
* <p>
* Class created by the HyDEV Team on 2020-02-21!
*
* @author HyDEV Team (https://github.com/HyDevelop)
* @author Hykilpikonna (https://github.com/hykilpikonna)
* @author Vanilla (https://github.com/VergeDX)
* @since 2020-02-21 13:54
*/
@Mixin(MouseHelper.class)
public abstract class MixinMouse implements IMouse
{
@Shadow
protected abstract void mouseButtonCallback(long window, int button, int action, int mods);
@Shadow @Final private Minecraft minecraft;
@Inject(method = "mouseButtonCallback", at = @At("HEAD"), cancellable = true)
private void inject(long window, int button, int action, int mods, CallbackInfo info)
{
System.out.println(window + " | " + button + " | " + action + " | " + mods + " | " + System.currentTimeMillis());
}
public void rightClick()
{
new Thread(() ->
{
rightHold();
sleep((long) (70 + Math.random() * 10));
rightRelease();
}).start();
}
public void leftClick()
{
new Thread(() ->
{
leftHold();
sleep((long) (70 + Math.random() * 10));
leftRelease();
}).start();
}
@Override
public void rightHold()
{
mouseButtonCallback(minecraft.getMainWindow().getHandle(), 1, 1, 0);
}
@Override
public void rightRelease()
{
mouseButtonCallback(minecraft.getMainWindow().getHandle(), 1, 0, 0);
}
@Override
public void leftHold()
{
mouseButtonCallback(minecraft.getMainWindow().getHandle(), 0, 1, 0);
}
@Override
public void leftRelease()
{
mouseButtonCallback(minecraft.getMainWindow().getHandle(), 0, 0, 0);
}
}
@@ -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,25 +18,25 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.utils.accessor.IBitArray; import baritone.utils.accessor.IBitArray;
import baritone.utils.accessor.IBlockStateContainer; import baritone.utils.accessor.IPalettedContainer;
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.util.palette.IPalette;
import net.minecraft.world.chunk.IBlockStatePalette; import net.minecraft.util.palette.PalettedContainer;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
@Mixin(BlockStateContainer.class) @Mixin(PalettedContainer.class)
public abstract class MixinBlockStateContainer implements IBlockStateContainer { public abstract class MixinPalettedContainer implements IPalettedContainer {
@Shadow @Shadow
protected BitArray storage; protected BitArray storage;
@Shadow @Shadow
protected IBlockStatePalette<IBlockState> palette; protected IPalette<BlockState> palette;
@Override @Override
public IBlockState getAtPalette(int index) { public BlockState getAtPalette(int index) {
return palette.get(index); return palette.get(index);
} }
@@ -0,0 +1,69 @@
/*
* 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.IBaritone;
import baritone.utils.accessor.IPlayerControllerMP;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.PlayerController;
import net.minecraft.util.math.BlockPos;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(PlayerController.class)
public abstract class MixinPlayerController implements IPlayerControllerMP {
@Shadow
@Final
private Minecraft mc;
@Accessor
@Override
public abstract void setIsHittingBlock(boolean isHittingBlock);
@Accessor
@Override
public abstract BlockPos getCurrentBlock();
@Invoker
@Override
public abstract void callSyncCurrentPlayItem();
@Inject(
method = "onPlayerDestroyBlock",
at = @At(value = "TAIL")
)
public void onPlayerDestroyBlock(BlockPos pos, CallbackInfoReturnable<Boolean> cir)
{
// Check if the block is broken
if (!cir.getReturnValue()) return;
// Call event
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer(this.mc.player);
if (baritone != null) {
baritone.getGameEventHandler().onBlockBreak(pos);
}
}
}
@@ -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 openLinkInvoker(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();
}
}
@@ -20,26 +20,29 @@ 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.RenderEvent; import baritone.api.event.events.RenderEvent;
import net.minecraft.client.renderer.GameRenderer; import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.renderer.*;
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;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
@Mixin(GameRenderer.class) /**
public class MixinGameRenderer { * @author Brady
* @since 2/13/2020
*/
@Mixin(WorldRenderer.class)
public class MixinWorldRenderer {
@Inject( @Inject(
method = "updateCameraAndRender(FJ)V", method = "updateCameraAndRender",
at = @At( at = @At("RETURN"),
value = "INVOKE_STRING", locals = LocalCapture.CAPTURE_FAILSOFT
target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V",
args = {"ldc=hand"}
)
) )
private void renderWorldPass(float partialTicks, long finishTimeNano, CallbackInfo ci) { private void onStartHand(MatrixStack matrixStackIn, float partialTicks, long finishTimeNano, boolean drawBlockOutline, ActiveRenderInfo activeRenderInfoIn, GameRenderer gameRendererIn, LightTexture lightmapIn, Matrix4f projectionIn, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks)); ibaritone.getGameEventHandler().onRenderPass(new RenderEvent(partialTicks, matrixStackIn, projectionIn));
} }
} }
} }
+13 -17
View File
@@ -8,26 +8,22 @@
"maxShiftBy": 2 "maxShiftBy": 2
}, },
"client": [ "client": [
"MixinAnvilChunkLoader",
"MixinBitArray", "MixinBitArray",
"MixinBlockStateContainer", "MixinChunkArray",
"MixinChunkProviderClient", "MixinClientChunkProvider",
"MixinChunkProviderServer", "MixinClientPlayerEntity",
"MixinChunkRenderContainer", "MixinClientPlayNetHandler",
"MixinChunkRenderWorker", "MixinCommandSuggestionHelper",
"MixinEntityLivingBase", "MixinEntity",
"MixinEntityPlayerSP", "MixinEntityRenderManager",
"MixinGameRenderer",
"MixinGuiChat",
"MixinGuiScreen",
"MixinItemStack", "MixinItemStack",
"MixinLivingEntity",
"MixinLootContext",
"MixinMinecraft", "MixinMinecraft",
"MixinNetHandlerPlayClient",
"MixinNetworkManager", "MixinNetworkManager",
"MixinPlayerControllerMP", "MixinPalettedContainer",
"MixinRenderChunk", "MixinPlayerController",
"MixinRenderChunkCache", "MixinScreen",
"MixinRenderList", "MixinWorldRenderer"
"MixinVboRenderList"
] ]
} }
+7 -1
View File
@@ -32,6 +32,7 @@ import baritone.utils.*;
import baritone.command.manager.CommandManager; import baritone.command.manager.CommandManager;
import baritone.utils.player.PrimaryPlayerContext; import baritone.utils.player.PrimaryPlayerContext;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import org.hydev.hyritone.Hyritone;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -87,6 +88,8 @@ public class Baritone implements IBaritone {
public BlockStateInterface bsi; public BlockStateInterface bsi;
public Hyritone hyritone;
Baritone() { Baritone() {
this.gameEventHandler = new GameEventHandler(this); this.gameEventHandler = new GameEventHandler(this);
@@ -121,6 +124,9 @@ public class Baritone implements IBaritone {
if (BaritoneAutoTest.ENABLE_AUTO_TEST) { if (BaritoneAutoTest.ENABLE_AUTO_TEST) {
this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE); this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE);
} }
// Hyritone
this.hyritone = new Hyritone(this);
} }
@Override @Override
@@ -218,7 +224,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().getPositionVec().x, ctx.player().getPositionVec().y, ctx.player().getPositionVec().z), 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());
@@ -381,8 +381,8 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
BetterBlockPos feet = ctx.playerFeet(); BetterBlockPos feet = ctx.playerFeet();
if (!MovementHelper.canWalkOn(ctx, feet.down())) { if (!MovementHelper.canWalkOn(ctx, feet.down())) {
if (ctx.player().onGround) { if (ctx.player().onGround) {
double playerX = ctx.player().posX; double playerX = ctx.player().getPositionVec().x;
double playerZ = ctx.player().posZ; double playerZ = ctx.player().getPositionVec().z;
ArrayList<BetterBlockPos> closest = new ArrayList<>(); ArrayList<BetterBlockPos> closest = new ArrayList<>();
for (int dx = -1; dx <= 1; dx++) { for (int dx = -1; dx <= 1; dx++) {
for (int dz = -1; dz <= 1; dz++) { for (int dz = -1; dz <= 1; dz++) {
+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:
+16 -16
View File
@@ -21,16 +21,16 @@ 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.util.palette.PalettedContainer;
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 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(); PalettedContainer<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(":", "_");
} }
+14 -15
View File
@@ -22,14 +22,14 @@ import baritone.api.cache.IWorldScanner;
import baritone.api.utils.BetterBlockPos; 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.IPalettedContainer;
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.AbstractChunkProvider;
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 +47,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 +71,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 +97,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()) {
@@ -118,7 +117,7 @@ public enum WorldScanner implements IWorldScanner {
@Override @Override
public int repack(IPlayerContext ctx, int range) { public int repack(IPlayerContext ctx, int range) {
IChunkProvider chunkProvider = ctx.world().getChunkProvider(); AbstractChunkProvider chunkProvider = ctx.world().getChunkProvider();
ICachedWorld cachedWorld = ctx.worldData().getCachedWorld(); ICachedWorld cachedWorld = ctx.worldData().getCachedWorld();
BetterBlockPos playerPos = ctx.playerFeet(); BetterBlockPos playerPos = ctx.playerFeet();
@@ -134,7 +133,7 @@ public enum WorldScanner implements IWorldScanner {
int queued = 0; int queued = 0;
for (int x = minX; x <= maxX; x++) { for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) { for (int z = minZ; z <= maxZ; z++) {
Chunk chunk = chunkProvider.getChunk(x, z, false, false); Chunk chunk = chunkProvider.getChunk(x, z, false);
if (chunk != null && !chunk.isEmpty()) { if (chunk != null && !chunk.isEmpty()) {
queued++; queued++;
@@ -151,18 +150,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(); IPalettedContainer bsc = (IPalettedContainer) 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) {
@@ -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,
@@ -100,7 +100,7 @@ public class BaritoneChatControl implements Helper, AbstractGameEventListener {
return false; return false;
} else if (msg.trim().equalsIgnoreCase("orderpizza")) { } else if (msg.trim().equalsIgnoreCase("orderpizza")) {
try { try {
((IGuiScreen) mc.currentScreen).openLink(new URI("https://www.dominos.com/en/pages/order/")); ((IGuiScreen) mc.currentScreen).openLinkInvoker(new URI("https://www.dominos.com/en/pages/order/"));
} catch (NullPointerException | URISyntaxException ignored) {} } catch (NullPointerException | URISyntaxException ignored) {}
return false; return false;
} }
@@ -17,7 +17,9 @@
package baritone.command.argument; package baritone.command.argument;
import baritone.Baritone;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.argument.ICommandArgument; import baritone.api.command.argument.ICommandArgument;
import baritone.api.command.datatypes.IDatatype; import baritone.api.command.datatypes.IDatatype;
import baritone.api.command.datatypes.IDatatypeContext; import baritone.api.command.datatypes.IDatatypeContext;
@@ -27,7 +29,6 @@ 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 baritone.api.command.exception.CommandTooManyArgumentsException; import baritone.api.command.exception.CommandTooManyArgumentsException;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.manager.ICommandManager; import baritone.api.command.manager.ICommandManager;
import java.util.ArrayList; import java.util.ArrayList;
@@ -316,6 +317,9 @@ public class ArgConsumer implements IArgConsumer {
try { try {
return datatype.apply(this.context, original); return datatype.apply(this.context, original);
} catch (Exception e) { } catch (Exception e) {
if (Baritone.settings().verboseCommandExceptions.value) {
e.printStackTrace();
}
throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName(), e); throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName(), e);
} }
} }
@@ -345,6 +349,9 @@ public class ArgConsumer implements IArgConsumer {
try { try {
return datatype.get(this.context); return datatype.get(this.context);
} catch (Exception e) { } catch (Exception e) {
if (Baritone.settings().verboseCommandExceptions.value) {
e.printStackTrace();
}
throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName(), e); throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName(), e);
} }
} }
@@ -19,6 +19,7 @@ package baritone.command.defaults;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.command.ICommand; import baritone.api.command.ICommand;
import org.hydev.hyritone.seedxray.SeedXrayCommand;
import java.util.*; import java.util.*;
@@ -64,7 +65,10 @@ public final class DefaultCommands {
new WaypointsCommand(baritone), new WaypointsCommand(baritone),
new CommandAlias(baritone, "sethome", "Sets your home waypoint", "waypoints save home"), new CommandAlias(baritone, "sethome", "Sets your home waypoint", "waypoints save home"),
new CommandAlias(baritone, "home", "Set goal to your home waypoint", "waypoints goal home"), new CommandAlias(baritone, "home", "Set goal to your home waypoint", "waypoints goal home"),
new SelCommand(baritone) new SelCommand(baritone),
// Hyritone
new SeedXrayCommand(baritone)
)); ));
ExecutionControlCommands prc = new ExecutionControlCommands(baritone); ExecutionControlCommands prc = new ExecutionControlCommands(baritone);
commands.add(prc.pauseCommand); commands.add(prc.pauseCommand);
@@ -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;
@@ -68,7 +68,7 @@ public class SelCommand extends Command {
float lineWidth = Baritone.settings().selectionLineWidth.value; float lineWidth = Baritone.settings().selectionLineWidth.value;
boolean ignoreDepth = Baritone.settings().renderSelectionIgnoreDepth.value; boolean ignoreDepth = Baritone.settings().renderSelectionIgnoreDepth.value;
IRenderer.startLines(color, opacity, lineWidth, ignoreDepth); IRenderer.startLines(color, opacity, lineWidth, ignoreDepth);
IRenderer.drawAABB(new AxisAlignedBB(pos1, pos1.add(1, 1, 1))); IRenderer.drawAABB(event.getModelViewStack(), new AxisAlignedBB(pos1, pos1.add(1, 1, 1)));
IRenderer.endLines(ignoreDepth); IRenderer.endLines(ignoreDepth);
} }
}); });
@@ -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(
@@ -25,6 +25,7 @@ import baritone.api.event.listener.IGameEventListener;
import baritone.api.utils.Helper; import baritone.api.utils.Helper;
import baritone.cache.WorldProvider; import baritone.cache.WorldProvider;
import baritone.utils.BlockStateInterface; import baritone.utils.BlockStateInterface;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
@@ -51,6 +52,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 +91,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 -> {
@@ -160,4 +162,9 @@ public final class GameEventHandler implements IEventBus, Helper {
public final void registerEventListener(IGameEventListener listener) { public final void registerEventListener(IGameEventListener listener) {
this.listeners.add(listener); this.listeners.add(listener);
} }
public final void onBlockBreak(BlockPos blockPos)
{
listeners.forEach(l -> l.onBlockBreak(blockPos));
}
} }
@@ -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;
import net.minecraft.world.IBlockReader; import net.minecraft.world.IBlockReader;
@@ -55,10 +50,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)
@@ -71,13 +66,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();
@@ -91,27 +86,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 || block == Blocks.HONEY_BLOCK) {
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
@@ -121,7 +116,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?
@@ -135,8 +130,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;
@@ -144,7 +139,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(bsi.access, BlockPos.ORIGIN, PathType.LAND); // workaround for future compatibility =P return state.allowsMovement(bsi.access, BlockPos.ZERO, PathType.LAND); // workaround for future compatibility =P
} }
/** /**
@@ -169,9 +164,9 @@ public interface MovementHelper extends ActionCosts, Helper {
return fullyPassable(ctx.world(), pos, ctx.world().getBlockState(pos)); return fullyPassable(ctx.world(), pos, ctx.world().getBlockState(pos));
} }
static boolean fullyPassable(IBlockReader access, BlockPos pos, IBlockState state) { static boolean fullyPassable(IBlockReader access, BlockPos pos, 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
@@ -181,21 +176,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(access, pos, PathType.LAND); return state.allowsMovement(access, pos, 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
@@ -207,16 +202,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;
@@ -225,7 +220,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);
} }
@@ -234,12 +229,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) {
@@ -247,27 +242,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;
} }
@@ -275,7 +270,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
@@ -298,14 +293,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 || block == Blocks.HONEY_BLOCK) {
// 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
@@ -320,9 +315,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) {
@@ -336,19 +331,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);
} }
@@ -376,18 +371,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()) {
@@ -408,8 +403,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);
} }
} }
@@ -418,9 +413,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;
} }
/** /**
@@ -429,7 +424,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);
} }
@@ -440,7 +435,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);
} }
@@ -460,7 +455,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;
} }
@@ -477,7 +472,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;
} }
@@ -493,17 +488,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;
@@ -517,6 +512,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();
@@ -539,7 +544,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;
@@ -553,7 +558,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,12 +171,12 @@ 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) {
state.setInput(Input.SNEAK, true); state.setInput(Input.SNEAK, true);
if (ctx.player().isSneaking()) { if (ctx.player().isCrouching()) {
state.setInput(Input.CLICK_RIGHT, true); state.setInput(Input.CLICK_RIGHT, true);
} }
} }
@@ -200,10 +199,10 @@ public class MovementAscend extends Movement {
int xAxis = Math.abs(src.getX() - dest.getX()); // either 0 or 1 int xAxis = Math.abs(src.getX() - dest.getX()); // either 0 or 1
int zAxis = Math.abs(src.getZ() - dest.getZ()); // either 0 or 1 int zAxis = Math.abs(src.getZ() - dest.getZ()); // either 0 or 1
double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ); double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().getPositionVec().x) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().getPositionVec().z);
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().getPositionVec().x) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().getPositionVec().z);
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)) {
@@ -212,17 +212,17 @@ public class MovementDescend extends Movement {
BlockPos playerFeet = ctx.playerFeet(); BlockPos playerFeet = ctx.playerFeet();
BlockPos fakeDest = new BlockPos(dest.getX() * 2 - src.getX(), dest.getY(), dest.getZ() * 2 - src.getZ()); BlockPos fakeDest = new BlockPos(dest.getX() * 2 - src.getX(), dest.getY(), dest.getZ() * 2 - src.getZ());
if ((playerFeet.equals(dest) || playerFeet.equals(fakeDest)) && (MovementHelper.isLiquid(ctx, dest) || ctx.player().posY - dest.getY() < 0.5)) { // lilypads if ((playerFeet.equals(dest) || playerFeet.equals(fakeDest)) && (MovementHelper.isLiquid(ctx, dest) || ctx.player().getPositionVec().y - dest.getY() < 0.5)) { // lilypads
// Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately // Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately
return state.setStatus(MovementStatus.SUCCESS); return state.setStatus(MovementStatus.SUCCESS);
/* else { /* else {
// System.out.println(player().posY + " " + playerFeet.getY() + " " + (player().posY - playerFeet.getY())); // System.out.println(player().getPositionVec().y + " " + playerFeet.getY() + " " + (player().getPositionVec().y - playerFeet.getY()));
}*/ }*/
} }
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),
@@ -231,11 +231,11 @@ public class MovementDescend extends Movement {
)).setInput(Input.MOVE_FORWARD, true); )).setInput(Input.MOVE_FORWARD, true);
return state; return state;
} }
double diffX = ctx.player().posX - (dest.getX() + 0.5); double diffX = ctx.player().getPositionVec().x - (dest.getX() + 0.5);
double diffZ = ctx.player().posZ - (dest.getZ() + 0.5); double diffZ = ctx.player().getPositionVec().z - (dest.getZ() + 0.5);
double ab = Math.sqrt(diffX * diffX + diffZ * diffZ); double ab = Math.sqrt(diffX * diffX + diffZ * diffZ);
double x = ctx.player().posX - (src.getX() + 0.5); double x = ctx.player().getPositionVec().x - (src.getX() + 0.5);
double z = ctx.player().posZ - (src.getZ() + 0.5); double z = ctx.player().getPositionVec().z - (src.getZ() + 0.5);
double fromStart = Math.sqrt(x * x + z * z); double fromStart = Math.sqrt(x * x + z * z);
if (!playerFeet.equals(dest) || ab > 0.25) { if (!playerFeet.equals(dest) || ab > 0.25) {
if (numTicks++ < 20 && fromStart < 1.25) { if (numTicks++ < 20 && fromStart < 1.25) {
@@ -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;
@@ -226,7 +226,7 @@ public class MovementDiagonal extends Movement {
} else if (!playerInValidPosition() && !(MovementHelper.isLiquid(ctx, src) && getValidPositions().contains(ctx.playerFeet().up()))) { } else if (!playerInValidPosition() && !(MovementHelper.isLiquid(ctx, src) && getValidPositions().contains(ctx.playerFeet().up()))) {
return state.setStatus(MovementStatus.UNREACHABLE); return state.setStatus(MovementStatus.UNREACHABLE);
} }
if (dest.y > src.y && ctx.player().posY < src.y + 0.1 && ctx.player().collidedHorizontally) { if (dest.y > src.y && ctx.player().getPositionVec().y < src.y + 0.1 && ctx.player().collidedHorizontally) {
state.setInput(Input.JUMP, true); state.setInput(Input.JUMP, true);
} }
if (sprint()) { if (sprint()) {
@@ -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;
@@ -84,8 +84,8 @@ public class MovementDownward extends Movement {
} else if (!playerInValidPosition()) { } else if (!playerInValidPosition()) {
return state.setStatus(MovementStatus.UNREACHABLE); return state.setStatus(MovementStatus.UNREACHABLE);
} }
double diffX = ctx.player().posX - (dest.getX() + 0.5); double diffX = ctx.player().getPositionVec().x - (dest.getX() + 0.5);
double diffZ = ctx.player().posZ - (dest.getZ() + 0.5); double diffZ = ctx.player().getPositionVec().z - (dest.getZ() + 0.5);
double ab = Math.sqrt(diffX * diffX + diffZ * diffZ); double ab = Math.sqrt(diffX * diffX + diffZ * diffZ);
if (numTicks++ < 10 && ab < 0.2) { if (numTicks++ < 10 && ab < 0.2) {
@@ -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,15 +92,15 @@ 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);
} }
if (ctx.player().posY - dest.getY() < ctx.playerController().getBlockReachDistance() && !ctx.player().onGround) { if (ctx.player().getPositionVec().y - dest.getY() < ctx.playerController().getBlockReachDistance() && !ctx.player().onGround) {
ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER); ctx.player().inventory.currentItem = ctx.player().inventory.getSlotFor(STACK_BUCKET_WATER);
targetRotation = new Rotation(toDest.getYaw(), 90.0F); targetRotation = new Rotation(toDest.getYaw(), 90.0F);
@@ -115,17 +115,17 @@ public class MovementFall extends Movement {
} else { } else {
state.setTarget(new MovementTarget(toDest, false)); state.setTarget(new MovementTarget(toDest, false));
} }
if (playerFeet.equals(dest) && (ctx.player().posY - playerFeet.getY() < 0.094 || isWater)) { // 0.094 because lilypads if (playerFeet.equals(dest) && (ctx.player().getPositionVec().y - 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,17 +134,17 @@ 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().getPositionVec().x + ctx.player().getMotion().x - destCenter.x) > 0.1 || Math.abs(ctx.player().getPositionVec().z + 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 {
double dist = Math.abs(avoid.getX() * (destCenter.x - avoid.getX() / 2.0 - ctx.player().posX)) + Math.abs(avoid.getZ() * (destCenter.z - avoid.getZ() / 2.0 - ctx.player().posZ)); double dist = Math.abs(avoid.getX() * (destCenter.x - avoid.getX() / 2.0 - ctx.player().getPositionVec().x)) + Math.abs(avoid.getZ() * (destCenter.z - avoid.getZ() / 2.0 - ctx.player().getPositionVec().z));
if (dist < 0.6) { if (dist < 0.6) {
state.setInput(Input.MOVE_FORWARD, true); state.setInput(Input.MOVE_FORWARD, true);
} else if (!ctx.player().onGround) { } else if (!ctx.player().onGround) {
@@ -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(context.bsi.access, context.bsi.isPassableBlockPos.setPos(destX, y, destZ), destInto)) { if (!MovementHelper.fullyPassable(context.bsi.access, context.bsi.isPassableBlockPos.setPos(destX, y, destZ), 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;
@@ -246,19 +246,19 @@ public class MovementParkour extends Movement {
// but i did it anyway // but i did it anyway
return state.setStatus(MovementStatus.SUCCESS); return state.setStatus(MovementStatus.SUCCESS);
} }
if (ctx.player().posY - ctx.playerFeet().getY() < 0.094) { // lilypads if (ctx.player().getPositionVec().y - ctx.playerFeet().getY() < 0.094) { // lilypads
state.setStatus(MovementStatus.SUCCESS); state.setStatus(MovementStatus.SUCCESS);
} }
} else if (!ctx.playerFeet().equals(src)) { } else if (!ctx.playerFeet().equals(src)) {
if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().posY - src.y > 0.0001) { if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().getPositionVec().y - src.y > 0.0001) {
if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround && MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), true) == PlaceResult.READY_TO_PLACE) { if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround && MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), true) == PlaceResult.READY_TO_PLACE) {
// go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory
state.setInput(Input.CLICK_RIGHT, true); state.setInput(Input.CLICK_RIGHT, true);
} }
// prevent jumping too late by checking for ascend // prevent jumping too late by checking for ascend
if (dist == 3 && !ascend) { // this is a 2 block gap, dest = src + direction * 3 if (dist == 3 && !ascend) { // this is a 2 block gap, dest = src + direction * 3
double xDiff = (src.x + 0.5) - ctx.player().posX; double xDiff = (src.x + 0.5) - ctx.player().getPositionVec().x;
double zDiff = (src.z + 0.5) - ctx.player().posZ; double zDiff = (src.z + 0.5) - ctx.player().getPositionVec().z;
double distFromStart = Math.max(Math.abs(xDiff), Math.abs(zDiff)); double distFromStart = Math.max(Math.abs(xDiff), Math.abs(zDiff));
if (distFromStart < 0.7) { if (distFromStart < 0.7) {
return state; return state;
@@ -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,12 +167,12 @@ 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));
Vec3d destCenter = VecUtils.getBlockPosCenter(dest); Vec3d destCenter = VecUtils.getBlockPosCenter(dest);
if (Math.abs(ctx.player().posX - destCenter.x) > 0.2 || Math.abs(ctx.player().posZ - destCenter.z) > 0.2) { if (Math.abs(ctx.player().getPositionVec().x - destCenter.x) > 0.2 || Math.abs(ctx.player().getPositionVec().z - destCenter.z) > 0.2) {
state.setInput(Input.MOVE_FORWARD, true); state.setInput(Input.MOVE_FORWARD, true);
} }
if (ctx.playerFeet().equals(dest)) { if (ctx.playerFeet().equals(dest)) {
@@ -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);
@@ -220,13 +218,13 @@ public class MovementPillar extends Movement {
} }
state.setInput(Input.SNEAK, ctx.player().posY > dest.getY() || ctx.player().posY < src.getY() + 0.2D); // delay placement by 1 tick for ncp compatibility state.setInput(Input.SNEAK, ctx.player().getPositionVec().y > dest.getY() || ctx.player().getPositionVec().y < src.getY() + 0.2D); // delay placement by 1 tick for ncp compatibility
// since (lower down) we only right click once player.isSneaking, and that happens the tick after we request to sneak // since (lower down) we only right click once player.isSneaking, and that happens the tick after we request to sneak
double diffX = ctx.player().posX - (dest.getX() + 0.5); double diffX = ctx.player().getPositionVec().x - (dest.getX() + 0.5);
double diffZ = ctx.player().posZ - (dest.getZ() + 0.5); double diffZ = ctx.player().getPositionVec().z - (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
@@ -238,22 +236,22 @@ public class MovementPillar extends Movement {
state.setTarget(new MovementState.MovementTarget(rotation, true)); state.setTarget(new MovementState.MovementTarget(rotation, true));
} else if (flatMotion < 0.05) { } else if (flatMotion < 0.05) {
// If our Y coordinate is above our goal, stop jumping // If our Y coordinate is above our goal, stop jumping
state.setInput(Input.JUMP, ctx.player().posY < dest.getY()); state.setInput(Input.JUMP, ctx.player().getPositionVec().y < dest.getY());
} }
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().isCrouching() && (ctx.isLookingAt(src.down()) || ctx.isLookingAt(src)) && ctx.player().getPositionVec().y > 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) {
@@ -177,7 +175,7 @@ public class MovementTraverse extends Movement {
return state; return state;
} }
// and we aren't already pressed up against the block // and we aren't already pressed up against the block
double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); double dist = Math.max(Math.abs(ctx.player().getPositionVec().x - (dest.getX() + 0.5D)), Math.abs(ctx.player().getPositionVec().z - (dest.getZ() + 0.5D)));
if (dist < 0.83) { if (dist < 0.83) {
return state; return state;
} }
@@ -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;
@@ -248,22 +245,22 @@ public class MovementTraverse extends Movement {
} }
Block low = BlockStateInterface.get(ctx, src).getBlock(); Block low = BlockStateInterface.get(ctx, src).getBlock();
Block high = BlockStateInterface.get(ctx, src.up()).getBlock(); Block high = BlockStateInterface.get(ctx, src.up()).getBlock();
if (ctx.player().posY > src.y + 0.1D && !ctx.player().onGround && (low == Blocks.VINE || low == Blocks.LADDER || high == Blocks.VINE || high == Blocks.LADDER)) { if (ctx.player().getPositionVec().y > src.y + 0.1D && !ctx.player().onGround && (low == Blocks.VINE || low == Blocks.LADDER || high == Blocks.VINE || high == Blocks.LADDER)) {
// hitting W could cause us to climb the ladder instead of going forward // hitting W could cause us to climb the ladder instead of going forward
// wait until we're on the ground // wait until we're on the ground
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,22 +271,22 @@ 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().getPositionVec().x), Math.abs(dest.getZ() + 0.5 - ctx.player().getPositionVec().z));
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);
return state.setInput(Input.MOVE_FORWARD, false) return state.setInput(Input.MOVE_FORWARD, false)
.setInput(Input.MOVE_BACK, true); .setInput(Input.MOVE_BACK, true);
} }
} }
double dist1 = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); double dist1 = Math.max(Math.abs(ctx.player().getPositionVec().x - (dest.getX() + 0.5D)), Math.abs(ctx.player().getPositionVec().z - (dest.getZ() + 0.5D)));
PlaceResult p = MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false); PlaceResult p = MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false);
if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.value) { if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.value) {
state.setInput(Input.SNEAK, true); state.setInput(Input.SNEAK, true);
} }
switch (p) { switch (p) {
case READY_TO_PLACE: { case READY_TO_PLACE: {
if (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.value) { if (ctx.player().isCrouching() || Baritone.settings().assumeSafeWalk.value) {
state.setInput(Input.CLICK_RIGHT, true); state.setInput(Input.CLICK_RIGHT, true);
} }
return state; return state;
@@ -322,7 +319,7 @@ public class MovementTraverse extends Movement {
Rotation backToFace = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); Rotation backToFace = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations());
float pitch = backToFace.getPitch(); float pitch = backToFace.getPitch();
double dist2 = Math.max(Math.abs(ctx.player().posX - faceX), Math.abs(ctx.player().posZ - faceZ)); double dist2 = Math.max(Math.abs(ctx.player().getPositionVec().x - faceX), Math.abs(ctx.player().getPositionVec().z - faceZ));
if (dist2 < 0.29) { // see issue #208 if (dist2 < 0.29) { // see issue #208
float yaw = RotationUtils.calcRotationFromVec3d(VecUtils.getBlockPosCenter(dest), ctx.playerHead(), ctx.playerRotations()).getYaw(); float yaw = RotationUtils.calcRotationFromVec3d(VecUtils.getBlockPosCenter(dest), ctx.playerHead(), ctx.playerRotations()).getYaw();
state.setTarget(new MovementState.MovementTarget(new Rotation(yaw, pitch), true)); state.setTarget(new MovementState.MovementTarget(new Rotation(yaw, pitch), true));
@@ -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
@@ -413,7 +414,7 @@ public class PathExecutor implements IPathExecutor, Helper {
// playerFeet adds 0.1251 to account for soul sand // playerFeet adds 0.1251 to account for soul sand
// farmland is 0.9375 // farmland is 0.9375
// 0.07 is to account for farmland // 0.07 is to account for farmland
if (ctx.player().posY >= center.getY() - 0.07) { if (ctx.player().getPositionVec().y >= center.getY() - 0.07) {
behavior.baritone.getInputOverrideHandler().setInputForceState(Input.JUMP, false); behavior.baritone.getInputOverrideHandler().setInputForceState(Input.JUMP, false);
return true; return true;
} }
@@ -484,7 +485,7 @@ public class PathExecutor implements IPathExecutor, Helper {
} }
private static boolean skipNow(IPlayerContext ctx, IMovement current) { private static boolean skipNow(IPlayerContext ctx, IMovement current) {
double offTarget = Math.abs(current.getDirection().getX() * (current.getSrc().z + 0.5D - ctx.player().posZ)) + Math.abs(current.getDirection().getZ() * (current.getSrc().x + 0.5D - ctx.player().posX)); double offTarget = Math.abs(current.getDirection().getX() * (current.getSrc().z + 0.5D - ctx.player().getPositionVec().z)) + Math.abs(current.getDirection().getZ() * (current.getSrc().x + 0.5D - ctx.player().getPositionVec().x));
if (offTarget > 0.1) { if (offTarget > 0.1) {
return false; return false;
} }
@@ -494,7 +495,7 @@ public class PathExecutor implements IPathExecutor, Helper {
return true; return true;
} }
// wait 0.3 // wait 0.3
double flatDist = Math.abs(current.getDirection().getX() * (headBonk.getX() + 0.5D - ctx.player().posX)) + Math.abs(current.getDirection().getZ() * (headBonk.getZ() + 0.5 - ctx.player().posZ)); double flatDist = Math.abs(current.getDirection().getX() * (headBonk.getX() + 0.5D - ctx.player().getPositionVec().x)) + Math.abs(current.getDirection().getZ() * (headBonk.getZ() + 0.5 - ctx.player().getPositionVec().z));
return flatDist > 0.8; return flatDist > 0.8;
} }
@@ -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());
} }
@@ -44,17 +44,18 @@ import baritone.utils.schematic.MapArtSchematic;
import baritone.utils.schematic.SchematicSystem; import baritone.utils.schematic.SchematicSystem;
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;
@@ -77,7 +78,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
private boolean paused; private boolean paused;
private int layer; private int layer;
private int numRepeats; private int numRepeats;
private List<IBlockState> approxPlaceable; private List<BlockState> approxPlaceable;
public BuilderProcess(Baritone baritone) { public BuilderProcess(Baritone baritone) {
super(baritone); super(baritone);
@@ -171,7 +172,7 @@ 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);
} }
@@ -180,15 +181,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;
@@ -206,12 +207,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()) {
@@ -228,10 +229,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;
@@ -239,7 +240,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++) {
@@ -247,13 +248,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);
@@ -268,15 +269,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;
} }
@@ -293,7 +294,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));
@@ -304,10 +305,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;
@@ -316,15 +317,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) {
@@ -340,7 +339,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)};
@@ -388,12 +387,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);
} }
@@ -446,7 +445,7 @@ public final class BuilderProcess extends BaritoneProcessHelper implements IBuil
BetterBlockPos pos = toBreak.get().getA(); BetterBlockPos pos = toBreak.get().getA();
baritone.getLookBehavior().updateTarget(rot, true); baritone.getLookBehavior().updateTarget(rot, true);
MovementHelper.switchToBestToolFor(ctx, bcc.get(pos)); MovementHelper.switchToBestToolFor(ctx, bcc.get(pos));
if (ctx.player().isSneaking()) { if (ctx.player().isCrouching()) {
// really horrible bug where a block is visible for breaking while sneaking but not otherwise // really horrible bug where a block is visible for breaking while sneaking but not otherwise
// so you can't see it, it goes to place something else, sneaks, then the next tick it tries to break // so you can't see it, it goes to place something else, sneaks, then the next tick it tries to break
// and is unable since it's unsneaked in the intermediary tick // and is unable since it's unsneaked in the intermediary tick
@@ -457,14 +456,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);
@@ -472,9 +471,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);
@@ -486,7 +485,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;
@@ -524,7 +523,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;
} }
@@ -539,7 +538,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);
@@ -564,7 +563,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;
} }
@@ -595,18 +594,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)) {
@@ -682,12 +681,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);
@@ -697,7 +696,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) {
@@ -773,36 +772,36 @@ 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().getPositionVec().x, ctx.player().getPositionVec().y, ctx.player().getPositionVec().z), 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) {
return true; return true;
} }
// TODO more complicated comparison logic I guess // TODO more complicated comparison logic I guess
if (desired.getBlock() instanceof BlockAir && Baritone.settings().buildIgnoreBlocks.value.contains(current.getBlock())) { if (desired.getBlock() instanceof AirBlock && Baritone.settings().buildIgnoreBlocks.value.contains(current.getBlock())) {
return true; return true;
} }
if (!(current.getBlock() instanceof BlockAir) && Baritone.settings().buildIgnoreExisting.value) { if (!(current.getBlock() instanceof AirBlock) && Baritone.settings().buildIgnoreExisting.value) {
return true; return true;
} }
return current.equals(desired); return current.equals(desired);
@@ -810,7 +809,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;
@@ -828,7 +827,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 {
@@ -837,14 +836,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
@@ -871,13 +870,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;

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