Compare commits

..

52 Commits

Author SHA1 Message Date
Brady f7041022d0 Merge branch 'master' into 1.13.2 2020-01-10 20:13:57 -06:00
Brady 710170ef2d Fix RelativeGoalXZ coordinate mix-up
Basically for many months now RelativeGoalXZ produced (~X, ~Y), not (~X, ~Z).
2020-01-10 20:10:16 -06:00
Leijurv dd76d2eabc v1.3.6 2020-01-04 21:58:21 -08:00
Leijurv fb22cf05eb v1.2.11 2020-01-04 21:57:16 -08:00
Brady e3d3407de5 Remove normalizations from BlockOptionalMeta 2019-12-31 19:44:44 -06:00
Brady f3d860e8fa Merge branch 'master' into 1.13.2 2019-12-31 19:40:14 -06:00
Brady adff391e45 Merge branch 'schematic-formats' 2019-12-31 18:25:21 -06:00
Brady 4a05837b01 Requested changes 2019-12-31 17:44:20 -06:00
Leijurv 1edd7126fd Merge branch 'master' into 1.13.2 2019-12-31 15:44:03 -08:00
Leijurv a0014fda12 Merge pull request #1216 from FTC55/master
Fixed a rather obnoxious bug that would require a full restart of the client.
2019-12-31 15:35:01 -08:00
FTC55 04190af340 ...more than I thought. Autoreformatted file x2 2019-12-31 19:45:08 +01:00
FTC55 4b10904b97 Git missed some changes. Autoreformatted files. 2019-12-31 19:43:54 +01:00
FTC55 bbb25acff3 Fixed the bug, merged CancelCommand into ExecutionControlCommands 2019-12-31 19:31:30 +01:00
Brady fcfa022232 Clean up BlockOptionalMeta comment and add behavioral clarification 2019-12-30 02:27:20 -06:00
Brady 220ee30d35 Appease Codacy 2019-12-27 21:28:05 -06:00
Brady 812bc0d8c4 Remove redundant parser layer 2019-12-27 01:14:31 -06:00
Brady d712839c25 Make Schematica respect mapArtMode setting 2019-12-25 01:35:10 -06:00
Brady eee705b371 Schematic Format API support 2019-12-24 17:20:00 -06:00
Brady 77bdf6e444 Fix MapSchematic 2019-12-23 18:05:50 -06:00
Brady 0a858c040c Working 2019-12-19 22:15:14 -06:00
Brady eea5b69b6c Utilize new FillSchematic 2019-12-19 12:03:02 -06:00
Brady 6759917a2f Additional clean up 2019-12-19 11:58:47 -06:00
Brady aa3bd80ab2 Clean ups 2019-12-19 11:40:38 -06:00
Brady ea8d7fb3b9 Improve file extension fallback mechanism 2019-12-18 15:19:58 -06:00
Brady b4ddf38116 Check if state is null 2019-12-18 10:27:34 -06:00
Brady 5c9f028103 Initial sponge support 2019-12-18 10:24:43 -06:00
Leijurv 937d4cc884 whoops 2019-12-13 20:46:12 -08:00
Leijurv 2c3e1f4232 builder stuff, fixes #1059 2019-12-13 20:09:04 -08:00
Leijurv ddc681fe77 build repeat count 2019-11-24 11:11:28 -08:00
Leijurv 2b71b31cfa Merge pull request #1087 from cabaletta/ispassable-crash-fix
Fix isPassable crash
2019-11-10 22:52:29 -08:00
Leijurv ed144e995b apparently this usage of > was an invalid javadoc command lol 2019-11-10 14:04:27 -08:00
Brady 7e3a2d3c0a Create a BlockStateInterface specialized IBlockAccess wrapper 2019-11-05 18:17:10 -06:00
Leijurv 152285043d Update USAGE.md 2019-11-05 11:50:27 -08:00
Leijurv ce52201e45 Merge pull request #1097 from greg904/fix-goto-errmsg
Remove error message when running goto with less than 3 args
2019-10-29 21:33:27 -07:00
Leijurv 45ea776090 Update README.md 2019-10-28 10:47:20 -07:00
Leijurv 2ae16d8bb1 configurable block reach distance 2019-10-26 16:01:08 -07:00
Greg Depoire--Ferrer 23fc6c8b49 Add a space between sentences in error message 2019-10-25 14:49:57 +02:00
Greg Depoire--Ferrer 0db4b193e1 Remove hack, add comment, don't use default when arg is required 2019-10-25 14:49:08 +02:00
Greg Depoire--Ferrer 82d520d808 Don't print invalid type error to stderr 2019-10-25 14:42:36 +02:00
Brady 5201d39adf Retain old method signature 2019-10-24 15:20:23 -05:00
Brady f02c33d95a Fix improper tick count incrementation 2019-10-23 17:47:20 -05:00
Brady 43ab4f7d3b Fix isPassable crash 2019-10-22 15:58:10 -05:00
Leijurv a57668bd15 Merge pull request #1073 from 0-x-2-2/1.13.2
Merged master into 1.13.2 branch. 😎
2019-10-17 13:54:06 -07:00
0x22 a324b58f55 Merged master into 1.13.2 branch. 😎 2019-10-17 16:01:35 -04:00
Leijurv 6341f9fcb4 Merge pull request #1072 from 0-x-2-2/disable-autotest-mob-spawning
Disable harmful mob spawning in Travis auto test.
2019-10-17 12:05:24 -07:00
0x22 66ffd1e0d9 Disable harmful mob spawning in Travis auto test. 2019-10-17 14:35:28 -04:00
Leijurv e65c854e6a Update USAGE.md 2019-10-15 11:25:35 -07:00
Brady 4eca960a4c Specify range in IWorldScanner#repack 2019-10-14 15:45:41 -05:00
Leijurv 69bceb43f8 Update USAGE.md 2019-10-12 13:07:12 -07:00
Leijurv 6a8807b0fa documentation stuff 2019-10-12 10:43:01 -07:00
Leijurv 105c7d438a v1.3.5 2019-10-11 17:29:27 -07:00
Leijurv e49549117b v1.2.10 2019-10-11 17:08:28 -07:00
150 changed files with 2574 additions and 1818 deletions
+1 -1
View File
@@ -19,7 +19,7 @@
![Lines of Code](https://tokei.rs/b1/github/cabaletta/baritone?category=code) ![Lines of Code](https://tokei.rs/b1/github/cabaletta/baritone?category=code)
[![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/) [![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/)
[![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/) [![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/)
[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.8%20/%20v1.3.4%20/%20v1.4.1-brightgreen.svg)](https://impactclient.net/) [![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.10%20/%20v1.3.5%20/%20v1.4.3-brightgreen.svg)](https://impactclient.net/)
[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/)
[![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%20integration-v1.3.4%20/%20v1.4.1-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api) [![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%20integration-v1.3.4%20/%20v1.4.1-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api)
[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/)
+13 -7
View File
@@ -8,11 +8,23 @@ Baritone commands can also by default be typed in the chatbox. However if you ma
To disable direct chat control (with no prefix), turn off the `chatControl` setting. To disable chat control with the `#` prefix, turn off the `prefixControl` setting. In Impact, `.b` cannot be disabled. Be careful that you don't leave yourself with all control methods disabled (if you do, reset your settings by deleting the file `minecraft/baritone/settings.txt` and relaunching). To disable direct chat control (with no prefix), turn off the `chatControl` setting. To disable chat control with the `#` prefix, turn off the `prefixControl` setting. In Impact, `.b` cannot be disabled. Be careful that you don't leave yourself with all control methods disabled (if you do, reset your settings by deleting the file `minecraft/baritone/settings.txt` and relaunching).
# For Baritone 1.2.10+, 1.3.5+, 1.4.2+
Lots of the commands have changed, BUT `#help` is improved vastly (its clickable! commands have tab completion! oh my!).
Try `#help` I promise it won't just send you back here =)
"wtf where is cleararea" -> look at `#help sel`
"wtf where is goto death, goto waypoint" -> look at `#help wp` (a "tag" is like "home" (created automatically on right clicking a bed) or "death" (created automatically on death) or "user" (has to be created manually)). So you might want `#wp save user coolbiome` then, to set the goal `#wp goal coolbiome` then `#path` to path to it. For death, `#wp goal death` (remember stuff is clickable!).
just look at `#help` lmao
# Commands # Commands
**All** of these commands may need a prefix before them, as above ^. **All** of these commands may need a prefix before them, as above ^.
`help` for (rudimentary) help. You can see what it says [here](https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/utils/ExampleBaritoneControl.java#L47). `help`
To toggle a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `primaryTimeoutMS 250`). It's case insensitive. To reset a setting to its default value, say `acceptableThrowawayItems reset`. To reset all settings, say `reset`. To see all settings that have been modified from their default values, say `modified`. To toggle a boolean setting, just say its name in chat (for example saying `allowBreak` toggles whether Baritone will consider breaking blocks). For a numeric setting, say its name then the new value (like `primaryTimeoutMS 250`). It's case insensitive. To reset a setting to its default value, say `acceptableThrowawayItems reset`. To reset all settings, say `reset`. To see all settings that have been modified from their default values, say `modified`.
@@ -38,12 +50,6 @@ Some common examples:
- `version` to get the version of Baritone you're running - `version` to get the version of Baritone you're running
- `damn` daniel - `damn` daniel
New commands:
- `sel` to manage selections
- some others
For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/utils/ExampleBaritoneControl.java). For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/utils/ExampleBaritoneControl.java).
All the settings and documentation are <a href="https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/Settings.java">here</a>. If you find HTML easier to read than Javadoc, you can look <a href="https://baritone.leijurv.com/baritone/api/Settings.html#field.detail">here</a>. All the settings and documentation are <a href="https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/Settings.java">here</a>. If you find HTML easier to read than Javadoc, you can look <a href="https://baritone.leijurv.com/baritone/api/Settings.html#field.detail">here</a>.
+4 -4
View File
@@ -16,11 +16,10 @@
*/ */
group 'baritone' group 'baritone'
version '1.4.2' version '1.3.6'
buildscript { buildscript {
repositories { repositories {
jcenter()
maven { maven {
name = 'forge' name = 'forge'
url = 'http://files.minecraftforge.net/maven' url = 'http://files.minecraftforge.net/maven'
@@ -29,6 +28,7 @@ buildscript {
name = 'impactdevelopment-repo' name = 'impactdevelopment-repo'
url = 'https://impactdevelopment.github.io/maven/' url = 'https://impactdevelopment.github.io/maven/'
} }
jcenter()
} }
dependencies { dependencies {
@@ -82,7 +82,7 @@ task sourceJar(type: Jar, dependsOn: classes) {
} }
minecraft { minecraft {
mappings channel: 'snapshot', version: '20190814-1.14.3' mappings channel: 'snapshot', version: '20190307-1.13.1'
reobfMappings 'notch' reobfMappings 'notch'
runs { runs {
@@ -138,7 +138,7 @@ repositories {
} }
dependencies { dependencies {
minecraft 'com.github.ImpactDevelopment:Vanilla:1.14.4' minecraft 'com.github.ImpactDevelopment:Vanilla:1.13.2'
runtime launchCompile('net.minecraft:launchwrapper:1.12') { runtime launchCompile('net.minecraft:launchwrapper:1.12') {
exclude module: 'lwjgl' exclude module: 'lwjgl'
@@ -20,7 +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 net.minecraft.client.entity.EntityPlayerSP;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -46,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(ClientPlayerEntity) * @see #getBaritoneForPlayer(EntityPlayerSP)
*/ */
List<IBaritone> getAllBaritones(); List<IBaritone> getAllBaritones();
/** /**
* Provides the {@link IBaritone} instance for a given {@link ClientPlayerEntity}. This will likely be * Provides the {@link IBaritone} instance for a given {@link EntityPlayerSP}. 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(ClientPlayerEntity player) { default IBaritone getBaritoneForPlayer(EntityPlayerSP 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;
@@ -82,4 +83,9 @@ public interface IBaritoneProvider {
* @return The {@link ICommandSystem} instance. * @return The {@link ICommandSystem} instance.
*/ */
ICommandSystem getCommandSystem(); ICommandSystem getCommandSystem();
/**
* @return The {@link ISchematicSystem} instance.
*/
ISchematicSystem getSchematicSystem();
} }
+35 -3
View File
@@ -20,8 +20,8 @@ package baritone.api;
import baritone.api.utils.SettingsUtil; import baritone.api.utils.SettingsUtil;
import baritone.api.utils.TypeUtils; import baritone.api.utils.TypeUtils;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
@@ -178,9 +178,25 @@ 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
))); )));
/**
* A list of blocks to be treated as if they're air.
* <p>
* If a schematic asks for air at a certain position, and that position currently contains a block on this list, it will be treated as correct.
*/
public final Setting<List<Block>> buildIgnoreBlocks = new Setting<>(new ArrayList<>(Arrays.asList(
)));
/**
* If this is true, the builder will treat all non-air blocks as correct. It will only place new blocks.
*/
public final Setting<Boolean> buildIgnoreExisting = new Setting<>(false);
/** /**
* If this setting is true, Baritone will never break a block that is adjacent to an unsupported falling block. * If this setting is true, Baritone will never break a block that is adjacent to an unsupported falling block.
* <p> * <p>
@@ -231,7 +247,7 @@ public final class Settings {
/** /**
* If we overshoot a traverse and end up one block beyond the destination, mark it as successful anyway. * If we overshoot a traverse and end up one block beyond the destination, mark it as successful anyway.
* <p> * <p>
* This helps with speed at >=20m/s * This helps with speed exceeding 20m/s
*/ */
public final Setting<Boolean> overshootTraverse = new Setting<>(true); public final Setting<Boolean> overshootTraverse = new Setting<>(true);
@@ -250,6 +266,11 @@ public final class Settings {
*/ */
public final Setting<Double> randomLooking113 = new Setting<>(2d); public final Setting<Double> randomLooking113 = new Setting<>(2d);
/**
* Block reach distance
*/
public final Setting<Float> blockReachDistance = new Setting<>(4.5f);
/** /**
* How many degrees to randomize the pitch and yaw every tick. Set to 0 to disable * How many degrees to randomize the pitch and yaw every tick. Set to 0 to disable
*/ */
@@ -740,6 +761,11 @@ public final class Settings {
*/ */
public final Setting<Vec3i> buildRepeat = new Setting<>(new Vec3i(0, 0, 0)); public final Setting<Vec3i> buildRepeat = new Setting<>(new Vec3i(0, 0, 0));
/**
* How many times to buildrepeat. -1 for infinite.
*/
public final Setting<Integer> buildRepeatCount = new Setting<>(-1);
/** /**
* Allow standing above a block while mining it, in BuilderProcess * Allow standing above a block while mining it, in BuilderProcess
* <p> * <p>
@@ -789,6 +815,12 @@ public final class Settings {
*/ */
public final Setting<Boolean> schematicOrientationZ = new Setting<>(false); public final Setting<Boolean> schematicOrientationZ = new Setting<>(false);
/**
* The fallback used by the build command when no extension is specified. This may be useful if schematics of a
* particular format are used often, and the user does not wish to have to specify the extension with every usage.
*/
public final Setting<String> schematicFallbackExtension = new Setting<>("schematic");
/** /**
* Distance to scan every tick for updates. Expanding this beyond player reach distance (i.e. setting it to 6 or above) * Distance to scan every tick for updates. Expanding this beyond player reach distance (i.e. setting it to 6 or above)
* is only necessary in very large schematics where rescanning the whole thing is costly. * is only necessary in very large schematics where rescanning the whole thing is costly.
+3 -3
View File
@@ -17,7 +17,7 @@
package baritone.api.cache; package baritone.api.cache;
import net.minecraft.block.BlockState; import net.minecraft.block.state.IBlockState;
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 {
BlockState getBlock(int x, int y, int z); IBlockState getBlock(int x, int y, int z);
default BlockState getBlock(BlockPos pos) { default IBlockState getBlock(BlockPos pos) {
return getBlock(pos.getX(), pos.getY(), pos.getZ()); return getBlock(pos.getX(), pos.getY(), pos.getZ());
} }
} }
-2
View File
@@ -81,6 +81,4 @@ public interface ICachedWorld {
* in a new thread by default. * in a new thread by default.
*/ */
void save(); void save();
} }
+13 -3
View File
@@ -77,10 +77,20 @@ public interface IWorldScanner {
} }
/** /**
* Repacks 40 chunks around the player. * Overload of {@link #repack(IPlayerContext, int)} where the value of the {@code range} parameter is {@code 40}.
* *
* @param ctx The player context for that player. * @param ctx The player, describing the origin
* @return The number of chunks queued for repacking. * @return The amount of chunks successfully queued for repacking
*/ */
int repack(IPlayerContext ctx); int repack(IPlayerContext ctx);
/**
* Queues the chunks in a square formation around the specified player, using the specified
* range, which represents 1/2 the square's dimensions, where the player is in the center.
*
* @param ctx The player, describing the origin
* @param range The range to repack
* @return The amount of chunks successfully queued for repacking
*/
int repack(IPlayerContext ctx, int range);
} }
@@ -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.Direction; import net.minecraft.util.EnumFacing;
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 Direction}, and the next argument's value is "up", this will return * For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return
* {@link Direction#UP} * {@link EnumFacing#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 Direction}, and the next argument's value is "up", this will return * For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return
* {@link Direction#UP} * {@link EnumFacing#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 Direction}, and the next argument's value is "up", this will return * For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return
* {@link Direction#UP} * {@link EnumFacing#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.Direction; import net.minecraft.util.EnumFacing;
/** /**
* 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 Direction}, and this argument's value is "up", it will return {@link * For example if you getEnum as an {@link EnumFacing}, and this argument's value is "up", it will return {@link
* Direction#UP} * EnumFacing#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,11 +17,12 @@
package baritone.api.command.datatypes; package baritone.api.command.datatypes;
import baritone.api.command.exception.CommandException;
import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.command.exception.CommandException;
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.Registry; import net.minecraft.util.registry.IRegistry;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -32,7 +33,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 = Registry.BLOCK.getValue(id).orElse(null)) == null) { if ((block = IRegistry.BLOCK.get(id)) == Blocks.AIR) {
throw new IllegalArgumentException("no block found by that id"); throw new IllegalArgumentException("no block found by that id");
} }
return block; return block;
@@ -42,7 +43,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(
Registry.BLOCK.keySet() IRegistry.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.Registry; import net.minecraft.util.registry.IRegistry;
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 = Registry.ENTITY_TYPE.getValue(id).orElse(null)) == null) { if ((entity = IRegistry.ENTITY_TYPE.get(id)) == 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(Registry.ENTITY_TYPE.stream().map(Object::toString)) .append(IRegistry.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.Direction; import net.minecraft.util.EnumFacing;
import java.util.Locale; import java.util.Locale;
import java.util.stream.Stream; import java.util.stream.Stream;
public enum ForDirection implements IDatatypeFor<Direction> { public enum ForEnumFacing implements IDatatypeFor<EnumFacing> {
INSTANCE; INSTANCE;
@Override @Override
public Direction get(IDatatypeContext ctx) throws CommandException { public EnumFacing get(IDatatypeContext ctx) throws CommandException {
return Direction.valueOf(ctx.getConsumer().getString().toUpperCase(Locale.US)); return EnumFacing.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(Direction.values()) .append(Stream.of(EnumFacing.values())
.map(Direction::getName).map(String::toLowerCase)) .map(EnumFacing::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.PlayerEntity; import net.minecraft.entity.player.EntityPlayer;
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<PlayerEntity> { public enum NearbyPlayer implements IDatatypeFor<EntityPlayer> {
INSTANCE; INSTANCE;
@Override @Override
public PlayerEntity get(IDatatypeContext ctx) throws CommandException { public EntityPlayer 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<PlayerEntity> {
@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(PlayerEntity::getName).map(ITextComponent::getString)) .append(getPlayers(ctx).stream().map(EntityPlayer::getName).map(ITextComponent::getString))
.filterPrefix(ctx.getConsumer().getString()) .filterPrefix(ctx.getConsumer().getString())
.sortAlphabetically() .sortAlphabetically()
.stream(); .stream();
} }
private static List<? extends PlayerEntity> getPlayers(IDatatypeContext ctx) { private static List<EntityPlayer> getPlayers(IDatatypeContext ctx) {
return ctx.getBaritone().getPlayerContext().world().getPlayers(); return ctx.getBaritone().getPlayerContext().world().playerEntities;
} }
} }
@@ -38,38 +38,26 @@ public enum RelativeGoal implements IDatatypePost<Goal, BetterBlockPos> {
if (origin == null) { if (origin == null) {
origin = BetterBlockPos.ORIGIN; origin = BetterBlockPos.ORIGIN;
} }
final IArgConsumer consumer = ctx.getConsumer(); final IArgConsumer consumer = ctx.getConsumer();
List<IDatatypePostFunction<Double, Double>> coords = new ArrayList<>(); GoalBlock goalBlock = consumer.peekDatatypePostOrNull(RelativeGoalBlock.INSTANCE, origin);
final IArgConsumer copy = consumer.copy(); // This is a hack and should be fixed in the future probably if (goalBlock != null) {
for (int i = 0; i < 3; i++) { return goalBlock;
if (copy.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) != null) {
coords.add(o -> consumer.getDatatypePost(RelativeCoordinate.INSTANCE, o));
copy.get(); // Consume so we actually decrement the remaining arguments
}
} }
switch (coords.size()) { GoalXZ goalXZ = consumer.peekDatatypePostOrNull(RelativeGoalXZ.INSTANCE, origin);
case 0: if (goalXZ != null) {
return new GoalBlock(origin); return goalXZ;
case 1:
return new GoalYLevel(
MathHelper.floor(coords.get(0).apply((double) origin.y))
);
case 2:
return new GoalXZ(
MathHelper.floor(coords.get(0).apply((double) origin.x)),
MathHelper.floor(coords.get(1).apply((double) origin.z))
);
case 3:
return new GoalBlock(
MathHelper.floor(coords.get(0).apply((double) origin.x)),
MathHelper.floor(coords.get(1).apply((double) origin.y)),
MathHelper.floor(coords.get(2).apply((double) origin.z))
);
default:
throw new IllegalStateException("Unexpected coords size: " + coords.size());
} }
GoalYLevel goalYLevel = consumer.peekDatatypePostOrNull(RelativeGoalYLevel.INSTANCE, origin);
if (goalYLevel != null) {
return goalYLevel;
}
// when the user doesn't input anything, default to the origin
return new GoalBlock(origin);
} }
@Override @Override
@@ -37,7 +37,7 @@ public enum RelativeGoalXZ implements IDatatypePost<GoalXZ, BetterBlockPos> {
final IArgConsumer consumer = ctx.getConsumer(); final IArgConsumer consumer = ctx.getConsumer();
return new GoalXZ( return new GoalXZ(
MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x)), MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x)),
MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y)) MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.z))
); );
} }
@@ -22,4 +22,8 @@ public abstract class CommandErrorMessageException extends CommandException {
protected CommandErrorMessageException(String reason) { protected CommandErrorMessageException(String reason) {
super(reason); super(reason);
} }
protected CommandErrorMessageException(String reason, Throwable cause) {
super(reason, cause);
}
} }
@@ -22,4 +22,8 @@ public abstract class CommandException extends Exception implements ICommandExce
protected CommandException(String reason) { protected CommandException(String reason) {
super(reason); super(reason);
} }
protected CommandException(String reason, Throwable cause) {
super(reason, cause);
}
} }
@@ -23,12 +23,21 @@ public abstract class CommandInvalidArgumentException extends CommandErrorMessag
public final ICommandArgument arg; public final ICommandArgument arg;
protected CommandInvalidArgumentException(ICommandArgument arg, String reason) { protected CommandInvalidArgumentException(ICommandArgument arg, String message) {
super(String.format( super(formatMessage(arg, message));
"Error at argument #%s: %s",
arg.getIndex() == -1 ? "<unknown>" : Integer.toString(arg.getIndex() + 1),
reason
));
this.arg = arg; this.arg = arg;
} }
protected CommandInvalidArgumentException(ICommandArgument arg, String message, Throwable cause) {
super(formatMessage(arg, message), cause);
this.arg = arg;
}
private static String formatMessage(ICommandArgument arg, String message) {
return String.format(
"Error at argument #%s: %s",
arg.getIndex() == -1 ? "<unknown>" : Integer.toString(arg.getIndex() + 1),
message
);
}
} }
@@ -26,7 +26,7 @@ public class CommandInvalidTypeException extends CommandInvalidArgumentException
} }
public CommandInvalidTypeException(ICommandArgument arg, String expected, Throwable cause) { public CommandInvalidTypeException(ICommandArgument arg, String expected, Throwable cause) {
super(arg, String.format("Expected %s.\nMore details: %s", expected, cause.getMessage())); super(arg, String.format("Expected %s", expected), cause);
} }
public CommandInvalidTypeException(ICommandArgument arg, String expected, String got) { public CommandInvalidTypeException(ICommandArgument arg, String expected, String got) {
@@ -34,6 +34,6 @@ public class CommandInvalidTypeException extends CommandInvalidArgumentException
} }
public CommandInvalidTypeException(ICommandArgument arg, String expected, String got, Throwable cause) { public CommandInvalidTypeException(ICommandArgument arg, String expected, String got, Throwable cause) {
super(arg, String.format("Expected %s, but got %s instead.\nMore details: %s", expected, got, cause.getMessage())); super(arg, String.format("Expected %s, but got %s instead", expected, got), cause);
} }
} }
@@ -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.StringTextComponent; import net.minecraft.util.text.TextComponentString;
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 StringTextComponent("<<"); ITextComponent prevPageComponent = new TextComponentString("<<");
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 StringTextComponent("Click to view previous page") new TextComponentString("Click to view previous page")
)); ));
} else { } else {
prevPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY); prevPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
} }
ITextComponent nextPageComponent = new StringTextComponent(">>"); ITextComponent nextPageComponent = new TextComponentString(">>");
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 StringTextComponent("Click to view next page") new TextComponentString("Click to view next page")
)); ));
} else { } else {
nextPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY); nextPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
} }
ITextComponent pagerComponent = new StringTextComponent(""); ITextComponent pagerComponent = new TextComponentString("");
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.IPacket; import net.minecraft.network.Packet;
/** /**
* @author Brady * @author Brady
@@ -31,9 +31,9 @@ public final class PacketEvent {
private final EventState state; private final EventState state;
private final IPacket<?> packet; private final Packet<?> packet;
public PacketEvent(NetworkManager networkManager, EventState state, IPacket<?> packet) { public PacketEvent(NetworkManager networkManager, EventState state, Packet<?> 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 IPacket<?> getPacket() { public final Packet<?> getPacket() {
return this.packet; return this.packet;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public final <T extends IPacket<?>> T cast() { public final <T extends Packet<?>> T cast() {
return (T) this.packet; return (T) this.packet;
} }
} }
@@ -18,6 +18,7 @@
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
@@ -75,7 +76,7 @@ public final class RotationMoveEvent {
/** /**
* Called when the player jumps. * Called when the player jumps.
* *
* @see LivingEntity#jump * @see EntityLivingBase#jump
*/ */
JUMP JUMP
} }
@@ -19,22 +19,20 @@ package baritone.api.event.events;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import java.util.function.BiFunction;
public final class TickEvent { public final class TickEvent {
private static int overallTickCount;
private final EventState state; private final EventState state;
private final Type type; private final Type type;
private final int count; private final int count;
private static int overallTickCount; public TickEvent(EventState state, Type type, int count) {
public TickEvent(EventState state, Type type) {
this.state = state; this.state = state;
this.type = type; this.type = type;
this.count = incrementCount(); this.count = count;
}
private static synchronized int incrementCount() {
return overallTickCount++;
} }
public int getCount() { public int getCount() {
@@ -49,6 +47,10 @@ public final class TickEvent {
return state; return state;
} }
public static synchronized BiFunction<EventState, Type, TickEvent> createNextProvider() {
final int count = overallTickCount++;
return (state, type) -> new TickEvent(state, type, count);
}
public enum Type { public enum Type {
/** /**
@@ -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.world.ClientWorld; import net.minecraft.client.multiplayer.WorldClient;
/** /**
* @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 ClientWorld world; private final WorldClient world;
/** /**
* The state of the event * The state of the event
*/ */
private final EventState state; private final EventState state;
public WorldEvent(ClientWorld world, EventState state) { public WorldEvent(WorldClient 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 ClientWorld getWorld() { public final WorldClient getWorld() {
return this.world; return this.world;
} }
@@ -19,11 +19,12 @@ 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.player.ClientPlayerEntity; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.screen.DeathScreen; 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;
/** /**
* @author Brady * @author Brady
@@ -43,7 +44,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 ClientPlayerEntity#tick() * @see EntityPlayerSP#tick()
*/ */
void onPlayerUpdate(PlayerUpdateEvent event); void onPlayerUpdate(PlayerUpdateEvent event);
@@ -51,7 +52,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 ClientPlayerEntity#sendChatMessage(String) * @see EntityPlayerSP#sendChatMessage(String)
*/ */
void onSendChatMessage(ChatEvent event); void onSendChatMessage(ChatEvent event);
@@ -80,7 +81,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(ClientWorld, Screen) * @see Minecraft#loadWorld(WorldClient, GuiScreen)
*/ */
void onWorldEvent(WorldEvent event); void onWorldEvent(WorldEvent event);
@@ -110,10 +111,10 @@ public interface IGameEventListener {
void onPlayerRotationMove(RotationMoveEvent event); void onPlayerRotationMove(RotationMoveEvent event);
/** /**
* Called whenever the sprint keybind state is checked in {@link ClientPlayerEntity#livingTick} * Called whenever the sprint keybind state is checked in {@link EntityPlayerSP#livingTick}
* *
* @param event The event * @param event The event
* @see ClientPlayerEntity#livingTick() * @see EntityPlayerSP#livingTick()
*/ */
void onPlayerSprintState(SprintStateEvent event); void onPlayerSprintState(SprintStateEvent event);
@@ -18,7 +18,7 @@
package baritone.api.pathing.goals; package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil; import baritone.api.utils.SettingsUtil;
import net.minecraft.util.Direction; import net.minecraft.util.EnumFacing;
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, Direction direction) { public GoalStrictDirection(BlockPos origin, EnumFacing 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.BlockState; import net.minecraft.block.state.IBlockState;
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<BlockState> getApproxPlaceable(); List<IBlockState> getApproxPlaceable();
} }
@@ -23,6 +23,10 @@ public abstract class AbstractSchematic implements ISchematic {
protected int y; protected int y;
protected int z; protected int z;
public AbstractSchematic() {
this(0, 0, 0);
}
public AbstractSchematic(int x, int y, int z) { public AbstractSchematic(int x, int y, int z) {
this.x = x; this.x = x;
this.y = y; this.y = y;
@@ -17,7 +17,7 @@
package baritone.api.schematic; package baritone.api.schematic;
import net.minecraft.block.BlockState; import net.minecraft.block.state.IBlockState;
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, BlockState currentState) { private CompositeSchematicEntry getSchematic(int x, int y, int z, IBlockState 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, BlockState currentState) { public boolean inSchematic(int x, int y, int z, IBlockState 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 BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) { public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> 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.BlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.block.Blocks; import net.minecraft.init.Blocks;
import java.util.List; import java.util.List;
@@ -32,18 +32,22 @@ public class FillSchematic extends AbstractSchematic {
this.bom = bom; this.bom = bom;
} }
public FillSchematic(int x, int y, int z, IBlockState state) {
this(x, y, z, new BlockOptionalMeta(state.getBlock()));
}
public BlockOptionalMeta getBom() { public BlockOptionalMeta getBom() {
return bom; return bom;
} }
@Override @Override
public BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) { public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> 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 (BlockState placeable : approxPlaceable) { for (IBlockState 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.BlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.util.Direction; import net.minecraft.util.EnumFacing;
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, BlockState currentState) { default boolean inSchematic(int x, int y, int z, IBlockState 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(Direction.Axis axis) { default int size(EnumFacing.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
*/ */
BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable); IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable);
/** /**
* @return The width (X axis length) of this schematic * @return The width (X axis length) of this schematic
@@ -0,0 +1,44 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.schematic;
import baritone.api.command.registry.Registry;
import baritone.api.schematic.format.ISchematicFormat;
import java.io.File;
import java.util.Optional;
/**
* @author Brady
* @since 12/23/2019
*/
public interface ISchematicSystem {
/**
* @return The registry of supported schematic formats
*/
Registry<ISchematicFormat> getRegistry();
/**
* Attempts to find an {@link ISchematicFormat} that supports the specified schematic file.
*
* @param file A schematic file
* @return The corresponding format for the file, {@link Optional#empty()} if no candidates were found.
*/
Optional<ISchematicFormat> getByFile(File file);
}
@@ -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.api.schematic;
import net.minecraft.block.state.IBlockState;
/**
* A static schematic is capable of providing the desired state at a given position without
* additional context. Schematics of this type are expected to have non-varying contents.
*
* @see #getDirect(int, int, int)
*
* @author Brady
* @since 12/24/2019
*/
public interface IStaticSchematic extends ISchematic {
/**
* Gets the {@link IBlockState} 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.
*
* @param x The X block position
* @param y The Y block position
* @param z The Z block position
* @return The desired state at the specified position.
*/
IBlockState getDirect(int x, int y, int z);
/**
* Returns an {@link IBlockState} array of size {@link #heightY()} which contains all
* desired block states in the specified vertical column. The index of {@link IBlockState}s
* in the array are equivalent to their Y position in the schematic.
*
* @param x The X column position
* @param z The Z column position
* @return An {@link IBlockState} array
*/
default IBlockState[] getColumn(int x, int z) {
IBlockState[] column = new IBlockState[this.heightY()];
for (int i = 0; i < this.heightY(); i++) {
column[i] = getDirect(x, i, z);
}
return column;
}
}
@@ -17,7 +17,7 @@
package baritone.api.schematic; package baritone.api.schematic;
import net.minecraft.block.BlockState; import net.minecraft.block.state.IBlockState;
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, BlockState currentState); protected abstract boolean partOfMask(int x, int y, int z, IBlockState currentState);
@Override @Override
public boolean inSchematic(int x, int y, int z, BlockState currentState) { public boolean inSchematic(int x, int y, int z, IBlockState 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 BlockState desiredState(int x, int y, int z, BlockState current, List<BlockState> approxPlaceable) { public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> 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.BlockState; import net.minecraft.block.state.IBlockState;
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, BlockState currentState) { protected boolean partOfMask(int x, int y, int z, IBlockState 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.BlockState; import net.minecraft.block.state.IBlockState;
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, BlockState currentState) { protected boolean partOfMask(int x, int y, int z, IBlockState 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.BlockState; import net.minecraft.block.state.IBlockState;
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, BlockState currentState) { protected boolean partOfMask(int x, int y, int z, IBlockState currentState) {
return x == 0 || z == 0 || x == widthX() - 1 || z == lengthZ() - 1; return x == 0 || z == 0 || x == widthX() - 1 || z == lengthZ() - 1;
} }
} }
@@ -0,0 +1,45 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.schematic.format;
import baritone.api.schematic.ISchematic;
import baritone.api.schematic.IStaticSchematic;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
/**
* The base of a {@link ISchematic} file format
*
* @author Brady
* @since 12/23/2019
*/
public interface ISchematicFormat {
/**
* @return The parser for creating schematics of this format
*/
IStaticSchematic parse(InputStream input) throws IOException;
/**
* @param file The file to check against
* @return Whether or not the specified file matches this schematic format
*/
boolean isFileType(File file);
}
@@ -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.Direction; import net.minecraft.util.EnumFacing;
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(Direction direction, int blocks); ISelection expand(EnumFacing 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(Direction direction, int blocks); ISelection contract(EnumFacing 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(Direction direction, int blocks); ISelection shift(EnumFacing 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.Direction; import net.minecraft.util.EnumFacing;
/** /**
* 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, Direction direction, int blocks); ISelection expand(ISelection selection, EnumFacing 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, Direction direction, int blocks); ISelection contract(ISelection selection, EnumFacing 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, Direction direction, int blocks); ISelection shift(ISelection selection, EnumFacing direction, int blocks);
} }
@@ -17,7 +17,7 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.util.Direction; import net.minecraft.util.EnumFacing;
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(Direction.UP, 1) // which calls this.offset(EnumFacing.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(Direction, int), new BlockPos, getX, getXOffset, getY, getYOffset, getZ, getZOffset // how many function calls is that? up(), up(int), offset(EnumFacing, 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(Direction dir) { public BetterBlockPos offset(EnumFacing 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(Direction dir, int dist) { public BetterBlockPos offset(EnumFacing dir, int dist) {
if (dist == 0) { if (dist == 0) {
return this; return this;
} }
@@ -19,40 +19,29 @@ package baritone.api.utils;
import baritone.api.utils.accessor.IItemStack; import baritone.api.utils.accessor.IItemStack;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import io.netty.util.concurrent.ThreadPerTaskExecutor;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.client.Minecraft; import net.minecraft.block.state.IBlockState;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.resources.*;
import net.minecraft.state.IProperty; import net.minecraft.state.IProperty;
import net.minecraft.state.properties.*; import net.minecraft.state.properties.*;
import net.minecraft.util.Direction; import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Unit; import net.minecraft.util.registry.IRegistry;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.storage.loot.*;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.regex.MatchResult; import java.util.regex.MatchResult;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
public final class BlockOptionalMeta { public final class BlockOptionalMeta {
private final Block block; private final Block block;
private final Set<BlockState> blockstates; private final Set<IBlockState> blockstates;
private final ImmutableSet<Integer> stateHashes; private final ImmutableSet<Integer> stateHashes;
private final ImmutableSet<Integer> stackHashes; private final ImmutableSet<Integer> stackHashes;
private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$"); private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$");
private static final Map<Object, Object> normalizations;
private static LootTableManager manager;
private static Map<Block, List<Item>> drops = new HashMap<>();
public BlockOptionalMeta(@Nonnull Block block) { public BlockOptionalMeta(@Nonnull Block block) {
this.block = block; this.block = block;
@@ -72,172 +61,36 @@ public final class BlockOptionalMeta {
ResourceLocation id = new ResourceLocation(matchResult.group(1)); ResourceLocation id = new ResourceLocation(matchResult.group(1));
if (!Registry.BLOCK.containsKey(id)) { if (!IRegistry.BLOCK.containsKey(id)) {
throw new IllegalArgumentException("Invalid block ID"); throw new IllegalArgumentException("Invalid block ID");
} }
block = Registry.BLOCK.getValue(id).orElse(null); block = IRegistry.BLOCK.get(id);
blockstates = getStates(block); blockstates = getStates(block);
stateHashes = getStateHashes(blockstates); stateHashes = getStateHashes(blockstates);
stackHashes = getStackHashes(blockstates); stackHashes = getStackHashes(blockstates);
} }
static { private static Set<IBlockState> getStates(@Nonnull Block block) {
Map<Object, Object> _normalizations = new HashMap<>();
Consumer<Enum> put = instance -> _normalizations.put(instance.getClass(), instance);
put.accept(Direction.NORTH);
put.accept(Direction.Axis.Y);
put.accept(Half.BOTTOM);
put.accept(StairsShape.STRAIGHT);
put.accept(AttachFace.FLOOR);
put.accept(DoubleBlockHalf.UPPER);
put.accept(SlabType.BOTTOM);
put.accept(DoorHingeSide.LEFT);
put.accept(BedPart.HEAD);
put.accept(RailShape.NORTH_SOUTH);
_normalizations.put(BannerBlock.ROTATION, 0);
_normalizations.put(BedBlock.OCCUPIED, false);
_normalizations.put(BrewingStandBlock.HAS_BOTTLE[0], false);
_normalizations.put(BrewingStandBlock.HAS_BOTTLE[1], false);
_normalizations.put(BrewingStandBlock.HAS_BOTTLE[2], false);
_normalizations.put(AbstractButtonBlock.POWERED, false);
// _normalizations.put(BlockCactus.AGE, 0);
// _normalizations.put(BlockCauldron.LEVEL, 0);
// _normalizations.put(BlockChorusFlower.AGE, 0);
_normalizations.put(ChorusPlantBlock.NORTH, false);
_normalizations.put(ChorusPlantBlock.EAST, false);
_normalizations.put(ChorusPlantBlock.SOUTH, false);
_normalizations.put(ChorusPlantBlock.WEST, false);
_normalizations.put(ChorusPlantBlock.UP, false);
_normalizations.put(ChorusPlantBlock.DOWN, false);
// _normalizations.put(BlockCocoa.AGE, 0);
// _normalizations.put(BlockCrops.AGE, 0);
_normalizations.put(SnowyDirtBlock.SNOWY, false);
_normalizations.put(DoorBlock.OPEN, false);
_normalizations.put(DoorBlock.POWERED, false);
// _normalizations.put(BlockFarmland.MOISTURE, 0);
_normalizations.put(FenceBlock.NORTH, false);
_normalizations.put(FenceBlock.EAST, false);
_normalizations.put(FenceBlock.WEST, false);
_normalizations.put(FenceBlock.SOUTH, false);
// _normalizations.put(BlockFenceGate.POWERED, false);
// _normalizations.put(BlockFenceGate.IN_WALL, false);
_normalizations.put(FireBlock.AGE, 0);
_normalizations.put(FireBlock.NORTH, false);
_normalizations.put(FireBlock.EAST, false);
_normalizations.put(FireBlock.SOUTH, false);
_normalizations.put(FireBlock.WEST, false);
_normalizations.put(FireBlock.UP, false);
// _normalizations.put(BlockFrostedIce.AGE, 0);
_normalizations.put(GrassBlock.SNOWY, false);
// _normalizations.put(BlockHopper.ENABLED, true);
// _normalizations.put(BlockLever.POWERED, false);
// _normalizations.put(BlockLiquid.LEVEL, 0);
// _normalizations.put(BlockMycelium.SNOWY, false);
// _normalizations.put(BlockNetherWart.AGE, false);
_normalizations.put(LeavesBlock.DISTANCE, false);
// _normalizations.put(BlockLeaves.DECAYABLE, false);
// _normalizations.put(BlockObserver.POWERED, false);
_normalizations.put(PaneBlock.NORTH, false);
_normalizations.put(PaneBlock.EAST, false);
_normalizations.put(PaneBlock.WEST, false);
_normalizations.put(PaneBlock.SOUTH, false);
// _normalizations.put(BlockPistonBase.EXTENDED, false);
// _normalizations.put(BlockPressurePlate.POWERED, false);
// _normalizations.put(BlockPressurePlateWeighted.POWER, false);
// _normalizations.put(BlockRailDetector.POWERED, false);
// _normalizations.put(BlockRailPowered.POWERED, false);
_normalizations.put(RedstoneWireBlock.NORTH, false);
_normalizations.put(RedstoneWireBlock.EAST, false);
_normalizations.put(RedstoneWireBlock.SOUTH, false);
_normalizations.put(RedstoneWireBlock.WEST, false);
// _normalizations.put(BlockReed.AGE, false);
_normalizations.put(SaplingBlock.STAGE, 0);
_normalizations.put(StandingSignBlock.ROTATION, 0);
_normalizations.put(StemBlock.AGE, 0);
_normalizations.put(TripWireBlock.NORTH, false);
_normalizations.put(TripWireBlock.EAST, false);
_normalizations.put(TripWireBlock.WEST, false);
_normalizations.put(TripWireBlock.SOUTH, false);
_normalizations.put(VineBlock.NORTH, false);
_normalizations.put(VineBlock.EAST, false);
_normalizations.put(VineBlock.SOUTH, false);
_normalizations.put(VineBlock.WEST, false);
_normalizations.put(VineBlock.UP, false);
_normalizations.put(WallBlock.UP, false);
_normalizations.put(WallBlock.NORTH, false);
_normalizations.put(WallBlock.EAST, false);
_normalizations.put(WallBlock.WEST, false);
_normalizations.put(WallBlock.SOUTH, false);
normalizations = Collections.unmodifiableMap(_normalizations);
}
private static <C extends Comparable<C>, P extends IProperty<C>> P castToIProperty(Object value) {
//noinspection unchecked
return (P) value;
}
private static <C extends Comparable<C>, P extends IProperty<C>> C castToIPropertyValue(P iproperty, Object value) {
//noinspection unchecked
return (C) value;
}
public static BlockState normalize(BlockState state) {
BlockState newState = state;
for (IProperty<?> property : state.getProperties()) {
Class<?> valueClass = property.getValueClass();
if (normalizations.containsKey(property)) {
try {
newState = newState.with(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(property))
);
} catch (IllegalArgumentException ignored) {}
} else if (normalizations.containsKey(state.get(property))) {
try {
newState = newState.with(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(state.get(property)))
);
} catch (IllegalArgumentException ignored) {}
} else if (normalizations.containsKey(valueClass)) {
try {
newState = newState.with(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(valueClass))
);
} catch (IllegalArgumentException ignored) {}
}
}
return newState;
}
public static int stateMeta(BlockState state) {
return state.hashCode();
}
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<BlockState> blockstates) { private static ImmutableSet<Integer> getStateHashes(Set<IBlockState> blockstates) {
return ImmutableSet.copyOf( return ImmutableSet.copyOf(
blockstates.stream() blockstates.stream()
.map(BlockState::hashCode) .map(IBlockState::hashCode)
.toArray(Integer[]::new) .toArray(Integer[]::new)
); );
} }
private static ImmutableSet<Integer> getStackHashes(Set<BlockState> blockstates) { private static ImmutableSet<Integer> getStackHashes(Set<IBlockState> blockstates) {
//noinspection ConstantConditions //noinspection ConstantConditions
return ImmutableSet.copyOf( return ImmutableSet.copyOf(
blockstates.stream() blockstates.stream()
.flatMap(state -> drops(state.getBlock()) .map(state -> new ItemStack(
.stream() state.getBlock().getItemDropped(state, null, null, 0).asItem(),
.map(item -> new ItemStack(item, 1)) 1
) ))
.map(stack -> ((IItemStack) (Object) stack).getBaritoneHash()) .map(stack -> ((IItemStack) (Object) stack).getBaritoneHash())
.toArray(Integer[]::new) .toArray(Integer[]::new)
); );
@@ -251,7 +104,7 @@ public final class BlockOptionalMeta {
return block == this.block; return block == this.block;
} }
public boolean matches(@Nonnull BlockState blockstate) { public boolean matches(@Nonnull IBlockState 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());
} }
@@ -270,43 +123,11 @@ public final class BlockOptionalMeta {
return String.format("BlockOptionalMeta{block=%s}", block); return String.format("BlockOptionalMeta{block=%s}", block);
} }
public BlockState getAnyBlockState() { public IBlockState getAnyBlockState() {
if (blockstates.size() > 0) { if (blockstates.size() > 0) {
return blockstates.iterator().next(); return blockstates.iterator().next();
} }
return null; return null;
} }
public static LootTableManager getManager() {
if (manager == null) {
ResourcePackList rpl = new ResourcePackList<>(ResourcePackInfo::new);
rpl.addPackFinder(new ServerPackFinder());
rpl.reloadPacksFromFinders();
IResourcePack thePack = ((ResourcePackInfo) rpl.getAllPacks().iterator().next()).getResourcePack();
IReloadableResourceManager resourceManager = new SimpleReloadableResourceManager(ResourcePackType.SERVER_DATA, null);
manager = new LootTableManager();
resourceManager.addReloadListener(manager);
try {
resourceManager.reloadResourcesAndThen(new ThreadPerTaskExecutor(Thread::new), new ThreadPerTaskExecutor(Thread::new), Collections.singletonList(thePack), CompletableFuture.completedFuture(Unit.INSTANCE)).get();
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
return manager;
}
private static List<Item> drops(Block b) {
if (!Minecraft.getInstance().isOnExecutionThread()) {
throw new IllegalStateException();
}
return drops.computeIfAbsent(b, block -> {
ResourceLocation lootTableLocation = block.getLootTable();
if (lootTableLocation == LootTables.EMPTY) {
return Collections.emptyList();
} else {
return getManager().getLootTableFromLocation(lootTableLocation).generate(new LootContext.Builder(null).withRandom(new Random()).withParameter(LootParameters.POSITION, BlockPos.ZERO).withParameter(LootParameters.TOOL, ItemStack.EMPTY).withNullableParameter(LootParameters.BLOCK_ENTITY, null).withParameter(LootParameters.BLOCK_STATE, block.getDefaultState()).build(LootParameterSets.BLOCK)).stream().map(ItemStack::getItem).collect(Collectors.toList());
}
});
}
} }
@@ -18,7 +18,7 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.state.IBlockState;
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(BlockState state) { public boolean has(IBlockState 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.Registry; import net.minecraft.util.registry.IRegistry;
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 = Registry.BLOCK.getKey(block); ResourceLocation loc = IRegistry.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 = Registry.BLOCK.getValue(ResourceLocation.tryCreate(name.contains(":") ? name : "minecraft:" + name)).orElse(null); block = IRegistry.BLOCK.get(ResourceLocation.tryCreate(name.contains(":") ? name : "minecraft:" + name));
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.StringTextComponent; import net.minecraft.util.text.TextComponentString;
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 StringTextComponent(BaritoneAPI.getSettings().shortBaritonePrefix.value ? "B" : "Baritone"); ITextComponent baritone = new TextComponentString(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 StringTextComponent(""); ITextComponent prefix = new TextComponentString("");
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 StringTextComponent(""); ITextComponent component = new TextComponentString("");
component.appendSibling(getPrefix()); component.appendSibling(getPrefix());
component.appendSibling(new StringTextComponent(" ")); component.appendSibling(new TextComponentString(" "));
Arrays.asList(components).forEach(component::appendSibling); Arrays.asList(components).forEach(component::appendSibling);
mc.execute(() -> BaritoneAPI.getSettings().logger.value.accept(component)); mc.addScheduledTask(() -> 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 StringTextComponent(line.replace("\t", " ")); ITextComponent component = new TextComponentString(line.replace("\t", " "));
component.getStyle().setColor(color); component.getStyle().setColor(color);
logDirect(component); logDirect(component);
}); });
@@ -18,16 +18,15 @@
package baritone.api.utils; package baritone.api.utils;
import baritone.api.cache.IWorldData; import baritone.api.cache.IWorldData;
import net.minecraft.block.SlabBlock; import net.minecraft.block.BlockSlab;
import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.math.*; import net.minecraft.util.math.BlockPos;
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
@@ -35,21 +34,12 @@ import java.util.stream.StreamSupport;
*/ */
public interface IPlayerContext { public interface IPlayerContext {
ClientPlayerEntity player(); EntityPlayerSP 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();
@@ -67,7 +57,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 SlabBlock) { if (world().getBlockState(feet).getBlock() instanceof BlockSlab) {
return feet.up(); return feet.up();
} }
} catch (NullPointerException ignored) {} } catch (NullPointerException ignored) {}
@@ -94,8 +84,8 @@ public interface IPlayerContext {
*/ */
default Optional<BlockPos> getSelectedBlock() { default Optional<BlockPos> getSelectedBlock() {
RayTraceResult result = objectMouseOver(); RayTraceResult result = objectMouseOver();
if (result != null && result.getType() == RayTraceResult.Type.BLOCK) { if (result != null && result.type == RayTraceResult.Type.BLOCK) {
return Optional.of(((BlockRayTraceResult) result).getPos()); return Optional.of(result.getBlockPos());
} }
return Optional.empty(); return Optional.empty();
} }
@@ -111,8 +101,8 @@ public interface IPlayerContext {
*/ */
default Optional<Entity> getSelectedEntity() { default Optional<Entity> getSelectedEntity() {
RayTraceResult result = objectMouseOver(); RayTraceResult result = objectMouseOver();
if (result != null && result.getType() == RayTraceResult.Type.ENTITY) { if (result != null && result.type == RayTraceResult.Type.ENTITY) {
return Optional.of(((EntityRayTraceResult) result).getEntity()); return Optional.of(result.entity);
} }
return Optional.empty(); return Optional.empty();
} }
@@ -17,15 +17,16 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.client.entity.player.ClientPlayerEntity; import baritone.api.BaritoneAPI;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.inventory.container.ClickType; 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.ActionResultType; import net.minecraft.util.EnumActionResult;
import net.minecraft.util.Direction; import net.minecraft.util.EnumFacing;
import net.minecraft.util.Hand; import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.util.math.Vec3d;
import net.minecraft.world.GameType; import net.minecraft.world.GameType;
import net.minecraft.world.World; import net.minecraft.world.World;
@@ -39,23 +40,23 @@ public interface IPlayerController {
boolean hasBrokenBlock(); boolean hasBrokenBlock();
boolean onPlayerDamageBlock(BlockPos pos, Direction side); boolean onPlayerDamageBlock(BlockPos pos, EnumFacing side);
void resetBlockRemoving(); void resetBlockRemoving();
ItemStack windowClick(int windowId, int slotId, int mouseButton, ClickType type, PlayerEntity player); ItemStack windowClick(int windowId, int slotId, int mouseButton, ClickType type, EntityPlayer player);
GameType getGameType(); GameType getGameType();
ActionResultType processRightClickBlock(ClientPlayerEntity player, World world, Hand hand, BlockRayTraceResult result); EnumActionResult processRightClickBlock(EntityPlayerSP player, World world, BlockPos pos, EnumFacing direction, Vec3d vec, EnumHand hand);
ActionResultType processRightClick(ClientPlayerEntity player, World world, Hand hand); EnumActionResult processRightClick(EntityPlayerSP player, World world, EnumHand hand);
boolean clickBlock(BlockPos loc, Direction face); boolean clickBlock(BlockPos loc, EnumFacing face);
void setHittingBlock(boolean hittingBlock); void setHittingBlock(boolean hittingBlock);
default double getBlockReachDistance() { default double getBlockReachDistance() {
return this.getGameType().isCreative() ? 5.0F : 4.5F; return this.getGameType().isCreative() ? 5.0F : BaritoneAPI.getSettings().blockReachDistance.value;
} }
} }
@@ -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.RayTraceContext; import net.minecraft.util.math.RayTraceFluidMode;
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(new RayTraceContext(start, end, RayTraceContext.BlockMode.OUTLINE, RayTraceContext.FluidMode.NONE, entity)); return entity.world.rayTraceBlocks(start, end, RayTraceFluidMode.NEVER, false, true);
} }
} }
@@ -19,12 +19,15 @@ package baritone.api.utils;
import baritone.api.BaritoneAPI; import baritone.api.BaritoneAPI;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockFire;
import net.minecraft.block.FireBlock; import net.minecraft.block.state.IBlockState;
import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.Direction; import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.*; import net.minecraft.util.math.BlockPos;
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;
@@ -137,7 +140,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(ClientPlayerEntity, BlockPos, double) * @see #reachable(EntityPlayerSP, 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());
@@ -155,7 +158,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(ClientPlayerEntity entity, BlockPos pos, double blockReachDistance) { public static Optional<Rotation> reachable(EntityPlayerSP 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)) {
/* /*
@@ -176,15 +179,15 @@ public final class RotationUtils {
return possibleRotation; return possibleRotation;
} }
BlockState state = entity.world.getBlockState(pos); IBlockState 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(Direction.Axis.X) * sideOffset.x + shape.getEnd(Direction.Axis.X) * (1 - sideOffset.x); double xDiff = shape.getStart(EnumFacing.Axis.X) * sideOffset.x + shape.getEnd(EnumFacing.Axis.X) * (1 - sideOffset.x);
double yDiff = shape.getStart(Direction.Axis.Y) * sideOffset.y + shape.getEnd(Direction.Axis.Y) * (1 - sideOffset.y); double yDiff = shape.getStart(EnumFacing.Axis.Y) * sideOffset.y + shape.getEnd(EnumFacing.Axis.Y) * (1 - sideOffset.y);
double zDiff = shape.getStart(Direction.Axis.Z) * sideOffset.z + shape.getEnd(Direction.Axis.Z) * (1 - sideOffset.z); double zDiff = shape.getStart(EnumFacing.Axis.Z) * sideOffset.z + shape.getEnd(EnumFacing.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;
@@ -208,11 +211,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.getType() == RayTraceResult.Type.BLOCK) { if (result != null && result.type == RayTraceResult.Type.BLOCK) {
if (((BlockRayTraceResult) result).getPos().equals(pos)) { if (result.getBlockPos().equals(pos)) {
return Optional.of(rotation); return Optional.of(rotation);
} }
if (entity.world.getBlockState(pos).getBlock() instanceof FireBlock && ((BlockRayTraceResult) result).getPos().equals(pos.down())) { if (entity.world.getBlockState(pos).getBlock() instanceof BlockFire && result.getBlockPos().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.Direction; import net.minecraft.util.EnumFacing;
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.Registry; import net.minecraft.util.registry.IRegistry;
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),
DIRECTION(Direction.class, Direction::byName), ENUMFACING(EnumFacing.class, EnumFacing::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 -> Registry.ITEM.getOrDefault(new ResourceLocation(str.trim())), // TODO this now returns AIR on failure instead of null, is that an issue? str -> IRegistry.ITEM.get(new ResourceLocation(str.trim())),
item -> Registry.ITEM.getKey(item).toString() item -> IRegistry.ITEM.getKey(item).toString()
), ),
LIST() { LIST() {
@Override @Override
@@ -17,10 +17,10 @@
package baritone.api.utils; package baritone.api.utils;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockFire;
import net.minecraft.block.FireBlock; import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.util.Direction; import net.minecraft.util.EnumFacing;
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) {
BlockState b = world.getBlockState(pos); IBlockState 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(Direction.Axis.X) + shape.getEnd(Direction.Axis.X)) / 2; double xDiff = (shape.getStart(EnumFacing.Axis.X) + shape.getEnd(EnumFacing.Axis.X)) / 2;
double yDiff = (shape.getStart(Direction.Axis.Y) + shape.getEnd(Direction.Axis.Y)) / 2; double yDiff = (shape.getStart(EnumFacing.Axis.Y) + shape.getEnd(EnumFacing.Axis.Y)) / 2;
double zDiff = (shape.getStart(Direction.Axis.Z) + shape.getEnd(Direction.Axis.Z)) / 2; double zDiff = (shape.getStart(EnumFacing.Axis.Z) + shape.getEnd(EnumFacing.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 FireBlock) {//look at bottom of fire when putting it out if (b.getBlock() instanceof BlockFire) {//look at bottom of fire when putting it out
yDiff = 0; yDiff = 0;
} }
return new Vec3d( return new Vec3d(
@@ -17,32 +17,27 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.utils.accessor.IEntityRenderManager; import baritone.utils.accessor.IAnvilChunkLoader;
import net.minecraft.client.renderer.entity.EntityRendererManager; import net.minecraft.world.chunk.storage.AnvilChunkLoader;
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;
@Mixin(EntityRendererManager.class) import java.io.File;
public class MixinEntityRenderManager implements IEntityRenderManager {
/**
* @author Brady
* @since 9/4/2018
*/
@Mixin(AnvilChunkLoader.class)
public class MixinAnvilChunkLoader implements IAnvilChunkLoader {
@Shadow @Shadow
private double renderPosX; @Final
@Shadow private File chunkSaveLocation;
private double renderPosY;
@Shadow
private double renderPosZ;
@Override @Override
public double renderPosX() { public File getChunkSaveLocation() {
return renderPosX; return this.chunkSaveLocation;
}
@Override
public double renderPosY() {
return renderPosY;
}
@Override
public double renderPosZ() {
return renderPosZ;
} }
} }
@@ -19,7 +19,7 @@ package baritone.launch.mixins;
import baritone.utils.accessor.IBitArray; import baritone.utils.accessor.IBitArray;
import baritone.utils.accessor.IBlockStateContainer; import baritone.utils.accessor.IBlockStateContainer;
import net.minecraft.block.BlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.util.BitArray; import net.minecraft.util.BitArray;
import net.minecraft.world.chunk.BlockStateContainer; import net.minecraft.world.chunk.BlockStateContainer;
import net.minecraft.world.chunk.IBlockStatePalette; import net.minecraft.world.chunk.IBlockStatePalette;
@@ -33,10 +33,10 @@ public abstract class MixinBlockStateContainer implements IBlockStateContainer {
protected BitArray storage; protected BitArray storage;
@Shadow @Shadow
protected IBlockStatePalette<BlockState> palette; protected IBlockStatePalette<IBlockState> palette;
@Override @Override
public BlockState getAtPalette(int index) { public IBlockState getAtPalette(int index) {
return palette.get(index); return palette.get(index);
} }
@@ -1,92 +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.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);
}
}
}
}
}
@@ -15,20 +15,25 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>. * along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/ */
package baritone.utils.accessor; package baritone.launch.mixins;
import baritone.utils.accessor.IChunkProviderClient;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import net.minecraft.client.multiplayer.ChunkProviderClient;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import java.util.concurrent.atomic.AtomicReferenceArray; @Mixin(ChunkProviderClient.class)
public class MixinChunkProviderClient implements IChunkProviderClient {
public interface IChunkArray { @Shadow
void copyFrom(IChunkArray other); @Final
private Long2ObjectMap<Chunk> loadedChunks;
AtomicReferenceArray<Chunk> getChunks(); @Override
public Long2ObjectMap<Chunk> loadedChunks() {
int centerX(); return this.loadedChunks;
}
int centerZ();
int viewDistance();
} }
@@ -0,0 +1,42 @@
/*
* 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;
}
}
@@ -0,0 +1,55 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <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();
}
}
@@ -0,0 +1,57 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <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);
}
}
@@ -1,61 +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.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()));
}
}
@@ -1,60 +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.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;
}
}
@@ -20,11 +20,10 @@ 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.player.ClientPlayerEntity; import net.minecraft.client.entity.EntityPlayerSP;
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;
@@ -38,15 +37,15 @@ import static org.spongepowered.asm.lib.Opcodes.GETFIELD;
* @author Brady * @author Brady
* @since 9/10/2018 * @since 9/10/2018
*/ */
@Mixin(LivingEntity.class) @Mixin(EntityLivingBase.class)
public abstract class MixinLivingEntity extends Entity { public abstract class MixinEntityLivingBase 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 MixinLivingEntity(EntityType<?> entityTypeIn, World worldIn) { public MixinEntityLivingBase(EntityType<?> entityTypeIn, World worldIn) {
super(entityTypeIn, worldIn); super(entityTypeIn, worldIn);
} }
@@ -56,8 +55,8 @@ public abstract class MixinLivingEntity extends Entity {
) )
private void preMoveRelative(CallbackInfo ci) { private void preMoveRelative(CallbackInfo ci) {
// noinspection ConstantConditions // noinspection ConstantConditions
if (ClientPlayerEntity.class.isInstance(this)) { if (EntityPlayerSP.class.isInstance(this)) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (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);
@@ -70,15 +69,34 @@ public abstract class MixinLivingEntity extends Entity {
at = @At( at = @At(
value = "FIELD", value = "FIELD",
opcode = GETFIELD, opcode = GETFIELD,
target = "net/minecraft/entity/LivingEntity.rotationYaw:F" target = "net/minecraft/entity/EntityLivingBase.rotationYaw:F"
) )
) )
private float overrideYaw(LivingEntity self) { private float overrideYaw(EntityLivingBase self) {
if (self instanceof ClientPlayerEntity && BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this) != null) { if (self instanceof EntityPlayerSP && BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (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;
}
} }
@@ -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.player.ClientPlayerEntity; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.settings.KeyBinding; import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.player.PlayerAbilities; import net.minecraft.entity.player.PlayerCapabilities;
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(ClientPlayerEntity.class) @Mixin(EntityPlayerSP.class)
public class MixinClientPlayerEntity { public class MixinEntityPlayerSP {
@Inject( @Inject(
method = "sendChatMessage", method = "sendChatMessage",
@@ -47,7 +47,7 @@ public class MixinClientPlayerEntity {
) )
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((ClientPlayerEntity) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone == null) { if (baritone == null) {
return; return;
} }
@@ -61,13 +61,13 @@ public class MixinClientPlayerEntity {
method = "tick", method = "tick",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/entity/player/ClientPlayerEntity.isPassenger()Z", target = "net/minecraft/client/entity/EntityPlayerSP.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((ClientPlayerEntity) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (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 MixinClientPlayerEntity {
method = "tick", method = "tick",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/entity/player/ClientPlayerEntity.onUpdateWalkingPlayer()V", target = "net/minecraft/client/entity/EntityPlayerSP.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((ClientPlayerEntity) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (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 MixinClientPlayerEntity {
method = "livingTick", method = "livingTick",
at = @At( at = @At(
value = "FIELD", value = "FIELD",
target = "net/minecraft/entity/player/PlayerAbilities.allowFlying:Z" target = "net/minecraft/entity/player/PlayerCapabilities.allowFlying:Z"
) )
) )
private boolean isAllowFlying(PlayerAbilities capabilities) { private boolean isAllowFlying(PlayerCapabilities capabilities) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone == null) { if (baritone == null) {
return capabilities.allowFlying; return capabilities.allowFlying;
} }
@@ -112,7 +112,7 @@ public class MixinClientPlayerEntity {
) )
) )
private boolean isKeyDown(KeyBinding keyBinding) { private boolean isKeyDown(KeyBinding keyBinding) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone == null) { if (baritone == null) {
return keyBinding.isKeyDown(); return keyBinding.isKeyDown();
} }
@@ -135,7 +135,7 @@ public class MixinClientPlayerEntity {
) )
) )
private void updateRidden(CallbackInfo cb) { private void updateRidden(CallbackInfo cb) {
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((ClientPlayerEntity) (Object) this); IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone != null) { if (baritone != null) {
((LookBehavior) baritone.getLookBehavior()).pig(); ((LookBehavior) baritone.getLookBehavior()).pig();
} }
@@ -33,7 +33,7 @@ public class MixinGameRenderer {
method = "updateCameraAndRender(FJ)V", method = "updateCameraAndRender(FJ)V",
at = @At( at = @At(
value = "INVOKE_STRING", value = "INVOKE_STRING",
target = "Lnet/minecraft/profiler/IProfiler;endStartSection(Ljava/lang/String;)V", target = "Lnet/minecraft/profiler/Profiler;endStartSection(Ljava/lang/String;)V",
args = {"ldc=hand"} args = {"ldc=hand"}
) )
) )
@@ -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.screen.ChatScreen; import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.GuiTextField;
import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
@@ -40,11 +40,11 @@ import java.util.stream.Stream;
* @author Brady * @author Brady
* @since 10/9/2019 * @since 10/9/2019
*/ */
@Mixin(ChatScreen.class) @Mixin(GuiChat.class)
public class MixinChatScreen { public class MixinGuiChat {
@Shadow @Shadow
protected TextFieldWidget inputField; protected GuiTextField inputField;
@Shadow @Shadow
@Final @Final
@@ -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.screen.Screen; import net.minecraft.client.gui.GuiScreen;
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(Screen.class) @Mixin(GuiScreen.class)
public abstract class MixinScreen implements IGuiScreen { public abstract class MixinGuiScreen implements IGuiScreen {
@Override @Override
@Invoker("openLink") @Invoker("openWebLink")
public abstract void openLink(URI url); public abstract void openLink(URI url);
} }
@@ -1,59 +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.api.utils.BlockOptionalMeta;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.LootTableManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(LootContext.Builder.class)
public class MixinLootContext {
@Redirect(
method = "build",
at = @At(
value = "INVOKE",
target = "net/minecraft/world/server/ServerWorld.getServer()Lnet/minecraft/server/MinecraftServer;"
)
)
private MinecraftServer getServer(ServerWorld world) {
if (world == null) {
return null;
}
return world.getServer();
}
@Redirect(
method = "build",
at = @At(
value = "INVOKE",
target = "net/minecraft/server/MinecraftServer.getLootTableManager()Lnet/minecraft/world/storage/loot/LootTableManager;"
)
)
private LootTableManager getLootTableManager(MinecraftServer server) {
if (server == null) {
return BlockOptionalMeta.getManager();
}
return server.getLootTableManager();
}
}
@@ -25,13 +25,13 @@ import baritone.api.event.events.WorldEvent;
import baritone.api.event.events.type.EventState; import baritone.api.event.events.type.EventState;
import baritone.utils.BaritoneAutoTest; import baritone.utils.BaritoneAutoTest;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.entity.EntityPlayerSP;
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.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResultType; import net.minecraft.util.EnumActionResult;
import net.minecraft.util.Hand; import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockRayTraceResult; 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;
@@ -41,6 +41,8 @@ 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 org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import java.util.function.BiFunction;
/** /**
* @author Brady * @author Brady
* @since 7/31/2018 * @since 7/31/2018
@@ -49,9 +51,9 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
public class MixinMinecraft { public class MixinMinecraft {
@Shadow @Shadow
public ClientPlayerEntity player; public EntityPlayerSP player;
@Shadow @Shadow
public ClientWorld world; public WorldClient world;
@Inject( @Inject(
method = "init", method = "init",
@@ -77,29 +79,31 @@ 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/screen/Screen;", target = "net/minecraft/client/Minecraft.currentScreen:Lnet/minecraft/client/gui/GuiScreen;",
ordinal = 5, ordinal = 5,
shift = At.Shift.BY, shift = At.Shift.BY,
by = -3 by = -3
) )
) )
private void runTick(CallbackInfo ci) { private void runTick(CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { final BiFunction<EventState, TickEvent.Type, TickEvent> tickProvider = TickEvent.createNextProvider();
TickEvent.Type type = ibaritone.getPlayerContext().player() != null && ibaritone.getPlayerContext().world() != null for (IBaritone baritone : BaritoneAPI.getProvider().getAllBaritones()) {
TickEvent.Type type = baritone.getPlayerContext().player() != null && baritone.getPlayerContext().world() != null
? TickEvent.Type.IN ? TickEvent.Type.IN
: TickEvent.Type.OUT; : TickEvent.Type.OUT;
ibaritone.getGameEventHandler().onTick(new TickEvent(EventState.PRE, type)); baritone.getGameEventHandler().onTick(tickProvider.apply(EventState.PRE, type));
} }
} }
@Inject( @Inject(
method = "loadWorld(Lnet/minecraft/client/world/ClientWorld;)V", method = "loadWorld(Lnet/minecraft/client/multiplayer/WorldClient;Lnet/minecraft/client/gui/GuiScreen;)V",
at = @At("HEAD") at = @At("HEAD")
) )
private void preLoadWorld(ClientWorld world, CallbackInfo ci) { private void preLoadWorld(WorldClient world, GuiScreen loadingScreen, CallbackInfo ci) {
// If we're unloading the world but one doesn't exist, ignore it // If we're unloading the world but one doesn't exist, ignore it
if (this.world == null && world == null) { if (this.world == null && world == null) {
return; return;
@@ -116,10 +120,10 @@ public class MixinMinecraft {
} }
@Inject( @Inject(
method = "loadWorld(Lnet/minecraft/client/world/ClientWorld;)V", method = "loadWorld(Lnet/minecraft/client/multiplayer/WorldClient;Lnet/minecraft/client/gui/GuiScreen;)V",
at = @At("RETURN") at = @At("RETURN")
) )
private void postLoadWorld(ClientWorld world, CallbackInfo ci) { private void postLoadWorld(WorldClient world, GuiScreen loadingScreen, CallbackInfo ci) {
// still fire event for both null, as that means we've just finished exiting a world // still fire event for both null, as that means we've just finished exiting a world
// mc.world changing is only the primary baritone // mc.world changing is only the primary baritone
@@ -136,24 +140,37 @@ public class MixinMinecraft {
at = @At( at = @At(
value = "FIELD", value = "FIELD",
opcode = Opcodes.GETFIELD, opcode = Opcodes.GETFIELD,
target = "net/minecraft/client/gui/screen/Screen.passEvents:Z" target = "net/minecraft/client/gui/GuiScreen.allowUserInput:Z"
) )
) )
private boolean passEvents(Screen screen) { private boolean isAllowUserInput(GuiScreen 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.passEvents; return (BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().getCurrent() != null && player != null) || screen.allowUserInput;
}
@Inject(
method = "clickMouse",
at = @At(
value = "INVOKE",
target = "net/minecraft/client/multiplayer/PlayerControllerMP.clickBlock(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/EnumFacing;)Z"
),
locals = LocalCapture.CAPTURE_FAILHARD
)
private void onBlockBreak(CallbackInfo ci, BlockPos pos) {
// clickMouse is only for the main player
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(pos, BlockInteractEvent.Type.START_BREAK));
} }
@Inject( @Inject(
method = "rightClickMouse", method = "rightClickMouse",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/entity/player/ClientPlayerEntity.swingArm(Lnet/minecraft/util/Hand;)V" target = "net/minecraft/client/entity/EntityPlayerSP.swingArm(Lnet/minecraft/util/EnumHand;)V"
), ),
locals = LocalCapture.CAPTURE_FAILHARD locals = LocalCapture.CAPTURE_FAILHARD
) )
private void onBlockUse(CallbackInfo ci, Hand var1[], int var2, int var3, Hand enumhand, ItemStack itemstack, BlockRayTraceResult raytrace, int i, ActionResultType enumactionresult) { private void onBlockUse(CallbackInfo ci, EnumHand var1[], int var2, int var3, EnumHand enumhand, ItemStack itemstack, BlockPos blockpos, int i, EnumActionResult enumactionresult) {
// rightClickMouse is only for the main player // rightClickMouse is only for the main player
BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(raytrace.getPos(), BlockInteractEvent.Type.USE)); BaritoneAPI.getProvider().getPrimaryBaritone().getGameEventHandler().onBlockInteract(new BlockInteractEvent(blockpos, BlockInteractEvent.Type.USE));
} }
} }
@@ -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.play.ClientPlayNetHandler; import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.network.play.server.SChunkDataPacket; import net.minecraft.network.play.server.SPacketChunkData;
import net.minecraft.network.play.server.SCombatPacket; import net.minecraft.network.play.server.SPacketCombatEvent;
import net.minecraft.network.play.server.SUnloadChunkPacket; import net.minecraft.network.play.server.SPacketUnloadChunk;
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,11 +34,10 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
* @author Brady * @author Brady
* @since 8/3/2018 * @since 8/3/2018
*/ */
@Mixin(ClientPlayNetHandler.class) @Mixin(NetHandlerPlayClient.class)
public class MixinClientPlayNetHandler { public class MixinNetHandlerPlayClient {
// unused lol @Inject(
/*@Inject(
method = "handleChunkData", method = "handleChunkData",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
@@ -58,15 +57,15 @@ public class MixinClientPlayNetHandler {
); );
} }
} }
}*/ }
@Inject( @Inject(
method = "handleChunkData", method = "handleChunkData",
at = @At("RETURN") at = @At("RETURN")
) )
private void postHandleChunkData(SChunkDataPacket packetIn, CallbackInfo ci) { private void postHandleChunkData(SPacketChunkData packetIn, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (ClientPlayNetHandler) (Object) this) { if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) {
ibaritone.getGameEventHandler().onChunkEvent( ibaritone.getGameEventHandler().onChunkEvent(
new ChunkEvent( new ChunkEvent(
EventState.POST, EventState.POST,
@@ -83,9 +82,9 @@ public class MixinClientPlayNetHandler {
method = "processChunkUnload", method = "processChunkUnload",
at = @At("HEAD") at = @At("HEAD")
) )
private void preChunkUnload(SUnloadChunkPacket packet, CallbackInfo ci) { private void preChunkUnload(SPacketUnloadChunk packet, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (ClientPlayNetHandler) (Object) this) { if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (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())
); );
@@ -97,9 +96,9 @@ public class MixinClientPlayNetHandler {
method = "processChunkUnload", method = "processChunkUnload",
at = @At("RETURN") at = @At("RETURN")
) )
private void postChunkUnload(SUnloadChunkPacket packet, CallbackInfo ci) { private void postChunkUnload(SPacketUnloadChunk packet, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (ClientPlayNetHandler) (Object) this) { if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (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())
); );
@@ -111,12 +110,12 @@ public class MixinClientPlayNetHandler {
method = "handleCombatEvent", method = "handleCombatEvent",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "net/minecraft/client/Minecraft.displayGuiScreen(Lnet/minecraft/client/gui/screen/Screen;)V" target = "net/minecraft/client/Minecraft.displayGuiScreen(Lnet/minecraft/client/gui/GuiScreen;)V"
) )
) )
private void onPlayerDeath(SCombatPacket packetIn, CallbackInfo ci) { private void onPlayerDeath(SPacketCombatEvent packetIn, CallbackInfo ci) {
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
if (ibaritone.getPlayerContext().player().connection == (ClientPlayNetHandler) (Object) this) { if (ibaritone.getPlayerContext().player().connection == (NetHandlerPlayClient) (Object) this) {
ibaritone.getGameEventHandler().onPlayerDeath(); ibaritone.getGameEventHandler().onPlayerDeath();
} }
} }
@@ -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.IPacket; import net.minecraft.network.EnumPacketDirection;
import net.minecraft.network.NetworkManager; import net.minecraft.network.NetworkManager;
import net.minecraft.network.PacketDirection; import net.minecraft.network.Packet;
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 PacketDirection direction; private EnumPacketDirection direction;
@Inject( @Inject(
method = "dispatchPacket", method = "dispatchPacket",
at = @At("HEAD") at = @At("HEAD")
) )
private void preDispatchPacket(IPacket<?> inPacket, final GenericFutureListener<? extends Future<? super Void>> futureListeners, CallbackInfo ci) { private void preDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>> futureListeners, CallbackInfo ci) {
if (this.direction != PacketDirection.CLIENTBOUND) { if (this.direction != EnumPacketDirection.CLIENTBOUND) {
return; return;
} }
@@ -69,8 +69,8 @@ public class MixinNetworkManager {
method = "dispatchPacket", method = "dispatchPacket",
at = @At("RETURN") at = @At("RETURN")
) )
private void postDispatchPacket(IPacket<?> inPacket, final GenericFutureListener<? extends Future<? super Void>> futureListeners, CallbackInfo ci) { private void postDispatchPacket(Packet<?> inPacket, final GenericFutureListener<? extends Future<? super Void>> futureListeners, CallbackInfo ci) {
if (this.direction != PacketDirection.CLIENTBOUND) { if (this.direction != EnumPacketDirection.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/IPacket;Lnet/minecraft/network/INetHandler;)V" target = "net/minecraft/network/NetworkManager.processPacket(Lnet/minecraft/network/Packet;Lnet/minecraft/network/INetHandler;)V"
) )
) )
private void preProcessPacket(ChannelHandlerContext context, IPacket<?> packet, CallbackInfo ci) { private void preProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) {
if (this.direction != PacketDirection.CLIENTBOUND) { if (this.direction != EnumPacketDirection.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, IPacket<?> packet, CallbackInfo ci) { private void postProcessPacket(ChannelHandlerContext context, Packet<?> packet, CallbackInfo ci) {
if (!this.channel.isOpen() || this.direction != PacketDirection.CLIENTBOUND) { if (!this.channel.isOpen() || this.direction != EnumPacketDirection.CLIENTBOUND) {
return; return;
} }
for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) { for (IBaritone ibaritone : BaritoneAPI.getProvider().getAllBaritones()) {
@@ -18,14 +18,14 @@
package baritone.launch.mixins; package baritone.launch.mixins;
import baritone.utils.accessor.IPlayerControllerMP; import baritone.utils.accessor.IPlayerControllerMP;
import net.minecraft.client.multiplayer.PlayerController; import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(PlayerController.class) @Mixin(PlayerControllerMP.class)
public abstract class MixinPlayerController implements IPlayerControllerMP { public abstract class MixinPlayerControllerMP implements IPlayerControllerMP {
@Accessor @Accessor
@Override @Override
@@ -0,0 +1,57 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <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);
}
}
@@ -0,0 +1,47 @@
/*
* 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;
}
}
@@ -0,0 +1,47 @@
/*
* 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();
}
}
@@ -0,0 +1,47 @@
/*
* 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();
}
}
+15 -11
View File
@@ -8,22 +8,26 @@
"maxShiftBy": 2 "maxShiftBy": 2
}, },
"client": [ "client": [
"MixinAnvilChunkLoader",
"MixinBitArray", "MixinBitArray",
"MixinBlockStateContainer", "MixinBlockStateContainer",
"MixinChatScreen", "MixinChunkProviderClient",
"MixinChunkArray", "MixinChunkProviderServer",
"MixinClientChunkProvider", "MixinChunkRenderContainer",
"MixinClientPlayerEntity", "MixinChunkRenderWorker",
"MixinClientPlayNetHandler", "MixinEntityLivingBase",
"MixinEntity", "MixinEntityPlayerSP",
"MixinEntityRenderManager",
"MixinGameRenderer", "MixinGameRenderer",
"MixinGuiChat",
"MixinGuiScreen",
"MixinItemStack", "MixinItemStack",
"MixinLivingEntity",
"MixinLootContext",
"MixinMinecraft", "MixinMinecraft",
"MixinNetHandlerPlayClient",
"MixinNetworkManager", "MixinNetworkManager",
"MixinPlayerController", "MixinPlayerControllerMP",
"MixinScreen" "MixinRenderChunk",
"MixinRenderChunkCache",
"MixinRenderList",
"MixinVboRenderList"
] ]
} }
+1 -1
View File
@@ -218,7 +218,7 @@ public class Baritone implements IBaritone {
new Thread(() -> { new Thread(() -> {
try { try {
Thread.sleep(100); Thread.sleep(100);
Helper.mc.execute(() -> Helper.mc.displayGuiScreen(new GuiClick())); Helper.mc.addScheduledTask(() -> Helper.mc.displayGuiScreen(new GuiClick()));
} catch (Exception ignored) {} } catch (Exception ignored) {}
}).start(); }).start();
} }
@@ -21,9 +21,11 @@ import baritone.api.IBaritone;
import baritone.api.IBaritoneProvider; import baritone.api.IBaritoneProvider;
import baritone.api.cache.IWorldScanner; import baritone.api.cache.IWorldScanner;
import baritone.api.command.ICommandSystem; import baritone.api.command.ICommandSystem;
import baritone.api.schematic.ISchematicSystem;
import baritone.command.BaritoneChatControl; import baritone.command.BaritoneChatControl;
import baritone.cache.WorldScanner; import baritone.cache.WorldScanner;
import baritone.command.CommandSystem; import baritone.command.CommandSystem;
import baritone.utils.schematic.SchematicSystem;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -64,4 +66,9 @@ public final class BaritoneProvider implements IBaritoneProvider {
public ICommandSystem getCommandSystem() { public ICommandSystem getCommandSystem() {
return CommandSystem.INSTANCE; return CommandSystem.INSTANCE;
} }
@Override
public ISchematicSystem getSchematicSystem() {
return SchematicSystem.INSTANCE;
}
} }
@@ -21,16 +21,13 @@ 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.BlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.block.Blocks; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.init.Blocks;
import net.minecraft.inventory.container.ClickType; import net.minecraft.inventory.ClickType;
import net.minecraft.item.*; import net.minecraft.item.*;
import net.minecraft.util.Direction; import net.minecraft.util.EnumFacing;
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;
@@ -51,14 +48,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().container) { if (ctx.player().openContainer != ctx.player().inventoryContainer) {
// 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, PickaxeItem.class); int pick = bestToolAgainst(Blocks.STONE, ItemPickaxe.class);
if (pick >= 9) { if (pick >= 9) {
swapWithHotBar(pick, 0); swapWithHotBar(pick, 0);
} }
@@ -93,7 +90,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().container.windowId, inInventory < 9 ? inInventory + 36 : inInventory, inHotbar, ClickType.SWAP, ctx.player()); ctx.playerController().windowClick(ctx.player().inventoryContainer.windowId, inInventory < 9 ? inInventory + 36 : inInventory, inHotbar, ClickType.SWAP, ctx.player());
} }
private int firstValidThrowaway() { // TODO offhand idk private int firstValidThrowaway() { // TODO offhand idk
@@ -106,7 +103,7 @@ public final class InventoryBehavior extends Behavior {
return -1; return -1;
} }
private int bestToolAgainst(Block against, Class<? extends ToolItem> cla$$) { private int bestToolAgainst(Block against, Class<? extends ItemTool> 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;
@@ -136,11 +133,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) {
BlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z, baritone.bsi.get0(x, y, z)); IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z, baritone.bsi.get0(x, y, z));
if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof BlockItem && maybe.equals(((BlockItem) stack.getItem()).getBlock().getStateForPlacement(new BlockItemUseContext(new ItemUseContext(ctx.world(), ctx.player(), Hand.MAIN_HAND, stack, new BlockRayTraceResult(new Vec3d(ctx.player().posX, ctx.player().posY, ctx.player().posZ), Direction.UP, ctx.playerFeet(), false)) {}))))) { 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)))))) {
return true; // gotem return true; // gotem
} }
if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof BlockItem && ((BlockItem) stack.getItem()).getBlock().equals(maybe.getBlock()))) { if (maybe != null && throwaway(select, stack -> stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock().equals(maybe.getBlock()))) {
return true; return true;
} }
for (Item item : Baritone.settings().acceptableThrowawayItems.value) { for (Item item : Baritone.settings().acceptableThrowawayItems.value) {
@@ -152,7 +149,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) {
ClientPlayerEntity p = ctx.player(); EntityPlayerSP 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);
@@ -176,7 +173,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 PickaxeItem) { if (item.isEmpty() || item.getItem() instanceof ItemPickaxe) {
if (select) { if (select) {
p.inventory.currentItem = i; p.inventory.currentItem = i;
} }
@@ -20,20 +20,32 @@ 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.BedBlock; import net.minecraft.block.Block;
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.HashMap; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/** /**
* doesn't work for horse inventories :^) * doesn't work for horse inventories :^)
@@ -43,13 +55,111 @@ import java.util.UUID;
*/ */
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 BedBlock) { if (event.getType() == BlockInteractEvent.Type.USE && BlockStateInterface.getBlock(ctx, event.getPos()) instanceof BlockBed) {
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())));
} }
} }
@@ -59,6 +169,86 @@ public final class MemoryBehavior extends Behavior {
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, ctx.playerFeet())); baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("death", Waypoint.Tag.DEATH, ctx.playerFeet()));
} }
private void updateInventory() {
if (!Baritone.settings().containerMemory.value) {
return;
}
int windowId = ctx.player().openContainer.windowId;
if (enderChestWindowId != null) {
if (windowId == enderChestWindowId) {
getCurrent().contents = ctx.player().openContainer.getInventory().subList(0, 27);
} else {
getCurrent().save();
enderChestWindowId = null;
}
}
if (getCurrentContainer() != null) {
getCurrentContainer().getInventoryFromWindow(windowId).ifPresent(inventory -> inventory.updateFromOpenWindow(ctx));
}
}
private ContainerMemory getCurrentContainer() {
if (baritone.getWorldProvider().getCurrentWorld() == null) {
return null;
}
return (ContainerMemory) baritone.getWorldProvider().getCurrentWorld().getContainerMemory();
}
private BlockPos neighboringConnectedBlock(BlockPos in) {
BlockStateInterface bsi = baritone.bsi;
Block block = bsi.get0(in).getBlock();
if (block != Blocks.TRAPPED_CHEST && block != Blocks.CHEST) {
return null; // other things that have contents, but can be placed adjacent without combining
}
for (int i = 0; i < 4; i++) {
BlockPos adj = in.offset(EnumFacing.byHorizontalIndex(i));
if (bsi.get0(adj).getBlock() == block) {
return adj;
}
}
return null;
}
/**
* An inventory that we are not yet fully aware of, but are expecting to exist at some point in the future.
*/
private static final class FutureInventory {
/**
* The time that we initially expected the inventory to be provided, in milliseconds
*/
private final long time;
/**
* The amount of slots in the inventory
*/
private final int slots;
/**
* The type of inventory
*/
private final String type;
/**
* The position of the inventory container
*/
private final BlockPos pos;
private FutureInventory(long time, int slots, String type, BlockPos pos) {
this.time = time;
this.slots = slots;
this.type = type;
this.pos = pos;
// betterblockpos has censoring
System.out.println("Future inventory created " + time + " " + slots + " " + type + " " + BetterBlockPos.from(pos));
}
}
public Optional<List<ItemStack>> echest() {
return Optional.ofNullable(getCurrent().contents).map(Collections::unmodifiableList);
}
public EnderChestMemory getCurrent() { public EnderChestMemory getCurrent() {
Path path = baritone.getWorldProvider().getCurrentWorld().directory; Path path = baritone.getWorldProvider().getCurrentWorld().directory;
return EnderChestMemory.getByServerAndPlayer(path.getParent(), ctx.player().getUniqueID()); return EnderChestMemory.getByServerAndPlayer(path.getParent(), ctx.player().getUniqueID());
+6 -6
View File
@@ -22,8 +22,8 @@ import baritone.utils.pathing.PathingBlockType;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.block.Blocks; import net.minecraft.init.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 BlockState[] overview; private final IBlockState[] 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, BlockState[] overview, Map<String, List<BlockPos>> specialBlockLocations, long cacheTimestamp) { CachedChunk(int x, int z, BitSet data, IBlockState[] 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 BlockState getBlock(int x, int y, int z, int dimension) { public final IBlockState 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 BlockState[] getOverview() { public final IBlockState[] 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.BlockState; import net.minecraft.block.state.IBlockState;
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 BlockState getBlock(int x, int y, int z) { public final IBlockState 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];
BlockState[][][] overview = new BlockState[32][32][]; IBlockState[][][] overview = new IBlockState[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 BlockState[256]; overview[x][z] = new IBlockState[256];
present[x][z] = true; present[x][z] = true;
break; break;
case CHUNK_NOT_PRESENT: case CHUNK_NOT_PRESENT:
+15 -15
View File
@@ -21,6 +21,8 @@ import baritone.api.utils.BlockUtils;
import baritone.pathing.movement.MovementHelper; import baritone.pathing.movement.MovementHelper;
import baritone.utils.pathing.PathingBlockType; import baritone.utils.pathing.PathingBlockType;
import net.minecraft.block.*; import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3d;
import net.minecraft.world.chunk.BlockStateContainer; import net.minecraft.world.chunk.BlockStateContainer;
@@ -29,8 +31,6 @@ 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<BlockState> bsc = extendedblockstorage.getData(); BlockStateContainer<IBlockState> 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);
BlockState state = bsc.get(x, y1, z); IBlockState 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);
BlockState[] blocks = new BlockState[256]; IBlockState[] blocks = new IBlockState[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] = getFromChunk(chunk, x, y, z); blocks[z << 4 | x] = chunk.getBlockState(x, y, z);
continue https; continue https;
} }
} }
@@ -103,10 +103,10 @@ public final class ChunkPacker {
} }
} }
// @formatter:on // @formatter:on
return new CachedChunk(chunk.getPos().x, chunk.getPos().z, bitSet, blocks, specialBlocks, System.currentTimeMillis()); return new CachedChunk(chunk.x, chunk.z, bitSet, blocks, specialBlocks, System.currentTimeMillis());
} }
private static PathingBlockType getPathingBlockType(BlockState state, Chunk chunk, int x, int y, int z) { private static PathingBlockType getPathingBlockType(IBlockState 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(getFromChunk(chunk, x + 1, y, z))) (x != 15 && MovementHelper.possiblyFlowing(chunk.getBlockState(x + 1, y, z)))
|| (x != 0 && MovementHelper.possiblyFlowing(getFromChunk(chunk, x - 1, y, z))) || (x != 0 && MovementHelper.possiblyFlowing(chunk.getBlockState(x - 1, y, z)))
|| (z != 15 && MovementHelper.possiblyFlowing(getFromChunk(chunk, x, y, z + 1))) || (z != 15 && MovementHelper.possiblyFlowing(chunk.getBlockState(x, y, z + 1)))
|| (z != 0 && MovementHelper.possiblyFlowing(getFromChunk(chunk, x, y, z - 1))) || (z != 0 && MovementHelper.possiblyFlowing(chunk.getBlockState(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.getPos().x << 4, y, z + chunk.getPos().z << 4)); Vec3d flow = state.getFluidState().getFlow(chunk.getWorld(), new BlockPos(x + chunk.x << 4, y, z + chunk.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 AirBlock || block instanceof TallGrassBlock || block instanceof DoublePlantBlock || block instanceof FlowerBlock) { if (block instanceof BlockAir || block instanceof BlockTallGrass || block instanceof BlockDoublePlant || block instanceof BlockFlower) {
return PathingBlockType.AIR; return PathingBlockType.AIR;
} }
return PathingBlockType.SOLID; return PathingBlockType.SOLID;
} }
public static BlockState pathingTypeToBlock(PathingBlockType type, int dimension) { public static IBlockState pathingTypeToBlock(PathingBlockType type, int dimension) {
switch (type) { switch (type) {
case AIR: case AIR:
return Blocks.AIR.getDefaultState(); return Blocks.AIR.getDefaultState();
+8 -4
View File
@@ -20,9 +20,11 @@ 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;
@@ -62,8 +64,10 @@ 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()) {
ServerWorld localServerWorld = integratedServer.getWorld(dimension); WorldServer localServerWorld = integratedServer.getWorld(dimension);
directory = dimension.getDirectory(localServerWorld.getSaveHandler().getWorldDirectory()); IChunkProviderServer provider = (IChunkProviderServer) localServerWorld.getChunkProvider();
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) {
@@ -74,7 +78,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.isConnectedToRealms() ? "realms" : mc.getCurrentServerData().serverIP; String folderName = mc.getCurrentServerData().serverIP;
if (SystemUtils.IS_OS_WINDOWS) { if (SystemUtils.IS_OS_WINDOWS) {
folderName = folderName.replace(":", "_"); folderName = folderName.replace(":", "_");
} }
+47 -32
View File
@@ -23,12 +23,13 @@ import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.BlockOptionalMetaLookup; import baritone.api.utils.BlockOptionalMetaLookup;
import baritone.api.utils.IPlayerContext; import baritone.api.utils.IPlayerContext;
import baritone.utils.accessor.IBlockStateContainer; import baritone.utils.accessor.IBlockStateContainer;
import net.minecraft.block.BlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.client.multiplayer.ClientChunkProvider; import net.minecraft.client.multiplayer.ChunkProviderClient;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkSection; import net.minecraft.world.chunk.ChunkSection;
import net.minecraft.world.chunk.IChunkProvider;
import java.util.*; import java.util.*;
import java.util.stream.IntStream; import java.util.stream.IntStream;
@@ -46,7 +47,8 @@ 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;
@@ -70,7 +72,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, null, false); Chunk chunk = chunkProvider.getChunk(chunkX, chunkZ, false, false);
if (chunk == null) { if (chunk == null) {
continue; continue;
} }
@@ -96,8 +98,8 @@ public enum WorldScanner implements IWorldScanner {
return Collections.emptyList(); return Collections.emptyList();
} }
ClientChunkProvider chunkProvider = (ClientChunkProvider) ctx.world().getChunkProvider(); ChunkProviderClient chunkProvider = (ChunkProviderClient) ctx.world().getChunkProvider();
Chunk chunk = chunkProvider.getChunk(pos.x, pos.z, null, false); Chunk chunk = chunkProvider.getChunk(pos.x, pos.z, false, false);
int playerY = ctx.playerFeet().getY(); int playerY = ctx.playerFeet().getY();
if (chunk == null || chunk.isEmpty()) { if (chunk == null || chunk.isEmpty()) {
@@ -109,23 +111,58 @@ public enum WorldScanner implements IWorldScanner {
return res; return res;
} }
@Override
public int repack(IPlayerContext ctx) {
return this.repack(ctx, 40);
}
@Override
public int repack(IPlayerContext ctx, int range) {
IChunkProvider chunkProvider = ctx.world().getChunkProvider();
ICachedWorld cachedWorld = ctx.worldData().getCachedWorld();
BetterBlockPos playerPos = ctx.playerFeet();
int playerChunkX = playerPos.getX() >> 4;
int playerChunkZ = playerPos.getZ() >> 4;
int minX = playerChunkX - range;
int minZ = playerChunkZ - range;
int maxX = playerChunkX + range;
int maxZ = playerChunkZ + range;
int queued = 0;
for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) {
Chunk chunk = chunkProvider.getChunk(x, z, false, false);
if (chunk != null && !chunk.isEmpty()) {
queued++;
cachedWorld.queueForPacking(chunk);
}
}
}
return queued;
}
private boolean scanChunkInto(int chunkX, int chunkZ, Chunk chunk, BlockOptionalMetaLookup filter, Collection<BlockPos> result, int max, int yLevelThreshold, int playerY, int[] coordinateIterationOrder) { private boolean scanChunkInto(int chunkX, int chunkZ, Chunk chunk, BlockOptionalMetaLookup filter, Collection<BlockPos> result, int max, int yLevelThreshold, int playerY, int[] coordinateIterationOrder) {
ChunkSection[] chunkInternalStorageArray = chunk.getSections(); ChunkSection[] chunkInternalStorageArray = chunk.getSections();
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 section = chunkInternalStorageArray[y0]; ChunkSection extendedblockstorage = chunkInternalStorageArray[y0];
if (section == null || ChunkSection.isEmpty(section)) { if (extendedblockstorage == null) {
continue; continue;
} }
int yReal = y0 << 4; int yReal = y0 << 4;
IBlockStateContainer bsc = (IBlockStateContainer) section.getData(); IBlockStateContainer bsc = (IBlockStateContainer) extendedblockstorage.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++) {
BlockState state = bsc.getAtPalette(storage[i]); IBlockState 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) {
@@ -145,26 +182,4 @@ public enum WorldScanner implements IWorldScanner {
} }
return foundWithinY; return foundWithinY;
} }
public int repack(IPlayerContext ctx) {
ClientChunkProvider chunkProvider = (ClientChunkProvider) ctx.world().getChunkProvider();
ICachedWorld cachedWorld = ctx.worldData().getCachedWorld();
BetterBlockPos playerPos = ctx.playerFeet();
int playerChunkX = playerPos.getX() >> 4;
int playerChunkZ = playerPos.getZ() >> 4;
int queued = 0;
for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) {
for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) {
Chunk chunk = chunkProvider.getChunk(x, z, null, false);
if (chunk != null && !chunk.isEmpty()) {
queued++;
cachedWorld.queueForPacking(chunk);
}
}
}
return queued;
}
} }
@@ -36,7 +36,7 @@ import baritone.command.argument.CommandArguments;
import baritone.command.manager.CommandManager; import baritone.command.manager.CommandManager;
import net.minecraft.util.Tuple; import net.minecraft.util.Tuple;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextComponentString;
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 StringTextComponent(String.format("> %s", toDisplay)); ITextComponent component = new TextComponentString(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 StringTextComponent("Click to rerun command") new TextComponentString("Click to rerun command")
)) ))
.setClickEvent(new ClickEvent( .setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND, ClickEvent.Action.RUN_COMMAND,
@@ -316,8 +316,7 @@ 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) {
e.printStackTrace(); throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName(), e);
throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName());
} }
} }
@@ -346,7 +345,7 @@ public class ArgConsumer implements IArgConsumer {
try { try {
return datatype.get(this.context); return datatype.get(this.context);
} catch (Exception e) { } catch (Exception e) {
throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName()); throw new CommandInvalidTypeException(hasAny() ? peek() : consumed(), datatype.getClass().getSimpleName(), e);
} }
} }
@@ -17,6 +17,7 @@
package baritone.command.defaults; package baritone.command.defaults;
import baritone.Baritone;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.utils.BetterBlockPos; import baritone.api.utils.BetterBlockPos;
import baritone.api.command.Command; import baritone.api.command.Command;
@@ -26,11 +27,11 @@ import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidStateException; import baritone.api.command.exception.CommandInvalidStateException;
import baritone.api.command.argument.IArgConsumer; import baritone.api.command.argument.IArgConsumer;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import org.apache.commons.io.FilenameUtils;
import java.io.File; import java.io.File;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.stream.Stream; import java.util.stream.Stream;
public class BuildCommand extends Command { public class BuildCommand extends Command {
@@ -44,8 +45,8 @@ public class BuildCommand extends Command {
@Override @Override
public void execute(String label, IArgConsumer args) throws CommandException { public void execute(String label, IArgConsumer args) throws CommandException {
File file = args.getDatatypePost(RelativeFile.INSTANCE, schematicsDir).getAbsoluteFile(); File file = args.getDatatypePost(RelativeFile.INSTANCE, schematicsDir).getAbsoluteFile();
if (!file.getName().toLowerCase(Locale.US).endsWith(".schematic")) { if (FilenameUtils.getExtension(file.getAbsolutePath()).isEmpty()) {
file = new File(file.getAbsolutePath() + ".schematic"); file = new File(file.getAbsolutePath() + "." + Baritone.settings().schematicFallbackExtension);
} }
BetterBlockPos origin = ctx.playerFeet(); BetterBlockPos origin = ctx.playerFeet();
BetterBlockPos buildOrigin; BetterBlockPos buildOrigin;
@@ -1,61 +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.command.defaults;
import baritone.api.IBaritone;
import baritone.api.command.Command;
import baritone.api.command.exception.CommandException;
import baritone.api.command.argument.IArgConsumer;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class CancelCommand extends Command {
public CancelCommand(IBaritone baritone) {
super(baritone, "cancel", "stop");
}
@Override
public void execute(String label, IArgConsumer args) throws CommandException {
args.requireMax(0);
baritone.getPathingBehavior().cancelEverything();
logDirect("ok canceled");
}
@Override
public Stream<String> tabComplete(String label, IArgConsumer args) {
return Stream.empty();
}
@Override
public String getShortDesc() {
return "Cancel what Baritone is currently doing";
}
@Override
public List<String> getLongDesc() {
return Arrays.asList(
"The cancel command tells Baritone to stop whatever it's currently doing.",
"",
"Usage:",
"> cancel"
);
}
}
@@ -24,7 +24,8 @@ import java.util.*;
public final class DefaultCommands { public final class DefaultCommands {
private DefaultCommands() {} private DefaultCommands() {
}
public static List<ICommand> createAll(IBaritone baritone) { public static List<ICommand> createAll(IBaritone baritone) {
Objects.requireNonNull(baritone); Objects.requireNonNull(baritone);
@@ -43,7 +44,6 @@ public final class DefaultCommands {
new SchematicaCommand(baritone), new SchematicaCommand(baritone),
new ComeCommand(baritone), new ComeCommand(baritone),
new AxisCommand(baritone), new AxisCommand(baritone),
new CancelCommand(baritone),
new ForceCancelCommand(baritone), new ForceCancelCommand(baritone),
new GcCommand(baritone), new GcCommand(baritone),
new InvertCommand(baritone), new InvertCommand(baritone),
@@ -66,10 +66,11 @@ public final class DefaultCommands {
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)
)); ));
PauseResumeCommands prc = new PauseResumeCommands(baritone); ExecutionControlCommands prc = new ExecutionControlCommands(baritone);
commands.add(prc.pauseCommand); commands.add(prc.pauseCommand);
commands.add(prc.resumeCommand); commands.add(prc.resumeCommand);
commands.add(prc.pausedCommand); commands.add(prc.pausedCommand);
commands.add(prc.cancelCommand);
return Collections.unmodifiableList(commands); return Collections.unmodifiableList(commands);
} }
} }
@@ -18,13 +18,13 @@
package baritone.command.defaults; package baritone.command.defaults;
import baritone.api.IBaritone; import baritone.api.IBaritone;
import baritone.api.command.Command;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidStateException;
import baritone.api.process.IBaritoneProcess; import baritone.api.process.IBaritoneProcess;
import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType; import baritone.api.process.PathingCommandType;
import baritone.api.command.Command;
import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidStateException;
import baritone.api.command.argument.IArgConsumer;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@@ -37,13 +37,14 @@ import java.util.stream.Stream;
* TO USE THIS to pause and resume Baritone. Make your own process that returns {@link PathingCommandType#REQUEST_PAUSE * TO USE THIS to pause and resume Baritone. Make your own process that returns {@link PathingCommandType#REQUEST_PAUSE
* REQUEST_PAUSE} as needed. * REQUEST_PAUSE} as needed.
*/ */
public class PauseResumeCommands { public class ExecutionControlCommands {
Command pauseCommand; Command pauseCommand;
Command resumeCommand; Command resumeCommand;
Command pausedCommand; Command pausedCommand;
Command cancelCommand;
public PauseResumeCommands(IBaritone baritone) { public ExecutionControlCommands(IBaritone baritone) {
// array for mutability, non-field so reflection can't touch it // array for mutability, non-field so reflection can't touch it
final boolean[] paused = {false}; final boolean[] paused = {false};
baritone.getPathingControlManager().registerProcess( baritone.getPathingControlManager().registerProcess(
@@ -64,7 +65,8 @@ public class PauseResumeCommands {
} }
@Override @Override
public void onLostControl() {} public void onLostControl() {
}
@Override @Override
public double priority() { public double priority() {
@@ -169,5 +171,36 @@ public class PauseResumeCommands {
); );
} }
}; };
cancelCommand = new Command(baritone, "cancel", "stop") {
@Override
public void execute(String label, IArgConsumer args) throws CommandException {
args.requireMax(0);
if (paused[0]) {
paused[0] = false;
}
baritone.getPathingBehavior().cancelEverything();
logDirect("ok canceled");
}
@Override
public Stream<String> tabComplete(String label, IArgConsumer args) {
return Stream.empty();
}
@Override
public String getShortDesc() {
return "Cancel what Baritone is currently doing";
}
@Override
public List<String> getLongDesc() {
return Arrays.asList(
"The cancel command tells Baritone to stop whatever it's currently doing.",
"",
"Usage:",
"> cancel"
);
}
};
} }
} }
@@ -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.Registry; import net.minecraft.util.registry.IRegistry;
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(
Registry.BLOCK.getKey(block).getPath(), IRegistry.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.LivingEntity; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.IRegistry;
import java.util.*; import java.util.*;
import java.util.function.Predicate; import java.util.function.Predicate;
@@ -64,11 +64,10 @@ 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 -> e.getType().equals(c)) : e -> classes.stream().anyMatch(c -> c.getEntityClass().isInstance(e))
); );
} }
if (group != null) { if (group != null) {
@@ -81,7 +80,7 @@ public class FollowCommand extends Command {
.forEach(this::logDirect); .forEach(this::logDirect);
} else { } else {
classes.stream() classes.stream()
.map(Registry.ENTITY_TYPE::getKey) .map(IRegistry.ENTITY_TYPE::getKey)
.map(Objects::requireNonNull) .map(Objects::requireNonNull)
.map(ResourceLocation::toString) .map(ResourceLocation::toString)
.forEach(this::logDirect); .forEach(this::logDirect);
@@ -133,8 +132,8 @@ public class FollowCommand extends Command {
} }
private enum FollowGroup { private enum FollowGroup {
ENTITIES(LivingEntity.class::isInstance), ENTITIES(EntityLiving.class::isInstance),
PLAYERS(PlayerEntity.class::isInstance); /* , PLAYERS(EntityPlayer.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;
@@ -41,9 +41,13 @@ public class GotoCommand extends Command {
@Override @Override
public void execute(String label, IArgConsumer args) throws CommandException { public void execute(String label, IArgConsumer args) throws CommandException {
if (args.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) != null) { // if we have a numeric first argument... // If we have a numeric first argument, then parse arguments as coordinates.
// Note: There is no reason to want to go where you're already at so there
// is no need to handle the case of empty arguments.
if (args.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) != null) {
args.requireMax(3);
BetterBlockPos origin = baritone.getPlayerContext().playerFeet(); BetterBlockPos origin = baritone.getPlayerContext().playerFeet();
Goal goal = args.getDatatypePostOrNull(RelativeGoal.INSTANCE, origin); Goal goal = args.getDatatypePost(RelativeGoal.INSTANCE, origin);
logDirect(String.format("Going to: %s", goal.toString())); logDirect(String.format("Going to: %s", goal.toString()));
baritone.getCustomGoalProcess().setGoalAndPath(goal); baritone.getCustomGoalProcess().setGoalAndPath(goal);
return; return;
@@ -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.StringTextComponent; import net.minecraft.util.text.TextComponentString;
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 StringTextComponent(" - " + command.getShortDesc()); ITextComponent shortDescComponent = new TextComponentString(" - " + command.getShortDesc());
shortDescComponent.getStyle().setColor(TextFormatting.DARK_GRAY); shortDescComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
ITextComponent namesComponent = new StringTextComponent(names); ITextComponent namesComponent = new TextComponentString(names);
namesComponent.getStyle().setColor(TextFormatting.WHITE); namesComponent.getStyle().setColor(TextFormatting.WHITE);
ITextComponent hoverComponent = new StringTextComponent(""); ITextComponent hoverComponent = new TextComponentString("");
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 StringTextComponent(name); ITextComponent component = new TextComponentString(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 StringTextComponent("Click to return to the help menu"); ITextComponent returnComponent = new TextComponentString("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.ForDirection; import baritone.api.command.datatypes.ForEnumFacing;
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.block.Blocks; import net.minecraft.init.Blocks;
import net.minecraft.util.Direction; import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i; import net.minecraft.util.math.Vec3i;
@@ -165,7 +165,7 @@ public class SelCommand extends Command {
if (transformTarget == null) { if (transformTarget == null) {
throw new CommandInvalidStateException("Invalid transform type"); throw new CommandInvalidStateException("Invalid transform type");
} }
Direction direction = args.getDatatypeFor(ForDirection.INSTANCE); EnumFacing direction = args.getDatatypeFor(ForEnumFacing.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(ForDirection.INSTANCE); return args.tabCompleteDatatype(ForEnumFacing.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.StringTextComponent; import net.minecraft.util.text.TextComponentString;
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 StringTextComponent(String.format( ITextComponent typeComponent = new TextComponentString(String.format(
" (%s)", " (%s)",
settingTypeToString(setting) settingTypeToString(setting)
)); ));
typeComponent.getStyle().setColor(TextFormatting.DARK_GRAY); typeComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
ITextComponent hoverComponent = new StringTextComponent(""); ITextComponent hoverComponent = new TextComponentString("");
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 StringTextComponent(setting.getName()); ITextComponent component = new TextComponentString(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 StringTextComponent(String.format("Old value: %s", oldValue)); ITextComponent oldValueComponent = new TextComponentString(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 StringTextComponent("Click to set the setting back to this value") new TextComponentString("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.StringTextComponent; import net.minecraft.util.text.TextComponentString;
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 StringTextComponent(""); ITextComponent component = new TextComponentString("");
ITextComponent tagComponent = new StringTextComponent(waypoint.getTag().name() + " "); ITextComponent tagComponent = new TextComponentString(waypoint.getTag().name() + " ");
tagComponent.getStyle().setColor(TextFormatting.GRAY); tagComponent.getStyle().setColor(TextFormatting.GRAY);
String name = waypoint.getName(); String name = waypoint.getName();
ITextComponent nameComponent = new StringTextComponent(!name.isEmpty() ? name : "<empty>"); ITextComponent nameComponent = new TextComponentString(!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 StringTextComponent(" @ " + new Date(waypoint.getCreationTimestamp())); ITextComponent timestamp = new TextComponentString(" @ " + 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 StringTextComponent("Click to select") new TextComponentString("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 StringTextComponent("Waypoint added: "); ITextComponent component = new TextComponentString("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 StringTextComponent("Click to delete this waypoint"); ITextComponent deleteComponent = new TextComponentString("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 StringTextComponent("Click to set goal to this waypoint"); ITextComponent goalComponent = new TextComponentString("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 StringTextComponent("Click to return to the waypoints list"); ITextComponent backComponent = new TextComponentString("Click to return to the waypoints list");
backComponent.getStyle().setClickEvent(new ClickEvent( backComponent.getStyle().setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND, ClickEvent.Action.RUN_COMMAND,
String.format( String.format(
@@ -51,7 +51,6 @@ 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 {
@@ -90,7 +89,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(), null, false) != null; && world.getChunkProvider().getChunk(event.getX(), event.getZ(), false, false) != null;
if (isPostPopulate || isPreUnload) { if (isPostPopulate || isPreUnload) {
baritone.getWorldProvider().ifWorldLoaded(worldData -> { baritone.getWorldProvider().ifWorldLoaded(worldData -> {
@@ -25,12 +25,12 @@ import baritone.utils.BlockStateInterface;
import baritone.utils.ToolSet; import baritone.utils.ToolSet;
import baritone.utils.pathing.BetterWorldBorder; import baritone.utils.pathing.BetterWorldBorder;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.InventoryPlayer;
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;
ClientPlayerEntity player = baritone.getPlayerContext().player(); EntityPlayerSP 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 && PlayerInventory.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.getDimension().isNether(); this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.value && InventoryPlayer.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 BlockState get(int x, int y, int z) { public IBlockState 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 BlockState get(BlockPos pos) { public IBlockState 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, BlockState current) { public double costOfPlacingAt(int x, int y, int z, IBlockState 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, BlockState current) { public double breakCostMultiplierAt(int x, int y, int z, IBlockState current) {
if (!allowBreak) { if (!allowBreak) {
return COST_INF; return COST_INF;
} }

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