Compare commits

...

146 Commits

Author SHA1 Message Date
Leijurv
89fb5cecd5 v1.2.4 2019-03-13 18:15:21 -07:00
Leijurv
a75317cc2c workaround some scuff 2019-03-13 09:17:25 -07:00
Leijurv
ee6df270ce relative coordinates 2019-03-13 08:50:04 -07:00
Leijurv
e09541151f update clients 2019-03-12 23:29:08 -07:00
Leijurv
74e0552be0 unscuff water, thanks wwe 2019-03-12 23:10:06 -07:00
Leijurv
909ab553eb small cleanup 2019-03-12 22:08:17 -07:00
Leijurv
866408aece rename 2019-03-12 19:17:50 -07:00
Leijurv
2215f170df Merge branch 'builder' 2019-03-12 19:16:40 -07:00
Leijurv
a5601fd89a nutty 2019-03-12 18:59:20 -07:00
Leijurv
fa8f2632f5 dont jump while breaking 2019-03-12 18:58:35 -07:00
Leijurv
52d8d271f1 fix a meme with a path ending in water 2019-03-12 16:18:48 -07:00
Leijurv
b240e8420a whoops 2019-03-12 15:53:00 -07:00
Leijurv
25024b58de fix a bunch of scuff 2019-03-12 15:52:40 -07:00
Leijurv
ba31d209c9 except what if it compiled 2019-03-11 23:29:39 -07:00
Leijurv
7974d9135b Merge branch 'master' into builder 2019-03-11 23:26:05 -07:00
Leijurv
a5a795a22c lower case ok 2019-03-11 22:21:35 -07:00
Leijurv
416b5b66d2 break fewer beds 2019-03-11 20:57:46 -07:00
Leijurv
88e41f37b1 explain whats happening 2019-03-11 20:08:52 -07:00
Leijurv
7cfa837604 blacklistClosestOnFailure 2019-03-11 20:06:19 -07:00
Leijurv
6b7aca3081 force revalidate on control change 2019-03-11 19:23:41 -07:00
Leijurv
580af2ab06 processes tied in priority 2019-03-11 18:24:31 -07:00
Leijurv
d144d30890 crucial clarification 2019-03-10 23:43:00 -07:00
Leijurv
ecac546c6d actually trolling is fine 2019-03-09 23:15:03 -08:00
Leijurv
76297e8176 add click to usage 2019-03-08 08:43:28 -08:00
Leijurv
d90f391b5e 7 lmao 2019-03-07 18:18:31 -08:00
Leijurv
d80ae57964 disconnect on arrival 2019-03-06 22:44:57 -08:00
Leijurv
74d7483b3c explore 2019-03-05 12:26:52 -08:00
Leijurv
b3c580e657 teensy javadoc 2019-03-04 21:49:21 -08:00
Leijurv
8050b69f2f no more .get 😎 2019-03-04 21:30:04 -08:00
Leijurv
459720c348 eh actually lets do the whole render distance! 2019-03-04 21:21:02 -08:00
Leijurv
a73f5c1359 crapton of performance improvements 2019-03-04 21:20:13 -08:00
Leijurv
71cb0f6d36 fix a weird way of getting stuck on a ladder 2019-03-04 21:00:41 -08:00
Leijurv
0d15225b1d dont construct one unlesss we need to 2019-03-04 21:00:30 -08:00
Leijurv
826f3788d0 performance improvement and no allocation promise 2019-03-04 20:39:22 -08:00
Leijurv
2133ab39b7 better cache, needs more testing 2019-03-04 19:44:36 -08:00
Leijurv
558c14a375 little cleanup 2019-03-04 13:11:36 -08:00
Leijurv
882ac41291 player coords 2019-03-04 11:28:41 -08:00
Leijurv
66c7a3f513 this is really bad 2019-03-03 21:29:31 -08:00
Leijurv
5904441a7e ❤️ code of conduct 2019-03-02 22:40:42 -08:00
Leijurv
c465228531 consistency with the previously existing anime policy 2019-03-02 21:44:20 -08:00
Leijurv
81b22019dd Create CODE_OF_CONDUCT.md 2019-03-02 21:43:18 -08:00
Leijurv
3e47d485f9 emphasize and clarify lol 2019-03-01 12:11:47 -08:00
Leijurv
701bc772a8 update impcat badge 2019-03-01 11:22:21 -08:00
Leijurv
3ae05b7348 worldedit 2019-02-28 15:26:09 -08:00
Leijurv
2e186019f5 Merge branch 'master' into builder 2019-02-28 12:32:29 -08:00
Leijurv
4c6f321cff clarify 2019-02-28 12:12:16 -08:00
Leijurv
c72eb3e195 v1.2.3 2019-02-28 09:47:47 -08:00
Leijurv
a4237bf1f9 tentative fix to descend, needs testing 2019-02-27 23:04:43 -08:00
Leijurv
e767e34b92 well that was stupid, thanks thesmarttheorist 2019-02-27 22:15:54 -08:00
Leijurv
8ac82ebe2a v1.2.2 2019-02-27 17:48:57 -08:00
Leijurv
0ed6ccab71 update some documentation 2019-02-27 15:46:28 -08:00
Leijurv
bf25d7328e revalidate on goal update too 2019-02-27 12:23:05 -08:00
Leijurv
a47b0c0581 rendering cleanup, fixes #317 2019-02-27 12:00:39 -08:00
Leijurv
596849c7e6 i am rarted 2019-02-26 19:51:20 -08:00
Leijurv
76914b7859 awesome 2019-02-26 19:50:35 -08:00
Leijurv
3dbbe053d7 teensy change 2019-02-26 19:45:20 -08:00
Brady
c474cdb1f8 Working clicking goals 2019-02-26 21:41:08 -06:00
Leijurv
3de02cbf21 brady save me idk how to gl 2019-02-26 18:34:11 -08:00
Brady
26fefc70f0 Better update the badges 2019-02-26 17:29:50 -06:00
Brady
4086c9f4b5 Implement secondary license conditioning
Sorry fellas, no anime in this town.
2019-02-26 17:25:30 -06:00
Leijurv
c947c77853 goodbye mc.objectMouseOver 2019-02-26 15:07:01 -08:00
Leijurv
9be44c0371 placement without unepic right click 2019-02-26 14:57:44 -08:00
Leijurv
5412fa6cfd cursed flowing 2019-02-25 20:35:06 -08:00
Leijurv
6e7320b954 v1.2.1 2019-02-25 18:07:55 -08:00
Leijurv
fbb2d37634 allow placing against replacable blocks 2019-02-25 18:01:11 -08:00
Leijurv
7afe16fc10 dont reset every tick 2019-02-25 16:26:17 -08:00
Leijurv
b19f241d81 override for the first tick 2019-02-25 15:06:55 -08:00
Leijurv
583ce80003 not reliable enough with jesus to jump from water over a gap 2019-02-24 13:57:33 -08:00
Leijurv
195c33407e cant walk through heads 2019-02-24 13:43:53 -08:00
Leijurv
600c5b77ad v1.2.0 2019-02-23 20:43:29 -08:00
Leijurv
f1084fab76 come 2019-02-23 20:33:00 -08:00
Brady
bd65e32407 Fix the failing build 2019-02-23 17:04:14 -06:00
Leijurv
e4416f424a interesting 2019-02-23 14:13:27 -08:00
Leijurv
73ec110b22 not every player is a baritone 2019-02-23 14:03:47 -08:00
Brady
0bce801a3f Minor javadoc changes 2019-02-23 14:32:10 -06:00
Brady
e8e00e8dfb CRLF -> LF
It was inconsistent across the board
2019-02-23 12:27:24 -06:00
Leijurv
cc4335e48e better links 2019-02-22 23:32:23 -08:00
Leijurv
5427911da3 only api in javadoc i guess 2019-02-22 23:29:08 -08:00
Brady
c808d5a42d Small build.gradle cleanup and README update 2019-02-22 18:12:04 -06:00
Leijurv
3b46dbd6a1 appease codacy 2019-02-22 14:05:29 -08:00
Leijurv
e63b2f1bf1 unused arg 2019-02-22 13:58:03 -08:00
Leijurv
d32e822057 settings overhaul 2019-02-22 12:13:19 -08:00
Leijurv
2b672998e1 fix two weird ways of getting stuck 2019-02-21 14:24:23 -08:00
Leijurv
e18dc7c7e7 Merge branch 'master' into builder 2019-02-21 11:28:13 -08:00
Leijurv
16dcd2f44d blocks on top of chests, fixes #299 2019-02-21 11:25:03 -08:00
Leijurv
eb9f755b54 disable rendercachedchunks in singleplayer, fixes #331 2019-02-21 10:03:03 -08:00
Leijurv
29a9e6e1d1 fine, forward alias to thisway 2019-02-21 09:45:01 -08:00
Leijurv
1f52f706ed should fix anticheatcompat off on forge 2019-02-20 23:41:29 -08:00
Leijurv
bf12763a10 fix a bunch of bugs with placement 2019-02-20 08:08:52 -08:00
Leijurv
963641a818 trim big schematics 2019-02-19 22:50:03 -08:00
Leijurv
3e94d92fbd Merge branch 'master' into builder 2019-02-19 22:33:19 -08:00
Leijurv
a72040f83d imagine breaking the build 2019-02-19 19:52:11 -08:00
Leijurv
84d8f826ff fine lol, fixes #340 2019-02-19 19:41:26 -08:00
Brady
70d216b29f Fix renderGoalXZBeacon path rendering incorrect color 2019-02-19 21:00:14 -06:00
Leijurv
66356d5334 hmm 2019-02-19 18:27:05 -08:00
Leijurv
d9625dfe78 no longer needed crab rave 2019-02-19 18:24:12 -08:00
Leijurv
6d847577d8 somehow missed those 2019-02-19 18:22:59 -08:00
Leijurv
8fd687f9d7 more usage help 2019-02-19 15:04:18 -08:00
Leijurv
f7a9380b9d v1.1.6 2019-02-19 14:53:43 -08:00
Leijurv
5617c595b2 public init 2019-02-19 14:43:48 -08:00
Leijurv
8770524679 fix weird angle forcing behavior, fixes #341 2019-02-19 14:29:08 -08:00
Leijurv
a8ddb2fcf1 also disallow while breaking 2019-02-19 13:28:58 -08:00
Leijurv
76c4ca9ba6 fix path reliability after lateral movement 2019-02-19 12:55:58 -08:00
Leijurv
ed2b0f0bb9 fix jump before place ascend 2019-02-19 12:44:29 -08:00
Leijurv
6702b44b3e reformatted and fixed stuck on break fall 2019-02-19 12:43:44 -08:00
Leijurv
c486d8241e continue 2019-02-19 07:53:36 -08:00
Leijurv
d2bb8c374e explain 2019-02-18 21:18:37 -08:00
Leijurv
530cecea5b it flows better this way 2019-02-17 21:41:54 -08:00
Leijurv
266e2dada9 cleanup 2019-02-16 20:49:38 -08:00
Leijurv
ce73d34627 Merge branch 'master' into builder 2019-02-16 20:49:07 -08:00
Leijurv
d8348ad292 Merge branch 'master' into builder 2019-02-07 14:11:26 -08:00
Leijurv
299540725e a start on inventory movement 2019-02-07 13:59:37 -08:00
Leijurv
0ef08142fd trim spaces from schematic name 2019-02-07 13:12:44 -08:00
Leijurv
8694d926c4 remove unneeded printouts 2019-02-07 10:45:51 -08:00
Leijurv
4c4bce3561 define origin 2019-02-06 22:10:52 -08:00
Leijurv
68e8717b5c Merge branch 'master' into builder 2019-02-06 21:05:14 -08:00
Leijurv
a822d3ef05 horrifying placement 2019-02-06 16:22:40 -08:00
Leijurv
311cf81e8a Merge branch 'master' into builder 2019-02-06 12:54:03 -08:00
Leijurv
5fb8a1d3d1 Merge branch 'master' into builder 2019-01-29 19:58:51 -08:00
Leijurv
306bd18a40 Merge branch 'master' into builder 2019-01-29 19:47:36 -08:00
Leijurv
847181ada4 Merge branch 'master' into builder 2019-01-24 21:00:52 -08:00
Leijurv
1c1fbe83ec idk lol 2019-01-19 22:12:54 -08:00
Leijurv
ccd56e0368 Merge branch 'master' into builder 2019-01-19 16:36:42 -08:00
Leijurv
cef88cde20 epic super 2019-01-17 12:25:48 -08:00
Brady
aa3833915b Repackage schematic implementations 2019-01-16 13:45:32 -06:00
Brady
0c0bbeff27 Minor AirSchematic access modifier change 2019-01-16 12:39:15 -06:00
Brady
ceda14096c Builder Process API exposure
Professional style 💪
2019-01-15 22:07:06 -06:00
Leijurv
d5b393d6bd area clear 2019-01-14 21:41:40 -08:00
Leijurv
e2cdd6a7f9 builder with multiple materials 2019-01-14 19:49:26 -08:00
Leijurv
261d02e67b Merge branch 'master' into builder 2019-01-14 13:01:25 -08:00
Leijurv
a6ce4694fc hotbar selection uwu 2019-01-12 19:51:21 -08:00
Leijurv
14bc65468a tweaks 2019-01-11 10:02:21 -08:00
Leijurv
56d109bf0a Merge pull request #310 from babbaj/builder
make code easy to understand
2019-01-11 10:00:54 -08:00
babbaj
a965859095 make code easy to understand 2019-01-11 01:13:14 -05:00
Leijurv
863ae447b9 except we actually make it work 2019-01-10 18:15:05 -08:00
Leijurv
4dd922f1b5 Merge branch 'master' into builder 2019-01-10 17:27:23 -08:00
Leijurv
f95dc40f4c consolidate triple duplicated placement code 2019-01-10 17:23:20 -08:00
Leijurv
81786f7a7c reuse calculationcontext for planning ahead next segment 2019-01-10 13:51:26 -08:00
Leijurv
1381d8d94c two small tweaks 2019-01-10 13:50:53 -08:00
Leijurv
1dca02517e disable backtrack cost favoring while building 2019-01-09 15:42:49 -08:00
Leijurv
b109fc7420 fun =) 2019-01-09 15:07:06 -08:00
Leijurv
c74c01271d better strategy 2019-01-09 14:36:44 -08:00
Leijurv
702b916948 preliminary schematic stuff 2019-01-08 20:45:02 -08:00
Leijurv
8ed2431f37 Merge branch 'master' into builder 2019-01-08 14:56:48 -08:00
Leijurv
c45cbebcce fixed 2018-12-27 08:06:10 -10:00
Leijurv
251110c4f8 the start of something big 2018-12-25 21:07:17 -08:00
92 changed files with 3173 additions and 1503 deletions

78
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,78 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* No Anime
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* Anime
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* ~~Trolling, insulting/derogatory comments, and personal or political attacks~~
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at complaints@leijurv.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

View File

@@ -4,7 +4,7 @@
- **Block breaking** Baritone considers breaking blocks as part of its path. It also takes into account your current tool set and hot bar. For example, if you have a Eff V diamond pick, it may choose to mine through a stone barrier, while if you only had a wood pick it might be faster to climb over it.
- **Block placing** Baritone considers placing blocks as part of its path. This includes sneak-back-placing, pillaring, etc. It has a configurable penalty of placing a block (set to 1 second by default), to conserve its resources. The list of acceptable throwaway blocks is also configurable, and is cobble, dirt, or netherrack by default. <a href="https://www.youtube.com/watch?v=F6FbI1L9UmU">Example</a>
- **Falling** Baritone will fall up to 3 blocks onto solid ground (configurable, if you have Feather Falling and/or don't mind taking a little damage). If you have a water bucket on your hotbar, it will fall up to 23 blocks and place the bucket beneath it. It will fall an unlimited distance into existing still water.
- **Vines and ladders** Baritone understands how to climb and descend vines and ladders. There is experimental support for more advanced maneuvers, like strafing to a different ladder / vine column in midair (off by default, setting named `allowVines`).
- **Vines and ladders** Baritone understands how to climb and descend vines and ladders. There is experimental support for more advanced maneuvers, like strafing to a different ladder / vine column in midair (off by default, setting named `allowVines`). Baritone can break its fall by grabbing ladders / vines midair, and understands when that is and isn't possible.
- **Opening fence gates and doors**
- **Slabs and stairs**
- **Falling blocks** Baritone understands the costs of breaking blocks with falling blocks on top, and includes all of their break costs. Additionally, since it avoids breaking any blocks touching a liquid, it won't break the bottom of a gravel stack below a lava lake (anymore).

View File

@@ -1,90 +0,0 @@
# Integration between Baritone and Impact
Impact 4.4 has Baritone included.
These instructions apply to Impact 4.3.
For Forge follow the instructions in [Setup](SETUP.md).
To run Baritone on Vanilla, just follow the instructions in the README (it's `./gradlew runClient`).
## An Introduction
There are some basic steps to getting Baritone setup with Impact.
- Acquiring a build of Baritone
- Placing Baritone in the libraries directory
- Modifying the Impact Profile JSON to run baritone
- How to use Baritone
## Acquiring a build of Baritone
There are two methods of acquiring a build of Baritone
### Official Release (Not always up to date)
https://github.com/cabaletta/baritone/releases
For Impact 4.3, there is no Baritone integration yet, so you will want `baritone-standalone-X.Y.Z.jar`. **For the rest of this guide, replace `X.Y.Z` with the actual numeric version you are using.**
Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`.
The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone .` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too).
### Building Baritone yourself
You can either build Baritone through a command line or through IntelliJ's UI, information on that can be found [here](SETUP.md#building).
## Placing Baritone in the libraries directory
``/libraries`` is a neat directory in your <a href="https://minecraft.gamepedia.com/.minecraft">Minecraft Installation Directory</a>
that contains all of the dependencies that are required from the game and some mods. This is where we will be
putting baritone.
- Locate the ``libraries`` folder, it should be in the Minecraft Installation Directory
- Create 3 new subdirectories starting from ``libraries``
- ``cabaletta``
- ``baritone``
- ``X.Y.Z``
- Copy the build of Baritone that was acquired earlier, and place it into the ``X.Y.Z`` folder, renamed like so:
- The full path should look like ``<Minecraft>/libraries/cabaletta/baritone/X.Y.Z/baritone-X.Y.Z.jar``
## Modifying the Impact Profile JSON to run baritone
The final step is "registering" the Baritone library with Impact, so that it loads on launch.
- Ensure your Minecraft launcher is closed
- Navigate back to the Minecraft Installation Directory
- Find the ``versions`` directory, and open in
- In here there should be a ``1.12.2-Impact_4.3`` folder.
- If you don't have any Impact folder or have a version older than 4.3, you can download Impact <a href="https://impactdevelopment.github.io">here</a>.
- Open the folder and inside there should be a file called ``1.12.2-Impact_4.3.json``
- Open the JSON file with a text editor that supports your system's line endings
- For example, Notepad on Windows likely will NOT work for this. You should instead use a Text Editor like
<a href="https://notepad-plus-plus.org/">Notepad++</a> if you're on Windows. (For other systems, I'm not sure
what would work the best so you may have to do some research.)
- Find the ``libraries`` array in the JSON. It should look something like this.
```
"libraries": [
{
"name": "net.minecraft:launchwrapper:1.12"
},
{
"name": "com.github.ImpactDevelopment:Impact:4.3-1.12.2",
"url": "https://impactdevelopment.github.io/maven/"
},
{
"name": "com.github.ImpactDeveloment:ClientAPI:3.0.2",
"url": "https://impactdevelopment.github.io/maven/"
},
...
```
- Create two new objects in the array, between the ``Impact`` and ``ClientAPI`` dependencies preferably.
```
{
"name": "cabaletta:baritone:X.Y.Z"
},
{
"name": "com.github.ImpactDevelopment:SimpleTweaker:1.2",
"url": "https://impactdevelopment.github.io/maven/"
},
```
- Now find the ``"minecraftArguments": "..."`` text near the top.
- At the very end of the quotes where it says ``--tweakClass clientapi.load.ClientTweaker"``, add on the following so it looks like:
- ``--tweakClass clientapi.load.ClientTweaker --tweakClass baritone.launch.BaritoneTweaker"``
- If you didn't close your launcher for this step, restart it now.
- You can now launch Impact 4.3 as normal, and Baritone should start up
## How to use Baritone
- [Baritone chat control usage](USAGE.md)

BIN
LICENSE-Part-2.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

@@ -1,9 +1,10 @@
# Baritone
[![Build Status](https://travis-ci.com/cabaletta/baritone.svg?branch=master)](https://travis-ci.com/cabaletta/baritone)
[![Release](https://img.shields.io/github/release/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/releases)
[![License](https://img.shields.io/badge/license-LGPL--3.0-green.svg)](LICENSE)
[![License](https://img.shields.io/badge/license-LGPL--3.0%20with%20anime%20exception-green.svg)](LICENSE)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/a73d037823b64a5faf597a18d71e3400)](https://www.codacy.com/app/leijurv/baritone?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=cabaletta/baritone&amp;utm_campaign=Badge_Grade)
[![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone)
[![Code of Conduct](https://img.shields.io/badge/%E2%9D%A4-code%20of%20conduct-blue.svg?style=flat)](https://github.com/cabaletta/baritone/blob/master/CODE_OF_CONDUCT.md)
[![Known Vulnerabilities](https://snyk.io/test/github/cabaletta/baritone/badge.svg?targetFile=build.gradle)](https://snyk.io/test/github/cabaletta/baritone?targetFile=build.gradle)
[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/cabaletta/baritone/issues)
[![Issues](https://img.shields.io/github/issues/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues/)
@@ -16,10 +17,9 @@
[![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://minecraft.gamepedia.com/1.12.2)
[![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/)
[![Asuna integration](https://img.shields.io/badge/Asuna%20integration-builder%20branch-brightgreen.svg)](https://github.com/EmotionalLove/Asuna/)
[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.0.0--hotfix--4-green.svg)](https://impactdevelopment.github.io/)
[![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-orange.svg)](https://github.com/zeroeightysix/KAMI/)
[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-v1.0.0%3F%3F%20smh%20license%20violations-orange.svg)](https://wweclient.com/)
[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.3-brightgreen.svg)](https://impactdevelopment.github.io/)
[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/)
[![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-red.svg)](https://github.com/zeroeightysix/KAMI/)
[![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/)
[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20integration-Soon™-red.svg)](https://github.com/fr1kin/ForgeHax)
@@ -28,29 +28,33 @@ A Minecraft pathfinder bot.
Baritone is the pathfinding system used in [Impact](https://impactdevelopment.github.io/) since 4.4. There's a [showcase video](https://www.youtube.com/watch?v=yI8hgW_m6dQ) made by @Adovin#3153 on Baritone's integration into Impact. [Here's](https://www.youtube.com/watch?v=StquF69-_wI) a video I made showing off what it can do.
This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/),
the original version of the bot for Minecraft 1.8, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths).
the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2. Baritone focuses on reliability and particularly performance (it's over [30x faster](https://github.com/cabaletta/baritone/pull/180#issuecomment-423822928) than MineBot at calculating paths).
Have committed at least once a day for the last 6 months =D 🦀
Have committed at least once a day for the last 7 months =D 🦀
1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2
# Getting Started
Here are some links to help to get started:
- [Features](FEATURES.md)
- [Setup](SETUP.md)
- [Installation & setup](SETUP.md)
- [Installation](INSTALL.md)
- [API Javadocs](https://baritone.leijurv.com/)
- [Javadocs](https://baritone.leijurv.com/)
- [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#allowBreak)
# Chat control
- [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#field.detail)
- [Baritone chat control usage](USAGE.md)
# API example
# API
The API is heavily documented, you can find the Javadocs for the latest release [here](https://baritone.leijurv.com/).
Please note that usage of anything located outside of the ``baritone.api`` package is not supported by the API release
jar.
Below is an example of basic usage for changing some settings, and then pathing to a X/Z goal.
```
BaritoneAPI.getSettings().allowSprint.value = true;
@@ -67,7 +71,7 @@ That's what it's for, sure! (As long as usage is in compliance with the LGPL 3 L
## How is it so fast?
Magic. (Hours of [Leijurv](https://github.com/leijurv) enduring excruciating pain)
Magic. (Hours of [leijurv](https://github.com/leijurv) enduring excruciating pain)
## Why is it called Baritone?

View File

@@ -1,20 +1,23 @@
# Setup
# Installation
## Prebuilt
(not always completely up to date with latest features)
## Prebuilt official releases
These releases are not always completely up to date with latest features, and are only released from `master`. (so if you want `builder` branch for example, you'll have to build it yourself)
Download from the [Releases](https://github.com/cabaletta/baritone/releases)
Link to the releases page: [Releases](https://github.com/cabaletta/baritone/releases)
The Forge releases can simply be added as a Forge mod.
Any official release will be GPG signed by leijurv (44A3EA646EADAC6A) and ZeroMemes (73A788379A197567). Please verify that the hash of the file you download is in `checksums.txt` and that `checksums_signed.asc` is a valid signature by those two public keys of `checksums.txt`.
If another one of your Forge mods has a Baritone integration, you want `baritone-api-forge-VERSION.jar`. Otherwise, you want `baritone-standalone-forge-VERSION.jar`
The build is fully deterministic and reproducible, and you can verify Travis did it properly by running `docker build --no-cache -t cabaletta/baritone .` yourself and comparing the shasum. This works identically on Travis, Mac, and Linux (if you have docker on Windows, I'd be grateful if you could let me know if it works there too).
Previously (Baritone v1.1.2 and below), it was not fully compatible with the latest version of Forge. `freeLook` was broken in Forge 14.23.4.2744. Forge 14.23.4.2743 or **older** worked with Baritone v1.1.2 and lower. Newer versions of Forge "worked", sort of, but Baritone's movement became unreliable and `freeLook` must be off.
## Artifacts
Building Baritone will result in 5 artifacts created in the ``dist`` directory. These are the same as the artifacts created in the [releases](https://github.com/cabaletta/baritone/releases).
**The Forge release can simply be added as a Forge mod.**
If another one of your Forge mods has a Baritone integration, you want `baritone-api-forge-VERSION.jar`. Otherwise, you want `baritone-standalone-forge-VERSION.jar`
- **API**: Only the non-api packages are obfuscated. This should be used in environments where other mods would like to use Baritone's features.
- **Forge API**: Same as API, but packaged for Forge. This should be used where another mod has a Baritone integration.
- **Standalone**: Everything is obfuscated. This should be used in environments where there are no other mods present that would like to use Baritone's features.
@@ -22,9 +25,9 @@ Building Baritone will result in 5 artifacts created in the ``dist`` directory.
- **Unoptimized**: Nothing is obfuscated. This shouldn't be used ever in production.
## More Info
To replace out Impact 4.4's Baritone build with a customized one, switch to the `impact4.4-compat` branch, build Baritone as above then copy `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.0.0/baritone-api-1.0.0.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.4/1.12.2-Impact_4.4.json`, find the line `"name": "cabaletta:baritone-api:1.0.0"`, remove the comma from the end, and entirely remove the line that's immediately after (starts with `"url"`).
To replace out Impact 4.5's Baritone build with a customized one, build Baritone as above then copy & **rename** `dist/baritone-api-$VERSION$.jar` into `minecraft/libraries/cabaletta/baritone-api/1.2/baritone-api-1.2.jar`, replacing the jar that was previously there. You also need to edit `minecraft/versions/1.12.2-Impact_4.5/1.12.2-Impact_4.5.json`, find the line `"name": "cabaletta:baritone-api:1.2"`, remove the comma from the end, and **entirely remove the NEXT line** (starts with `"url"`). **Restart your launcher** then load as normal.
Impact 4.4 **only** works with builds from the quite outdated `impact4.4-compat` branch. If you must have the latest Baritone features with Impact, and can't wait for 4.5, consider creating a standalone (non forge) build then adding it to Impact 4.**3** via the instructions in [Install](INSTALL.md).
You can verify whether or not it worked by running `.b version` in chat (only valid in Impact). It should print out the version that you downloaded. Note: The version that comes with 4.5 is `v1.2.3`.
## Build it yourself
- Clone or download Baritone

View File

@@ -9,7 +9,7 @@ Therefore you can use a prefix before your messages.
On Baritone v1.1.0 and newer: The prefix is `#` by default. Anything beginning with `#` isn't sent, and is only interpreted by Baritone.
For older than v1.1.0, `#` must be enabled by toggling on the `prefix` setting.
**Only** in Impact 4.4 is `.b` also a valid prefix. In 4.4, `#` does **not** work, neither does saying the commands directly in chat.
**Only** in Impact is `.b` also a valid prefix. In 4.4, `#` does **not** work, neither does saying the commands directly in chat. `#` works by default in 4.5 (not 4.4).
Other clients like Kami and Asuna have their own custom things (like `-path`), and can disable direct chat control entirely.
@@ -21,7 +21,7 @@ Other clients like Kami and Asuna have their own custom things (like `-path`), a
`help` for (rudimentary) help. You can see what it says [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/utils/ExampleBaritoneControl.java#L53).
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 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`.
@@ -34,16 +34,18 @@ Some common examples:
- `cancel` or `stop` to stop everything
- `goto portal` or `goto ender_chest` or `goto block_type` to go to a block. (in Impact, `.goto` is an alias for `.b goto` for the most part)
- `mine diamond_ore` to mine diamond ore (turn on the setting `legitMine` to only mine ores that it can actually see. It will explore randomly around y=11 until it finds them.)
- `click` to click your destination on the screen. left click to path into it, right click to path on top of it.
- `follow playerName` to follow a player. `follow` to follow the entity you're looking at (only works if it hitting range). `followplayers` to follow any players in range (combine with Kill Aura for a fun time).
- `save waypointName` to save a waypoint. `goto waypointName` to go to it.
- `axis` to go to an axis or diagonal axis at y=120 (`axisHeight` is a configurable setting, defaults to 120).
- `invert` to invert the current goal and path. This gets as far away from it as possible, instead of as close as possible. For example, do `goal` then `invert` to run as far as possible from where you're standing at the start.
- `render` to rerender the world in case `renderCachedChunks` is being glitchy
- `version` to get the version of Baritone you're running
- `damn` daniel
For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/main/java/baritone/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#allowBreak">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>.
There are about a hundred settings, but here are some fun / interesting / important ones that you might want to look at changing in normal usage of Baritone. The documentation for each can be found at the above links.
- `allowBreak`

View File

@@ -1,134 +1,132 @@
/*
* 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/>.
*/
group 'baritone'
version '1.1.5'
buildscript {
repositories {
maven {
name = 'forge'
url = 'http://files.minecraftforge.net/maven'
}
maven {
name = 'SpongePowered'
url = 'http://repo.spongepowered.org/maven'
}
jcenter()
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT'
}
}
import baritone.gradle.task.CreateDistTask
import baritone.gradle.task.ProguardTask
apply plugin: 'java'
apply plugin: 'net.minecraftforge.gradle.tweaker-client'
apply plugin: 'org.spongepowered.mixin'
sourceCompatibility = targetCompatibility = '1.8'
compileJava {
sourceCompatibility = targetCompatibility = '1.8'
options.encoding = "UTF-8" // allow emoji in comments :^)
}
sourceSets {
launch {
compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output
}
}
minecraft {
version = '1.12.2'
mappings = 'stable_39'
tweakClass = 'baritone.launch.BaritoneTweaker'
runDir = 'run'
// The sources jar should use SRG names not MCP to ensure compatibility with all mappings
makeObfSourceJar = true
}
repositories {
mavenCentral()
maven {
name = 'spongepowered-repo'
url = 'http://repo.spongepowered.org/maven/'
}
maven {
name = 'impactdevelopment-repo'
url = 'https://impactdevelopment.github.io/maven/'
}
}
dependencies {
runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.2')
runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') {
// Mixin includes a lot of dependencies that are too up-to-date
exclude module: 'launchwrapper'
exclude module: 'guava'
exclude module: 'gson'
exclude module: 'commons-io'
exclude module: 'log4j-core'
}
testImplementation 'junit:junit:4.12'
}
mixin {
defaultObfuscationEnv searge
add sourceSets.launch, 'mixins.baritone.refmap.json'
}
javadoc {
options.addStringOption('Xwerror', '-quiet') // makes the build fail on travis when there is a javadoc error
options.linkSource true
options.encoding "UTF-8" // allow emoji in comments :^)
source += sourceSets.api.allJava
classpath += sourceSets.api.compileClasspath
}
jar {
from sourceSets.launch.output, sourceSets.api.output
preserveFileTimestamps = false
reproducibleFileOrder = true
}
jar {
manifest {
attributes(
'MixinConfigs': 'mixins.baritone.json',
'Implementation-Title': 'Baritone',
'Implementation-Version': version
)
}
}
task proguard(type: ProguardTask) {
url 'https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip'
extract 'proguard6.0.3/lib/proguard.jar'
}
task createDist(type: CreateDistTask, dependsOn: proguard)
build.finalizedBy(createDist)
/*
* 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/>.
*/
group 'baritone'
version '1.2.4'
buildscript {
repositories {
maven {
name = 'forge'
url = 'http://files.minecraftforge.net/maven'
}
maven {
name = 'SpongePowered'
url = 'http://repo.spongepowered.org/maven'
}
jcenter()
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT'
}
}
import baritone.gradle.task.CreateDistTask
import baritone.gradle.task.ProguardTask
apply plugin: 'java'
apply plugin: 'net.minecraftforge.gradle.tweaker-client'
apply plugin: 'org.spongepowered.mixin'
sourceCompatibility = targetCompatibility = '1.8'
compileJava {
sourceCompatibility = targetCompatibility = '1.8'
options.encoding = "UTF-8" // allow emoji in comments :^)
}
sourceSets {
launch {
compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output
}
}
minecraft {
version = '1.12.2'
mappings = 'stable_39'
tweakClass = 'baritone.launch.BaritoneTweaker'
runDir = 'run'
// The sources jar should use SRG names not MCP to ensure compatibility with all mappings
makeObfSourceJar = true
}
repositories {
mavenCentral()
maven {
name = 'spongepowered-repo'
url = 'http://repo.spongepowered.org/maven/'
}
maven {
name = 'impactdevelopment-repo'
url = 'https://impactdevelopment.github.io/maven/'
}
}
dependencies {
runtime launchCompile('com.github.ImpactDevelopment:SimpleTweaker:1.2')
runtime launchCompile('org.spongepowered:mixin:0.7.11-SNAPSHOT') {
// Mixin includes a lot of dependencies that are too up-to-date
exclude module: 'launchwrapper'
exclude module: 'guava'
exclude module: 'gson'
exclude module: 'commons-io'
exclude module: 'log4j-core'
}
testImplementation 'junit:junit:4.12'
}
mixin {
defaultObfuscationEnv searge
add sourceSets.launch, 'mixins.baritone.refmap.json'
}
javadoc {
options.addStringOption('Xwerror', '-quiet') // makes the build fail on travis when there is a javadoc error
options.linkSource true
options.encoding "UTF-8" // allow emoji in comments :^)
source = sourceSets.api.allJava
classpath += sourceSets.api.compileClasspath
}
jar {
from sourceSets.launch.output, sourceSets.api.output
preserveFileTimestamps = false
reproducibleFileOrder = true
manifest {
attributes(
'MixinConfigs': 'mixins.baritone.json',
'Implementation-Title': 'Baritone',
'Implementation-Version': version
)
}
}
task proguard(type: ProguardTask) {
url 'https://downloads.sourceforge.net/project/proguard/proguard/6.0/proguard6.0.3.zip'
extract 'proguard6.0.3/lib/proguard.jar'
}
task createDist(type: CreateDistTask, dependsOn: proguard)
build.finalizedBy(createDist)

View File

@@ -1,6 +1,6 @@
#Tue Jul 31 21:56:56 PDT 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip
#Tue Jul 31 21:56:56 PDT 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip

168
gradlew.bat vendored
View File

@@ -1,84 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -13,7 +13,7 @@
-repackageclasses 'baritone'
# lwjgl is weird
-dontwarn org.lwjgl.opengl.GL14
-dontwarn org.lwjgl.**
-keep class baritone.api.** { *; } # this is the keep api
@@ -21,9 +21,6 @@
-keep class baritone.BaritoneProvider
-keep class baritone.api.IBaritoneProvider
# hack
-keep class baritone.utils.ExampleBaritoneControl { *; } # have to include this string to remove this keep in the standalone build: # this is the keep api
# setting names are reflected from field names, so keep field names
-keepclassmembers class baritone.api.Settings {
public <fields>;

View File

@@ -1,19 +1,19 @@
/*
* 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/>.
*/
rootProject.name = 'baritone'
/*
* 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/>.
*/
rootProject.name = 'baritone'

View File

@@ -23,9 +23,7 @@ import java.util.Iterator;
import java.util.ServiceLoader;
/**
* API exposure for various things implemented in Baritone.
* <p>
* W.I.P
* Exposes the {@link IBaritoneProvider} instance and the {@link Settings} instance for API usage.
*
* @author Brady
* @since 9/23/2018

View File

@@ -22,10 +22,7 @@ import baritone.api.behavior.IPathingBehavior;
import baritone.api.cache.IWorldProvider;
import baritone.api.event.listener.IEventBus;
import baritone.api.pathing.calc.IPathingControlManager;
import baritone.api.process.ICustomGoalProcess;
import baritone.api.process.IFollowProcess;
import baritone.api.process.IGetToBlockProcess;
import baritone.api.process.IMineProcess;
import baritone.api.process.*;
import baritone.api.utils.IInputOverrideHandler;
import baritone.api.utils.IPlayerContext;
@@ -36,22 +33,13 @@ import baritone.api.utils.IPlayerContext;
public interface IBaritone {
/**
* @return The {@link IFollowProcess} instance
* @see IFollowProcess
* Call as soon as Minecraft is ready, initializes all of the processes, behaviors, etc. This will
* only effectively be ran once, any additional calls are redundant because the initialization state
* is saved.
* <p>
* Or whenever your overeager utility client wants.
*/
IFollowProcess getFollowProcess();
/**
* @return The {@link ILookBehavior} instance
* @see ILookBehavior
*/
ILookBehavior getLookBehavior();
/**
* @return The {@link IMineProcess} instance
* @see IMineProcess
*/
IMineProcess getMineProcess();
void init();
/**
* @return The {@link IPathingBehavior} instance
@@ -59,21 +47,72 @@ public interface IBaritone {
*/
IPathingBehavior getPathingBehavior();
/**
* @return The {@link ILookBehavior} instance
* @see ILookBehavior
*/
ILookBehavior getLookBehavior();
/**
* @return The {@link IFollowProcess} instance
* @see IFollowProcess
*/
IFollowProcess getFollowProcess();
/**
* @return The {@link IMineProcess} instance
* @see IMineProcess
*/
IMineProcess getMineProcess();
/**
* @return The {@link IBuilderProcess} instance
* @see IBuilderProcess
*/
IBuilderProcess getBuilderProcess();
/**
* @return The {@link ICustomGoalProcess} instance
* @see ICustomGoalProcess
*/
ICustomGoalProcess getCustomGoalProcess();
/**
* @return The {@link IGetToBlockProcess} instance
* @see IGetToBlockProcess
*/
IGetToBlockProcess getGetToBlockProcess();
/**
* @return The {@link IWorldProvider} instance
* @see IWorldProvider
*/
IWorldProvider getWorldProvider();
/**
* Returns the {@link IPathingControlManager} for this {@link IBaritone} instance, which is responsible
* for managing the {@link IBaritoneProcess}es which control the {@link IPathingBehavior} state.
*
* @return The {@link IPathingControlManager} instance
* @see IPathingControlManager
*/
IPathingControlManager getPathingControlManager();
/**
* @return The {@link IInputOverrideHandler} instance
* @see IInputOverrideHandler
*/
IInputOverrideHandler getInputOverrideHandler();
ICustomGoalProcess getCustomGoalProcess();
IGetToBlockProcess getGetToBlockProcess();
/**
* @return The {@link IPlayerContext} instance
* @see IPlayerContext
*/
IPlayerContext getPlayerContext();
/**
* @return The {@link IEventBus} instance
* @see IEventBus
*/
IEventBus getGameEventHandler();
}

View File

@@ -23,7 +23,9 @@ import net.minecraft.client.entity.EntityPlayerSP;
import java.util.List;
/**
* @author Leijurv
* Provides the present {@link IBaritone} instances
*
* @author leijurv
*/
public interface IBaritoneProvider {
@@ -47,7 +49,8 @@ public interface IBaritoneProvider {
/**
* Provides the {@link IBaritone} instance for a given {@link EntityPlayerSP}. This will likely be
* replaced with {@code #getBaritoneForUser(IBaritoneUser)} when {@code bot-system} is merged.
* replaced with or be overloaded in addition to {@code #getBaritoneForUser(IBaritoneUser)} when
* {@code bot-system} is merged into {@code master}.
*
* @param player The player
* @return The {@link IBaritone} instance.
@@ -58,7 +61,7 @@ public interface IBaritoneProvider {
return baritone;
}
}
throw new IllegalStateException("No baritone for player " + player);
return null;
}
/**

View File

@@ -17,6 +17,7 @@
package baritone.api;
import baritone.api.utils.SettingsUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
@@ -29,7 +30,7 @@ import java.util.List;
import java.util.function.Consumer;
/**
* Baritone's settings
* Baritone's settings. Settings apply to all Baritone instances.
*
* @author leijurv
*/
@@ -169,6 +170,11 @@ public final class Settings {
*/
public final Setting<Boolean> sprintAscends = new Setting<>(true);
/**
* How many ticks between right clicks are allowed. Default in game is 4
*/
public final Setting<Integer> rightClickSpeed = new Setting<>(4);
/**
* This is the big A* setting.
* As long as your cost heuristic is an *underestimate*, it's guaranteed to find you the best path.
@@ -385,11 +391,6 @@ public final class Settings {
*/
public final Setting<Boolean> pruneRegionsFromRAM = new Setting<>(false);
/**
* Cancel baritone on left click, as a form of "panic button"
*/
public final Setting<Boolean> clickCancel = new Setting<>(false);
/**
* Remember the contents of containers (chests, echests, furnaces)
* <p>
@@ -484,10 +485,12 @@ public final class Settings {
public final Setting<Boolean> sprintInWater = new Setting<>(true);
/**
* When GetToBlockProcess fails to calculate a path, instead of just giving up, mark the closest instances
* of that block as "unreachable" and go towards the next closest
* When GetToBlockProcess or MineProcess fails to calculate a path, instead of just giving up, mark the closest instance
* of that block as "unreachable" and go towards the next closest. GetToBlock expands this seaarch to the whole "vein"; MineProcess does not.
* This is because MineProcess finds individual impossible blocks (like one block in a vein that has gravel on top then lava, so it can't break)
* Whereas GetToBlock should blacklist the whole "vein" if it can't get to any of them.
*/
public final Setting<Boolean> blacklistOnGetToBlockFailure = new Setting<>(true);
public final Setting<Boolean> blacklistClosestOnFailure = new Setting<>(true);
/**
* 😎 Render cached chunks as semitransparent. Doesn't work with OptiFine 😭 Rarely randomly crashes, see <a href="https://github.com/cabaletta/baritone/issues/327">this issue</a>.
@@ -500,18 +503,13 @@ public final class Settings {
* <p>
* SOLID is rendered as stone in the overworld, netherrack in the nether, and end stone in the end
*/
public Setting<Boolean> renderCachedChunks = new Setting<>(false);
public final Setting<Boolean> renderCachedChunks = new Setting<>(false);
/**
* 0.0f = not visible, fully transparent
* 1.0f = fully opaque
*/
public Setting<Float> cachedChunksOpacity = new Setting<>(0.5f);
/**
* If true, Baritone will not allow you to left or right click while pathing
*/
public Setting<Boolean> suppressClicks = new Setting<>(false);
public final Setting<Float> cachedChunksOpacity = new Setting<>(0.5f);
/**
* Whether or not to use the "#" command prefix
@@ -539,6 +537,11 @@ public final class Settings {
*/
public final Setting<Integer> mineGoalUpdateInterval = new Setting<>(5);
/**
* After finding this many instances of the target block in the cache, it will stop expanding outward the chunk search.
*/
public final Setting<Integer> maxCachedWorldScanCount = new Setting<>(10);
/**
* When GetToBlock doesn't know any locations for the desired block, explore randomly instead of giving up.
*/
@@ -569,6 +572,11 @@ public final class Settings {
*/
public final Setting<Integer> axisHeight = new Setting<>(120);
/**
* Disconnect from the server upon arriving at your goal
*/
public final Setting<Boolean> disconnectOnArrival = new Setting<>(false);
/**
* Disallow MineBehavior from using X-Ray to see where the ores are. Turn this option on to force it to mine "legit"
* where it will only mine an ore once it can actually see it, so it won't do or know anything that a normal player
@@ -624,6 +632,13 @@ public final class Settings {
*/
public final Setting<Integer> followRadius = new Setting<>(3);
/**
* true = exploration uses pythagorean distance to choose closest uncached chunk
* <p>
* false = exploration uses manhattan / taxicab distance to choose
*/
public final Setting<Boolean> exploreUsePythagorean = new Setting<>(false);
/**
* Cached chunks (regardless of if they're in RAM or saved to disk) expire and are deleted after this number of seconds
* -1 to disable
@@ -704,12 +719,6 @@ public final class Settings {
*/
public final List<Setting<?>> allSettings;
public void reset() {
for (Setting setting : allSettings) {
setting.value = setting.defaultValue;
}
}
public final class Setting<T> {
public T value;
public final T defaultValue;
@@ -726,9 +735,14 @@ public final class Settings {
this.klass = (Class<T>) value.getClass();
}
@SuppressWarnings("unchecked")
public final <K extends T> K get() {
return (K) value;
/**
* Deprecated! Please use .value directly instead
*
* @return the current setting value
*/
@Deprecated
public final T get() {
return value;
}
public final String getName() {
@@ -739,8 +753,16 @@ public final class Settings {
return klass;
}
@Override
public String toString() {
return name + ": " + value;
return SettingsUtil.settingToString(this);
}
/**
* Reset this setting to its default value
*/
public void reset() {
value = defaultValue;
}
}

View File

@@ -18,8 +18,13 @@
package baritone.api.behavior;
import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.event.listener.IGameEventListener;
/**
* A behavior is simply a type that is able to listen to events.
*
* @see IGameEventListener
*
* @author Brady
* @since 9/23/2018
*/

View File

@@ -20,7 +20,7 @@ package baritone.api.cache;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.Chunk;
import java.util.LinkedList;
import java.util.ArrayList;
/**
* @author Brady
@@ -68,7 +68,7 @@ public interface ICachedWorld {
* @param maxRegionDistanceSq The maximum region distance, squared
* @return The locations found that match the special block
*/
LinkedList<BlockPos> getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq);
ArrayList<BlockPos> getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq);
/**
* Reloads all of the cached regions in this world from disk. Anything that is not saved

View File

@@ -25,7 +25,7 @@ public class GoalAxis implements Goal {
@Override
public boolean isInGoal(int x, int y, int z) {
return y == BaritoneAPI.getSettings().axisHeight.get() && (x == 0 || z == 0 || Math.abs(x) == Math.abs(z));
return y == BaritoneAPI.getSettings().axisHeight.value && (x == 0 || z == 0 || Math.abs(x) == Math.abs(z));
}
@Override
@@ -39,7 +39,7 @@ public class GoalAxis implements Goal {
double flatAxisDistance = Math.min(x, Math.min(z, diff * SQRT_2_OVER_2));
return flatAxisDistance * BaritoneAPI.getSettings().costHeuristic.get() + GoalYLevel.calculate(BaritoneAPI.getSettings().axisHeight.get(), y);
return flatAxisDistance * BaritoneAPI.getSettings().costHeuristic.value + GoalYLevel.calculate(BaritoneAPI.getSettings().axisHeight.value, y);
}
@Override

View File

@@ -30,17 +30,17 @@ public class GoalBlock implements Goal, IGoalRenderPos {
/**
* The X block position of this goal
*/
private final int x;
public final int x;
/**
* The Y block position of this goal
*/
private final int y;
public final int y;
/**
* The Z block position of this goal
*/
private final int z;
public final int z;
public GoalBlock(BlockPos pos) {
this(pos.getX(), pos.getY(), pos.getZ());

View File

@@ -28,9 +28,9 @@ import net.minecraft.util.math.BlockPos;
*/
public class GoalGetToBlock implements Goal, IGoalRenderPos {
private final int x;
private final int y;
private final int z;
public final int x;
public final int y;
public final int z;
public GoalGetToBlock(BlockPos pos) {
this.x = pos.getX();

View File

@@ -80,7 +80,7 @@ public class GoalXZ implements Goal {
diagonal = z;
}
diagonal *= SQRT_2;
return (diagonal + straight) * BaritoneAPI.getSettings().costHeuristic.get(); // big TODO tune
return (diagonal + straight) * BaritoneAPI.getSettings().costHeuristic.value; // big TODO tune
}
public static GoalXZ fromDirection(Vec3d origin, float yaw, double distance) {

View File

@@ -45,10 +45,6 @@ public interface IMovement {
*/
boolean safeToCancel();
double recalculateCost();
double calculateCostWithoutCaching();
boolean calculatedWhileLoaded();
BetterBlockPos getSrc();

View File

@@ -35,6 +35,16 @@ import baritone.api.event.events.PathEvent;
*/
public interface IBaritoneProcess {
/**
* Default priority. Most normal processes should have this value.
* <p>
* Some examples of processes that should have different values might include some kind of automated mob avoidance
* that would be temporary and would forcefully take control. Same for something that pauses pathing for auto eat, etc.
* <p>
* The value is -1 beacuse that's what Impact 4.5's beta auto walk returns and I want to tie with it.
*/
double DEFAULT_PRIORITY = -1;
/**
* Would this process like to be in control?
*
@@ -82,12 +92,23 @@ public interface IBaritoneProcess {
*
* @return A double representing the priority
*/
double priority();
default double priority() {
return DEFAULT_PRIORITY;
}
/**
* Returns a user-friendly name for this process. Suitable for a HUD.
*
* @return A display name that's suitable for a HUD
*/
String displayName();
default String displayName() {
if (!isActive()) {
// i love it when impcat's scuffed HUD calls displayName for inactive processes for 1 tick too long
// causing NPEs when the displayname relies on fields that become null when inactive
return "INACTIVE";
}
return displayName0();
}
String displayName0();
}

View File

@@ -0,0 +1,49 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.process;
import baritone.api.utils.ISchematic;
import net.minecraft.util.math.Vec3i;
import java.io.File;
/**
* @author Brady
* @since 1/15/2019
*/
public interface IBuilderProcess extends IBaritoneProcess {
/**
* Requests a build for the specified schematic, labeled as specified, with the specified origin.
*
* @param name A user-friendly name for the schematic
* @param schematic The object representation of the schematic
* @param origin The origin position of the schematic being built
*/
void build(String name, ISchematic schematic, Vec3i origin);
/**
* Requests a build for the specified schematic, labeled as specified, with the specified origin.
*
* @param name A user-friendly name for the schematic
* @param schematic The file path of the schematic
* @param origin The origin position of the schematic being built
* @return Whether or not the schematic was able to load from file
*/
boolean build(String name, File schematic, Vec3i origin);
}

View File

@@ -53,4 +53,9 @@ public class PathingCommand {
this.goal = goal;
this.commandType = commandType;
}
@Override
public String toString() {
return commandType + " " + goal;
}
}

View File

@@ -19,7 +19,6 @@ package baritone.api.utils;
import baritone.api.behavior.IBehavior;
import baritone.api.utils.input.Input;
import net.minecraft.client.settings.KeyBinding;
/**
* @author Brady
@@ -27,8 +26,6 @@ import net.minecraft.client.settings.KeyBinding;
*/
public interface IInputOverrideHandler extends IBehavior {
Boolean isInputForcedDown(KeyBinding key);
boolean isInputForcedDown(Input input);
void setInputForceState(Input input, boolean forced);

View File

@@ -17,12 +17,17 @@
package baritone.api.utils;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ClickType;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.GameType;
import net.minecraft.world.World;
/**
* @author Brady
@@ -43,4 +48,6 @@ public interface IPlayerController {
default double getBlockReachDistance() {
return this.getGameType().isCreative() ? 5.0F : 4.5F;
}
EnumActionResult processRightClickBlock(EntityPlayerSP player, World world, BlockPos pos, EnumFacing direction, Vec3d vec, EnumHand hand);
}

View File

@@ -0,0 +1,71 @@
/*
* 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.utils;
import net.minecraft.block.state.IBlockState;
/**
* Basic representation of a schematic. Provides the dimensions and
* the desired statefor a given position relative to the origin.
*
* @author leijurv
*/
public interface ISchematic {
/**
* Does the block at this coordinate matter to the schematic?
* <p>
* Normally just a check for if the coordinate is in the cube.
* <p>
* However, in the case of something like a map art, anything that's below the level of the map art doesn't matter,
* so this function should return false in that case. (i.e. it doesn't really have to be air below the art blocks)
*
* @param x The x position of the block, relative to the origin
* @param y The y position of the block, relative to the origin
* @param z The z position of the block, relative to the origin
* @return Whether or not the specified position is within the bounds of this schematic
*/
default boolean inSchematic(int x, int y, int z) {
return x >= 0 && x < widthX() && y >= 0 && y < heightY() && z >= 0 && z < lengthZ();
}
/**
* Returns the desired block state at a given (X, Y, Z) position relative to the origin (0, 0, 0).
*
* @param x The x position of the block, relative to the origin
* @param y The y position of the block, relative to the origin
* @param z The z position of the block, relative to the origin
* @return The desired block state at the specified position
*/
IBlockState desiredState(int x, int y, int z);
/**
* @return The width (X axis length) of this schematic
*/
int widthX();
/**
* @return The height (Y axis length) of this schematic
*/
int heightY();
/**
* @return The length (Z axis length) of this schematic
*/
int lengthZ();
}

View File

@@ -27,10 +27,8 @@ import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Matcher;
@@ -89,22 +87,8 @@ public class SettingsUtil {
public static synchronized void save(Settings settings) {
try (BufferedWriter out = Files.newBufferedWriter(SETTINGS_PATH)) {
for (Settings.Setting setting : settings.allSettings) {
if (setting.get() == null) {
System.out.println("NULL SETTING?" + setting.getName());
continue;
}
if (setting.getName().equals("logger")) {
continue; // NO
}
if (setting.value == setting.defaultValue) {
continue;
}
SettingsIO io = map.get(setting.getValueClass());
if (io == null) {
throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting + " " + setting.getName());
}
out.write(setting.getName() + " " + io.toString.apply(setting.get()) + "\n");
for (Settings.Setting setting : modifiedSettings(settings)) {
out.write(settingToString(setting) + "\n");
}
} catch (Exception ex) {
System.out.println("Exception thrown while saving Baritone settings!");
@@ -112,7 +96,36 @@ public class SettingsUtil {
}
}
private static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException {
public static List<Settings.Setting> modifiedSettings(Settings settings) {
List<Settings.Setting> modified = new ArrayList<>();
for (Settings.Setting setting : settings.allSettings) {
if (setting.value == null) {
System.out.println("NULL SETTING?" + setting.getName());
continue;
}
if (setting.getName().equals("logger")) {
continue; // NO
}
if (setting.value == setting.defaultValue) {
continue;
}
modified.add(setting);
}
return modified;
}
public static String settingToString(Settings.Setting setting) throws IllegalStateException {
if (setting.getName().equals("logger")) {
return "logger";
}
SettingsIO io = map.get(setting.getValueClass());
if (io == null) {
throw new IllegalStateException("Missing " + setting.getValueClass() + " " + setting.getName());
}
return setting.getName() + " " + io.toString.apply(setting.value);
}
public static void parseAndApply(Settings settings, String settingName, String settingValue) throws IllegalStateException, NumberFormatException {
Settings.Setting setting = settings.byLowerName.get(settingName);
if (setting == null) {
throw new IllegalStateException("No setting by that name");

View File

@@ -17,15 +17,6 @@
package baritone.api.utils.input;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.client.settings.KeyBinding;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* An {@link Enum} representing the inputs that control the player's
* behavior. This includes moving, interacting with blocks, jumping,
@@ -36,84 +27,45 @@ public enum Input {
/**
* The move forward input
*/
MOVE_FORWARD(s -> s.keyBindForward),
MOVE_FORWARD,
/**
* The move back input
*/
MOVE_BACK(s -> s.keyBindBack),
MOVE_BACK,
/**
* The move left input
*/
MOVE_LEFT(s -> s.keyBindLeft),
MOVE_LEFT,
/**
* The move right input
*/
MOVE_RIGHT(s -> s.keyBindRight),
MOVE_RIGHT,
/**
* The attack input
*/
CLICK_LEFT(s -> s.keyBindAttack),
CLICK_LEFT,
/**
* The use item input
*/
CLICK_RIGHT(s -> s.keyBindUseItem),
CLICK_RIGHT,
/**
* The jump input
*/
JUMP(s -> s.keyBindJump),
JUMP,
/**
* The sneak input
*/
SNEAK(s -> s.keyBindSneak),
SNEAK,
/**
* The sprint input
*/
SPRINT(s -> s.keyBindSprint);
/**
* Map of {@link KeyBinding} to {@link Input}. Values should be queried through {@link #getInputForBind(KeyBinding)}
*/
private static final Map<KeyBinding, Input> bindToInputMap = new HashMap<>();
/**
* The actual game {@link KeyBinding} being forced.
*/
private final KeyBinding keyBinding;
Input(Function<GameSettings, KeyBinding> keyBindingMapper) {
/*
Here, a Function is used because referring to a static field in this enum for the game instance,
as it was before, wouldn't be possible in an Enum constructor unless the static field was in an
interface that this class implemented. (Helper acted as this interface) I didn't feel like making
an interface with a game instance field just to not have to do this.
*/
this.keyBinding = keyBindingMapper.apply(Minecraft.getMinecraft().gameSettings);
}
/**
* @return The actual game {@link KeyBinding} being forced.
*/
public final KeyBinding getKeyBinding() {
return this.keyBinding;
}
/**
* Finds the {@link Input} constant that is associated with the specified {@link KeyBinding}.
*
* @param binding The {@link KeyBinding} to find the associated {@link Input} for
* @return The {@link Input} associated with the specified {@link KeyBinding}
*/
public static Input getInputForBind(KeyBinding binding) {
return bindToInputMap.computeIfAbsent(binding, b -> Arrays.stream(values()).filter(input -> input.keyBinding == b).findFirst().orElse(null));
}
SPRINT
}

View File

@@ -41,10 +41,10 @@ public class MixinChunkRenderContainer {
)
)
private BlockPos getPosition(RenderChunk renderChunkIn) {
if (Baritone.settings().renderCachedChunks.get() && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) {
if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null && Minecraft.getMinecraft().world.getChunk(renderChunkIn.getPosition()).isEmpty()) {
GlStateManager.enableAlpha();
GlStateManager.enableBlend();
GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.get());
GL14.glBlendColor(0, 0, 0, Baritone.settings().cachedChunksOpacity.value);
GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_ONE, GL_ZERO);
}
return renderChunkIn.getPosition();

View File

@@ -20,6 +20,7 @@ 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;
@@ -42,7 +43,7 @@ public abstract class MixinChunkRenderWorker {
)
)
private boolean isChunkExisting(ChunkRenderWorker worker, BlockPos pos, World world) {
if (Baritone.settings().renderCachedChunks.get()) {
if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) {
Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone();
IPlayerContext ctx = baritone.getPlayerContext();
if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) {

View File

@@ -18,6 +18,7 @@
package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.event.events.RotationMoveEvent;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
@@ -55,8 +56,11 @@ public abstract class MixinEntityLivingBase extends Entity {
private void preMoveRelative(CallbackInfo ci) {
// noinspection ConstantConditions
if (EntityPlayerSP.class.isInstance(this)) {
this.jumpRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.JUMP, this.rotationYaw);
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent);
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone != null) {
this.jumpRotationEvent = new RotationMoveEvent(RotationMoveEvent.Type.JUMP, this.rotationYaw);
baritone.getGameEventHandler().onPlayerRotationMove(this.jumpRotationEvent);
}
}
}
@@ -69,7 +73,7 @@ public abstract class MixinEntityLivingBase extends Entity {
)
)
private float overrideYaw(EntityLivingBase self) {
if (self instanceof EntityPlayerSP) {
if (self instanceof EntityPlayerSP && BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this) != null) {
return this.jumpRotationEvent.getYaw();
}
return self.rotationYaw;
@@ -84,7 +88,7 @@ public abstract class MixinEntityLivingBase extends Entity {
)
private void travel(EntityLivingBase self, float strafe, float up, float forward, float friction) {
// noinspection ConstantConditions
if (!EntityPlayerSP.class.isInstance(this)) {
if (!EntityPlayerSP.class.isInstance(this) || BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this) == null) {
moveRelative(strafe, up, forward, friction);
return;
}

View File

@@ -19,7 +19,6 @@ package baritone.launch.mixins;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.behavior.IPathingBehavior;
import baritone.api.event.events.ChatEvent;
import baritone.api.event.events.PlayerUpdateEvent;
import baritone.api.event.events.SprintStateEvent;
@@ -48,7 +47,11 @@ public class MixinEntityPlayerSP {
)
private void sendChatMessage(String msg, CallbackInfo ci) {
ChatEvent event = new ChatEvent(msg);
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onSendChatMessage(event);
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone == null) {
return;
}
baritone.getGameEventHandler().onSendChatMessage(event);
if (event.isCancelled()) {
ci.cancel();
}
@@ -64,7 +67,10 @@ public class MixinEntityPlayerSP {
)
)
private void onPreUpdate(CallbackInfo ci) {
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.PRE));
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone != null) {
baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.PRE));
}
}
@Inject(
@@ -77,7 +83,10 @@ public class MixinEntityPlayerSP {
)
)
private void onPostUpdate(CallbackInfo ci) {
BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST));
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone != null) {
baritone.getGameEventHandler().onPlayerUpdate(new PlayerUpdateEvent(EventState.POST));
}
}
@Redirect(
@@ -88,8 +97,11 @@ public class MixinEntityPlayerSP {
)
)
private boolean isAllowFlying(PlayerCapabilities capabilities) {
IPathingBehavior pathingBehavior = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getPathingBehavior();
return !pathingBehavior.isPathing() && capabilities.allowFlying;
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone == null) {
return capabilities.allowFlying;
}
return !baritone.getPathingBehavior().isPathing() && capabilities.allowFlying;
}
@Redirect(
@@ -100,8 +112,11 @@ public class MixinEntityPlayerSP {
)
)
private boolean isKeyDown(KeyBinding keyBinding) {
SprintStateEvent event = new SprintStateEvent();
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone == null) {
return keyBinding.isKeyDown();
}
SprintStateEvent event = new SprintStateEvent();
baritone.getGameEventHandler().onPlayerSprintState(event);
if (event.getState() != null) {
return event.getState();
@@ -120,6 +135,9 @@ public class MixinEntityPlayerSP {
)
)
private void updateRidden(CallbackInfo cb) {
((LookBehavior) BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this).getLookBehavior()).pig();
IBaritone baritone = BaritoneAPI.getProvider().getBaritoneForPlayer((EntityPlayerSP) (Object) this);
if (baritone != null) {
((LookBehavior) baritone.getLookBehavior()).pig();
}
}
}

View File

@@ -1,79 +0,0 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.launch.mixins;
import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.utils.Helper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
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.CallbackInfoReturnable;
/**
* @author Brady
* @since 7/31/2018
*/
@Mixin(KeyBinding.class)
public class MixinKeyBinding {
@Shadow
private int pressTime;
@Inject(
method = "isKeyDown",
at = @At("HEAD"),
cancellable = true
)
private void isKeyDown(CallbackInfoReturnable<Boolean> cir) {
// only the primary baritone forces keys
Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this);
if (force != null) {
if (!force && !Baritone.settings().suppressClicks.get()) {
return;
}
cir.setReturnValue(force); // :sunglasses:
}
}
@Inject(
method = "isPressed",
at = @At("HEAD"),
cancellable = true
)
private void isPressed(CallbackInfoReturnable<Boolean> cir) {
// only the primary baritone forces keys
Boolean force = BaritoneAPI.getProvider().getPrimaryBaritone().getInputOverrideHandler().isInputForcedDown((KeyBinding) (Object) this);
if (pressTime > 0 && (KeyBinding) (Object) this == Minecraft.getMinecraft().gameSettings.keyBindAttack && Baritone.settings().clickCancel.get() && BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().isPathing()) {
Helper.HELPER.logDirect("Cancelling path on left click since the clickCancel setting is enabled!");
BaritoneAPI.getProvider().getPrimaryBaritone().getPathingBehavior().cancelEverything();
return;
}
if (force != null && !force && Baritone.settings().suppressClicks.get()) { // <-- cursed
if (pressTime > 0) {
Helper.HELPER.logDirect("You're trying to press this mouse button but I won't let you.");
Helper.HELPER.logDirect("Turn off the suppressClicks setting to allow clicking while pathing.");
pressTime--;
}
cir.setReturnValue(force); // :sunglasses:
}
}
}

View File

@@ -21,6 +21,7 @@ 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.util.math.BlockPos;
import net.minecraft.world.ChunkCache;
@@ -46,7 +47,7 @@ public class MixinRenderChunk {
if (!chunkCache.isEmpty()) {
return false;
}
if (Baritone.settings().renderCachedChunks.get()) {
if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) {
Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone();
IPlayerContext ctx = baritone.getPlayerContext();
if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) {
@@ -75,7 +76,7 @@ public class MixinRenderChunk {
)
)
private IBlockState getBlockState(ChunkCache chunkCache, BlockPos pos) {
if (Baritone.settings().renderCachedChunks.get()) {
if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) {
Baritone baritone = (Baritone) BaritoneAPI.getProvider().getPrimaryBaritone();
IPlayerContext ctx = baritone.getPlayerContext();
if (ctx.player() != null && ctx.world() != null && baritone.bsi != null) {

View File

@@ -18,6 +18,7 @@
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;
@@ -37,7 +38,7 @@ public class MixinRenderList {
)
)
private void popMatrix() {
if (Baritone.settings().renderCachedChunks.get()) {
if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) {
// reset the blend func to normal (not dependent on constant alpha)
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
}

View File

@@ -18,6 +18,7 @@
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;
@@ -37,7 +38,7 @@ public class MixinVboRenderList {
)
)
private void popMatrix() {
if (Baritone.settings().renderCachedChunks.get()) {
if (Baritone.settings().renderCachedChunks.value && Minecraft.getMinecraft().getIntegratedServer() == null) {
// reset the blend func to normal (not dependent on constant alpha)
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
}

View File

@@ -17,7 +17,6 @@
"MixinEntityLivingBase",
"MixinEntityPlayerSP",
"MixinEntityRenderer",
"MixinKeyBinding",
"MixinMinecraft",
"MixinNetHandlerPlayClient",
"MixinNetworkManager",

View File

@@ -1,210 +1,226 @@
/*
* 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;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.Settings;
import baritone.api.event.listener.IEventBus;
import baritone.api.utils.IPlayerContext;
import baritone.behavior.*;
import baritone.cache.WorldProvider;
import baritone.event.GameEventHandler;
import baritone.process.CustomGoalProcess;
import baritone.process.FollowProcess;
import baritone.process.GetToBlockProcess;
import baritone.process.MineProcess;
import baritone.utils.*;
import baritone.utils.player.PrimaryPlayerContext;
import net.minecraft.client.Minecraft;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author Brady
* @since 7/31/2018
*/
public class Baritone implements IBaritone {
private static ThreadPoolExecutor threadPool;
private static File dir;
static {
threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>());
dir = new File(Minecraft.getMinecraft().gameDir, "baritone");
if (!Files.exists(dir.toPath())) {
try {
Files.createDirectories(dir.toPath());
} catch (IOException ignored) {}
}
}
/**
* Whether or not {@link Baritone#init()} has been called yet
*/
private boolean initialized;
private GameEventHandler gameEventHandler;
private List<Behavior> behaviors;
private PathingBehavior pathingBehavior;
private LookBehavior lookBehavior;
private MemoryBehavior memoryBehavior;
private InputOverrideHandler inputOverrideHandler;
private FollowProcess followProcess;
private MineProcess mineProcess;
private GetToBlockProcess getToBlockProcess;
private CustomGoalProcess customGoalProcess;
private PathingControlManager pathingControlManager;
private IPlayerContext playerContext;
private WorldProvider worldProvider;
public BlockStateInterface bsi;
Baritone() {
this.gameEventHandler = new GameEventHandler(this);
}
public synchronized void init() {
if (initialized) {
return;
}
// Define this before behaviors try and get it, or else it will be null and the builds will fail!
this.playerContext = PrimaryPlayerContext.INSTANCE;
this.behaviors = new ArrayList<>();
{
// the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist
pathingBehavior = new PathingBehavior(this);
lookBehavior = new LookBehavior(this);
memoryBehavior = new MemoryBehavior(this);
new InventoryBehavior(this);
inputOverrideHandler = new InputOverrideHandler(this);
new ExampleBaritoneControl(this);
}
this.pathingControlManager = new PathingControlManager(this);
{
followProcess = new FollowProcess(this);
mineProcess = new MineProcess(this);
customGoalProcess = new CustomGoalProcess(this); // very high iq
getToBlockProcess = new GetToBlockProcess(this);
}
this.worldProvider = new WorldProvider();
if (BaritoneAutoTest.ENABLE_AUTO_TEST) {
this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE);
}
this.initialized = true;
}
@Override
public PathingControlManager getPathingControlManager() {
return this.pathingControlManager;
}
public List<Behavior> getBehaviors() {
return this.behaviors;
}
public void registerBehavior(Behavior behavior) {
this.behaviors.add(behavior);
this.gameEventHandler.registerEventListener(behavior);
}
@Override
public InputOverrideHandler getInputOverrideHandler() {
return this.inputOverrideHandler;
}
@Override
public CustomGoalProcess getCustomGoalProcess() { // Iffy
return this.customGoalProcess;
}
@Override
public GetToBlockProcess getGetToBlockProcess() { // Iffy
return this.getToBlockProcess;
}
@Override
public IPlayerContext getPlayerContext() {
return this.playerContext;
}
public MemoryBehavior getMemoryBehavior() {
return this.memoryBehavior;
}
@Override
public FollowProcess getFollowProcess() {
return this.followProcess;
}
@Override
public LookBehavior getLookBehavior() {
return this.lookBehavior;
}
@Override
public MineProcess getMineProcess() {
return this.mineProcess;
}
@Override
public PathingBehavior getPathingBehavior() {
return this.pathingBehavior;
}
@Override
public WorldProvider getWorldProvider() {
return this.worldProvider;
}
@Override
public IEventBus getGameEventHandler() {
return this.gameEventHandler;
}
public static Settings settings() {
return BaritoneAPI.getSettings();
}
public static File getDir() {
return dir;
}
public static Executor getExecutor() {
return threadPool;
}
}
/*
* 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;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.Settings;
import baritone.api.event.listener.IEventBus;
import baritone.api.utils.IPlayerContext;
import baritone.behavior.*;
import baritone.cache.WorldProvider;
import baritone.event.GameEventHandler;
import baritone.process.*;
import baritone.utils.*;
import baritone.utils.player.PrimaryPlayerContext;
import net.minecraft.client.Minecraft;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author Brady
* @since 7/31/2018
*/
public class Baritone implements IBaritone {
private static ThreadPoolExecutor threadPool;
private static File dir;
static {
threadPool = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>());
dir = new File(Minecraft.getMinecraft().gameDir, "baritone");
if (!Files.exists(dir.toPath())) {
try {
Files.createDirectories(dir.toPath());
} catch (IOException ignored) {}
}
}
/**
* Whether or not {@link Baritone#init()} has been called yet
*/
private boolean initialized;
private GameEventHandler gameEventHandler;
private List<Behavior> behaviors;
private PathingBehavior pathingBehavior;
private LookBehavior lookBehavior;
private MemoryBehavior memoryBehavior;
private InventoryBehavior inventoryBehavior;
private InputOverrideHandler inputOverrideHandler;
private FollowProcess followProcess;
private MineProcess mineProcess;
private GetToBlockProcess getToBlockProcess;
private CustomGoalProcess customGoalProcess;
private BuilderProcess builderProcess;
private ExploreProcess exploreProcess;
private PathingControlManager pathingControlManager;
private IPlayerContext playerContext;
private WorldProvider worldProvider;
public BlockStateInterface bsi;
Baritone() {
this.gameEventHandler = new GameEventHandler(this);
}
@Override
public synchronized void init() {
if (initialized) {
return;
}
// Define this before behaviors try and get it, or else it will be null and the builds will fail!
this.playerContext = PrimaryPlayerContext.INSTANCE;
this.behaviors = new ArrayList<>();
{
// the Behavior constructor calls baritone.registerBehavior(this) so this populates the behaviors arraylist
pathingBehavior = new PathingBehavior(this);
lookBehavior = new LookBehavior(this);
memoryBehavior = new MemoryBehavior(this);
inventoryBehavior = new InventoryBehavior(this);
inputOverrideHandler = new InputOverrideHandler(this);
new ExampleBaritoneControl(this);
}
this.pathingControlManager = new PathingControlManager(this);
{
followProcess = new FollowProcess(this);
mineProcess = new MineProcess(this);
customGoalProcess = new CustomGoalProcess(this); // very high iq
getToBlockProcess = new GetToBlockProcess(this);
builderProcess = new BuilderProcess(this);
exploreProcess = new ExploreProcess(this);
}
this.worldProvider = new WorldProvider();
if (BaritoneAutoTest.ENABLE_AUTO_TEST) {
this.gameEventHandler.registerEventListener(BaritoneAutoTest.INSTANCE);
}
this.initialized = true;
}
@Override
public PathingControlManager getPathingControlManager() {
return this.pathingControlManager;
}
public List<Behavior> getBehaviors() {
return this.behaviors;
}
public void registerBehavior(Behavior behavior) {
this.behaviors.add(behavior);
this.gameEventHandler.registerEventListener(behavior);
}
@Override
public InputOverrideHandler getInputOverrideHandler() {
return this.inputOverrideHandler;
}
@Override
public CustomGoalProcess getCustomGoalProcess() { // Iffy
return this.customGoalProcess;
}
@Override
public GetToBlockProcess getGetToBlockProcess() { // Iffy
return this.getToBlockProcess;
}
@Override
public IPlayerContext getPlayerContext() {
return this.playerContext;
}
public MemoryBehavior getMemoryBehavior() {
return this.memoryBehavior;
}
@Override
public FollowProcess getFollowProcess() {
return this.followProcess;
}
@Override
public BuilderProcess getBuilderProcess() {
return this.builderProcess;
}
public InventoryBehavior getInventoryBehavior() {
return this.inventoryBehavior;
}
@Override
public LookBehavior getLookBehavior() {
return this.lookBehavior;
}
public ExploreProcess getExploreProcess() {
return this.exploreProcess;
}
@Override
public MineProcess getMineProcess() {
return this.mineProcess;
}
@Override
public PathingBehavior getPathingBehavior() {
return this.pathingBehavior;
}
@Override
public WorldProvider getWorldProvider() {
return this.worldProvider;
}
@Override
public IEventBus getGameEventHandler() {
return this.gameEventHandler;
}
public static Settings settings() {
return BaritoneAPI.getSettings();
}
public static File getDir() {
return dir;
}
public static Executor getExecutor() {
return threadPool;
}
}

View File

@@ -21,13 +21,18 @@ import baritone.Baritone;
import baritone.api.event.events.TickEvent;
import baritone.utils.ToolSet;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.ClickType;
import net.minecraft.item.ItemPickaxe;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import net.minecraft.item.*;
import net.minecraft.util.NonNullList;
import java.util.ArrayList;
import java.util.OptionalInt;
import java.util.Random;
import java.util.function.Predicate;
public class InventoryBehavior extends Behavior {
public InventoryBehavior(Baritone baritone) {
super(baritone);
@@ -35,7 +40,7 @@ public class InventoryBehavior extends Behavior {
@Override
public void onTick(TickEvent event) {
if (!Baritone.settings().allowInventory.get()) {
if (!Baritone.settings().allowInventory.value) {
return;
}
if (event.getType() == TickEvent.Type.OUT) {
@@ -54,6 +59,34 @@ public class InventoryBehavior extends Behavior {
}
}
public void attemptToPutOnHotbar(int inMainInvy, Predicate<Integer> disallowedHotbar) {
OptionalInt destination = getTempHotbarSlot(disallowedHotbar);
if (destination.isPresent()) {
swapWithHotBar(inMainInvy, destination.getAsInt());
}
}
public OptionalInt getTempHotbarSlot(Predicate<Integer> disallowedHotbar) {
// we're using 0 and 8 for pickaxe and throwaway
ArrayList<Integer> candidates = new ArrayList<>();
for (int i = 1; i < 8; i++) {
if (ctx.player().inventory.mainInventory.get(i).isEmpty() && !disallowedHotbar.test(i)) {
candidates.add(i);
}
}
if (candidates.isEmpty()) {
for (int i = 1; i < 8; i++) {
if (!disallowedHotbar.test(i)) {
candidates.add(i);
}
}
}
if (candidates.isEmpty()) {
return OptionalInt.empty();
}
return OptionalInt.of(candidates.get(new Random().nextInt(candidates.size())));
}
private void swapWithHotBar(int inInventory, int inHotbar) {
ctx.playerController().windowClick(ctx.player().inventoryContainer.windowId, inInventory < 9 ? inInventory + 36 : inInventory, inHotbar, ClickType.SWAP, ctx.player());
}
@@ -61,7 +94,7 @@ public class InventoryBehavior extends Behavior {
private int firstValidThrowaway() { // TODO offhand idk
NonNullList<ItemStack> invy = ctx.player().inventory.mainInventory;
for (int i = 0; i < invy.size(); i++) {
if (Baritone.settings().acceptableThrowawayItems.get().contains(invy.get(i).getItem())) {
if (Baritone.settings().acceptableThrowawayItems.value.contains(invy.get(i).getItem())) {
return i;
}
}
@@ -87,4 +120,62 @@ public class InventoryBehavior extends Behavior {
}
return bestInd;
}
public boolean hasGenericThrowaway() {
for (Item item : Baritone.settings().acceptableThrowawayItems.value) {
if (throwaway(false, item::equals)) {
return true;
}
}
return false;
}
public boolean selectThrowawayForLocation(int x, int y, int z) {
IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z);
if (maybe != null && throwaway(true, item -> item instanceof ItemBlock && ((ItemBlock) item).getBlock().equals(maybe.getBlock()))) {
return true; // gotem
}
for (Item item : Baritone.settings().acceptableThrowawayItems.value) {
if (throwaway(true, item::equals)) {
return true;
}
}
return false;
}
private boolean throwaway(boolean select, Predicate<? super Item> desired) {
EntityPlayerSP p = ctx.player();
NonNullList<ItemStack> inv = p.inventory.mainInventory;
for (byte i = 0; i < 9; i++) {
ItemStack item = inv.get(i);
// this usage of settings() is okay because it's only called once during pathing
// (while creating the CalculationContext at the very beginning)
// and then it's called during execution
// since this function is never called during cost calculation, we don't need to migrate
// acceptableThrowawayItems to the CalculationContext
if (desired.test(item.getItem())) {
if (select) {
p.inventory.currentItem = i;
}
return true;
}
}
if (desired.test(p.inventory.offHandInventory.get(0).getItem())) {
// main hand takes precedence over off hand
// that means that if we have block A selected in main hand and block B in off hand, right clicking places block B
// we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem
// so we need to select in the main hand something that doesn't right click
// so not a shovel, not a hoe, not a block, etc
for (byte i = 0; i < 9; i++) {
ItemStack item = inv.get(i);
if (item.isEmpty() || item.getItem() instanceof ItemPickaxe) {
if (select) {
p.inventory.currentItem = i;
}
return true;
}
}
}
return false;
}
}

View File

@@ -53,7 +53,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior {
@Override
public void updateTarget(Rotation target, boolean force) {
this.target = target;
this.force = force || !Baritone.settings().freeLook.get();
this.force = force || !Baritone.settings().freeLook.value;
}
@Override
@@ -63,7 +63,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior {
}
// Whether or not we're going to silently set our angles
boolean silent = Baritone.settings().antiCheatCompatibility.get() && !this.force;
boolean silent = Baritone.settings().antiCheatCompatibility.value && !this.force;
switch (event.getState()) {
case PRE: {
@@ -73,7 +73,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior {
float desiredPitch = this.target.getPitch();
ctx.player().rotationPitch = desiredPitch;
if (desiredPitch == oldPitch) {
nudgeToLevel();
//nudgeToLevel();
}
this.target = null;
}
@@ -103,13 +103,13 @@ public final class LookBehavior extends Behavior implements ILookBehavior {
@Override
public void onPlayerRotationMove(RotationMoveEvent event) {
if (this.target != null && !this.force) {
if (this.target != null) {
event.setYaw(this.target.getYaw());
// If we have antiCheatCompatibility on, we're going to use the target value later in onPlayerUpdate()
// Also the type has to be MOTION_UPDATE because that is called after JUMP
if (!Baritone.settings().antiCheatCompatibility.get() && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE) {
if (!Baritone.settings().antiCheatCompatibility.value && event.getType() == RotationMoveEvent.Type.MOTION_UPDATE && !this.force) {
this.target = null;
}
}

View File

@@ -25,7 +25,6 @@ import baritone.api.event.events.TickEvent;
import baritone.api.event.events.type.EventState;
import baritone.cache.ContainerMemory;
import baritone.cache.Waypoint;
import baritone.pathing.movement.CalculationContext;
import baritone.utils.BlockStateInterface;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBed;
@@ -65,7 +64,7 @@ public final class MemoryBehavior extends Behavior {
@Override
public synchronized void onTick(TickEvent event) {
if (!Baritone.settings().containerMemory.get()) {
if (!Baritone.settings().containerMemory.value) {
return;
}
if (event.getType() == TickEvent.Type.OUT) {
@@ -83,7 +82,7 @@ public final class MemoryBehavior extends Behavior {
@Override
public synchronized void onSendPacket(PacketEvent event) {
if (!Baritone.settings().containerMemory.get()) {
if (!Baritone.settings().containerMemory.value) {
return;
}
Packet p = event.getPacket();
@@ -122,7 +121,7 @@ public final class MemoryBehavior extends Behavior {
@Override
public synchronized void onReceivePacket(PacketEvent event) {
if (!Baritone.settings().containerMemory.get()) {
if (!Baritone.settings().containerMemory.value) {
return;
}
Packet p = event.getPacket();
@@ -171,7 +170,7 @@ public final class MemoryBehavior extends Behavior {
private void updateInventory() {
if (!Baritone.settings().containerMemory.get()) {
if (!Baritone.settings().containerMemory.value) {
return;
}
int windowId = ctx.player().openContainer.windowId;
@@ -196,7 +195,7 @@ public final class MemoryBehavior extends Behavior {
}
private BlockPos neighboringConnectedBlock(BlockPos in) {
BlockStateInterface bsi = new CalculationContext(baritone).bsi;
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

View File

@@ -23,6 +23,7 @@ import baritone.api.event.events.*;
import baritone.api.pathing.calc.IPath;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalXZ;
import baritone.api.process.PathingCommand;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.PathCalculationResult;
import baritone.api.utils.interfaces.IGoalRenderPos;
@@ -33,6 +34,7 @@ import baritone.pathing.movement.MovementHelper;
import baritone.pathing.path.PathExecutor;
import baritone.utils.Helper;
import baritone.utils.PathRenderer;
import baritone.utils.PathingCommandContext;
import baritone.utils.pathing.Favoring;
import net.minecraft.util.math.BlockPos;
@@ -48,9 +50,11 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
private PathExecutor next;
private Goal goal;
private CalculationContext context;
private boolean safeToCancel;
private boolean pauseRequestedLastTick;
private boolean unpausedLastTick;
private boolean cancelRequested;
private boolean calcFailedLastTick;
@@ -106,10 +110,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
private void tickPath() {
if (pauseRequestedLastTick && safeToCancel) {
pauseRequestedLastTick = false;
baritone.getInputOverrideHandler().clearAllKeys();
baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock();
if (unpausedLastTick) {
baritone.getInputOverrideHandler().clearAllKeys();
baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock();
}
unpausedLastTick = false;
return;
}
unpausedLastTick = true;
if (cancelRequested) {
cancelRequested = false;
baritone.getInputOverrideHandler().clearAllKeys();
@@ -141,6 +149,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
logDebug("All done. At " + goal);
queuePathEvent(PathEvent.AT_GOAL);
next = null;
if (Baritone.settings().disconnectOnArrival.value) {
ctx.world().sendQuittingDisconnectingPacket();
}
return;
}
if (next != null && !next.getPath().positions().contains(ctx.playerFeet()) && !next.getPath().positions().contains(expectedSegmentStart)) { // can contain either one
@@ -170,7 +181,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
}
// we aren't calculating
queuePathEvent(PathEvent.CALC_STARTED);
findPathInNewThread(expectedSegmentStart, true);
findPathInNewThread(expectedSegmentStart, true, context);
}
return;
}
@@ -201,13 +212,13 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
// and this path doesn't get us all the way there
return;
}
if (ticksRemainingInSegment(false).get() < Baritone.settings().planningTickLookahead.get()) {
if (ticksRemainingInSegment(false).get() < Baritone.settings().planningTickLookahead.value) {
// and this path has 7.5 seconds or less left
// don't include the current movement so a very long last movement (e.g. descend) doesn't trip it up
// if we actually included current, it wouldn't start planning ahead until the last movement was done, if the last movement took more than 7.5 seconds on its own
logDebug("Path almost over. Planning ahead...");
queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED);
findPathInNewThread(current.getPath().getDest(), false);
findPathInNewThread(current.getPath().getDest(), false, context);
}
}
}
@@ -234,9 +245,32 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
this.goal = goal;
}
public boolean secretInternalSetGoalAndPath(Goal goal) {
secretInternalSetGoal(goal);
return secretInternalPath();
public boolean secretInternalSetGoalAndPath(PathingCommand command) {
secretInternalSetGoal(command.goal);
if (command instanceof PathingCommandContext) {
context = ((PathingCommandContext) command).desiredCalcContext;
} else {
context = new CalculationContext(baritone, true);
}
if (goal == null) {
return false;
}
if (goal.isInGoal(ctx.playerFeet()) || goal.isInGoal(expectedSegmentStart)) {
return false;
}
synchronized (pathPlanLock) {
if (current != null) {
return false;
}
synchronized (pathCalcLock) {
if (inProgress != null) {
return false;
}
queuePathEvent(PathEvent.CALC_STARTED);
findPathInNewThread(expectedSegmentStart, true, context);
return true;
}
}
}
@Override
@@ -324,39 +358,16 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
}
}
/**
* Start calculating a path if we aren't already
*
* @return true if this call started path calculation, false if it was already calculating or executing a path
*/
public boolean secretInternalPath() {
if (goal == null) {
return false;
}
if (goal.isInGoal(ctx.playerFeet())) {
return false;
}
synchronized (pathPlanLock) {
if (current != null) {
return false;
}
synchronized (pathCalcLock) {
if (inProgress != null) {
return false;
}
queuePathEvent(PathEvent.CALC_STARTED);
findPathInNewThread(expectedSegmentStart, true);
return true;
}
}
}
public void secretCursedFunctionDoNotCall(IPath path) {
synchronized (pathPlanLock) {
current = new PathExecutor(this, path);
}
}
public CalculationContext secretInternalGetCalculationContext() {
return context;
}
/**
* See issue #209
*
@@ -408,7 +419,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
* @param start
* @param talkAboutIt
*/
private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt) {
private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt, CalculationContext context) {
// this must be called with synchronization on pathCalcLock!
// actually, we can check this, muahaha
if (!Thread.holdsLock(pathCalcLock)) {
@@ -418,6 +429,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
if (inProgress != null) {
throw new IllegalStateException("Already doing it"); // should have been checked by caller
}
if (!context.safeForThreadedUse) {
throw new IllegalStateException("Improper context thread safety level");
}
Goal goal = this.goal;
if (goal == null) {
logDebug("no goal"); // TODO should this be an exception too? definitely should be checked by caller
@@ -426,13 +440,12 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
long primaryTimeout;
long failureTimeout;
if (current == null) {
primaryTimeout = Baritone.settings().primaryTimeoutMS.get();
failureTimeout = Baritone.settings().failureTimeoutMS.get();
primaryTimeout = Baritone.settings().primaryTimeoutMS.value;
failureTimeout = Baritone.settings().failureTimeoutMS.value;
} else {
primaryTimeout = Baritone.settings().planAheadPrimaryTimeoutMS.get();
failureTimeout = Baritone.settings().planAheadFailureTimeoutMS.get();
primaryTimeout = Baritone.settings().planAheadPrimaryTimeoutMS.value;
failureTimeout = Baritone.settings().planAheadFailureTimeoutMS.value;
}
CalculationContext context = new CalculationContext(baritone, true); // not safe to create on the other thread, it looks up a lot of stuff in minecraft
AbstractNodeCostSearch pathfinder = createPathfinder(start, goal, current == null ? null : current.getPath(), context);
if (!Objects.equals(pathfinder.getGoal(), goal)) { // will return the exact same object if simplification didn't happen
logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance");
@@ -494,13 +507,13 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior,
public static AbstractNodeCostSearch createPathfinder(BlockPos start, Goal goal, IPath previous, CalculationContext context) {
Goal transformed = goal;
if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) {
if (Baritone.settings().simplifyUnloadedYCoord.value && goal instanceof IGoalRenderPos) {
BlockPos pos = ((IGoalRenderPos) goal).getGoalPos();
if (!context.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ())) {
transformed = new GoalXZ(pos.getX(), pos.getZ());
}
}
Favoring favoring = new Favoring(context.getBaritone().getPlayerContext(), previous);
Favoring favoring = new Favoring(context.getBaritone().getPlayerContext(), previous, context);
return new AStarPathFinder(start.getX(), start.getY(), start.getZ(), transformed, favoring, context);
}

View File

@@ -18,6 +18,7 @@
package baritone.cache;
import baritone.utils.pathing.PathingBlockType;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
@@ -85,6 +86,8 @@ public final class CachedChunk {
temp.add(Blocks.END_GATEWAY);
temp.add(Blocks.WEB);
temp.add(Blocks.NETHER_WART);
temp.add(Blocks.LADDER);
temp.add(Blocks.VINE);
BLOCKS_TO_KEEP_TRACK_OF = Collections.unmodifiableSet(temp);
}
@@ -117,6 +120,8 @@ public final class CachedChunk {
*/
private final BitSet data;
private final Int2ObjectOpenHashMap<String> special;
/**
* The block names of each surface level block for generating an overview
*/
@@ -138,12 +143,30 @@ public final class CachedChunk {
this.heightMap = new int[256];
this.specialBlockLocations = specialBlockLocations;
this.cacheTimestamp = cacheTimestamp;
if (specialBlockLocations.isEmpty()) {
this.special = null;
} else {
this.special = new Int2ObjectOpenHashMap<>();
setSpecial();
}
calculateHeightMap();
}
private final void setSpecial() {
for (Map.Entry<String, List<BlockPos>> entry : specialBlockLocations.entrySet()) {
for (BlockPos pos : entry.getValue()) {
special.put(getPositionIndex(pos.getX(), pos.getY(), pos.getZ()), entry.getKey());
}
}
}
public final IBlockState getBlock(int x, int y, int z, int dimension) {
int index = getPositionIndex(x, y, z);
PathingBlockType type = getType(index);
int internalPos = z << 4 | x;
if (heightMap[internalPos] == y) {
if (heightMap[internalPos] == y && type != PathingBlockType.AVOID) {
// if the top block in a column is water, we cache it as AVOID but we don't want to just return default state water (which is not flowing) beacuse then it would try to path through it
// we have this exact block, it's a surface block
/*System.out.println("Saying that " + x + "," + y + "," + z + " is " + state);
if (!Minecraft.getMinecraft().world.getBlockState(new BlockPos(x + this.x * 16, y, z + this.z * 16)).getBlock().equals(state.getBlock())) {
@@ -151,15 +174,20 @@ public final class CachedChunk {
}*/
return overview[internalPos];
}
PathingBlockType type = getType(x, y, z);
if (special != null) {
String str = special.get(index);
if (str != null) {
return ChunkPacker.stringToBlock(str).getDefaultState();
}
}
if (type == PathingBlockType.SOLID && y == 127 && dimension == -1) {
return Blocks.BEDROCK.getDefaultState();
}
return ChunkPacker.pathingTypeToBlock(type, dimension);
}
private PathingBlockType getType(int x, int y, int z) {
int index = getPositionIndex(x, y, z);
private PathingBlockType getType(int index) {
return PathingBlockType.fromBits(data.get(index), data.get(index + 1));
}
@@ -187,11 +215,11 @@ public final class CachedChunk {
return specialBlockLocations;
}
public final LinkedList<BlockPos> getAbsoluteBlocks(String blockType) {
public final ArrayList<BlockPos> getAbsoluteBlocks(String blockType) {
if (specialBlockLocations.get(blockType) == null) {
return null;
}
LinkedList<BlockPos> res = new LinkedList<>();
ArrayList<BlockPos> res = new ArrayList<>();
for (BlockPos pos : specialBlockLocations.get(blockType)) {
res.add(new BlockPos(pos.getX() + x * 16, pos.getY(), pos.getZ() + z * 16));
}

View File

@@ -87,19 +87,16 @@ public final class CachedRegion implements ICachedRegion {
return chunks[x >> 4][z >> 4] != null;
}
public final LinkedList<BlockPos> getLocationsOf(String block) {
LinkedList<BlockPos> res = new LinkedList<>();
public final ArrayList<BlockPos> getLocationsOf(String block) {
ArrayList<BlockPos> res = new ArrayList<>();
for (int chunkX = 0; chunkX < 32; chunkX++) {
for (int chunkZ = 0; chunkZ < 32; chunkZ++) {
if (chunks[chunkX][chunkZ] == null) {
continue;
}
List<BlockPos> locs = chunks[chunkX][chunkZ].getAbsoluteBlocks(block);
if (locs == null) {
continue;
}
for (BlockPos pos : locs) {
res.add(pos);
ArrayList<BlockPos> locs = chunks[chunkX][chunkZ].getAbsoluteBlocks(block);
if (locs != null) {
res.addAll(locs);
}
}
}
@@ -306,7 +303,7 @@ public final class CachedRegion implements ICachedRegion {
}
public synchronized final void removeExpired() {
long expiry = Baritone.settings().cachedChunksExpirySeconds.get();
long expiry = Baritone.settings().cachedChunksExpirySeconds.value;
if (expiry < 0) {
return;
}

View File

@@ -32,7 +32,6 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
@@ -45,7 +44,7 @@ public final class CachedWorld implements ICachedWorld, Helper {
/**
* The maximum number of regions in any direction from (0,0)
*/
private static final int REGION_MAX = 58594;
private static final int REGION_MAX = 30_000_000 / 512 + 1;
/**
* A map of all of the cached regions.
@@ -108,9 +107,13 @@ public final class CachedWorld implements ICachedWorld, Helper {
return region.isCached(blockX & 511, blockZ & 511);
}
public final boolean regionLoaded(int blockX, int blockZ) {
return getRegion(blockX >> 9, blockZ >> 9) != null;
}
@Override
public final LinkedList<BlockPos> getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq) {
LinkedList<BlockPos> res = new LinkedList<>();
public final ArrayList<BlockPos> getLocationsOf(String block, int maximum, int centerX, int centerZ, int maxRegionDistanceSq) {
ArrayList<BlockPos> res = new ArrayList<>();
int centerRegionX = centerX >> 9;
int centerRegionZ = centerZ >> 9;
@@ -127,7 +130,7 @@ public final class CachedWorld implements ICachedWorld, Helper {
CachedRegion region = getOrCreateRegion(regionX, regionZ);
if (region != null) {
// TODO: 100% verify if this or addAll is faster.
region.getLocationsOf(block).forEach(res::add);
res.addAll(region.getLocationsOf(block));
}
}
}
@@ -146,7 +149,7 @@ public final class CachedWorld implements ICachedWorld, Helper {
@Override
public final void save() {
if (!Baritone.settings().chunkCaching.get()) {
if (!Baritone.settings().chunkCaching.value) {
System.out.println("Not saving to disk; chunk caching is disabled.");
allRegions().forEach(region -> {
if (region != null) {
@@ -171,7 +174,7 @@ public final class CachedWorld implements ICachedWorld, Helper {
* Delete regions that are too far from the player
*/
private synchronized void prune() {
if (!Baritone.settings().pruneRegionsFromRAM.get()) {
if (!Baritone.settings().pruneRegionsFromRAM.value) {
return;
}
BlockPos pruneCenter = guessPosition();

View File

@@ -19,10 +19,7 @@ package baritone.cache;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.pathing.PathingBlockType;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDoublePlant;
import net.minecraft.block.BlockFlower;
import net.minecraft.block.BlockTallGrass;
import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.ResourceLocation;
@@ -73,7 +70,7 @@ public final class ChunkPacker {
for (int x = 0; x < 16; x++) {
int index = CachedChunk.getPositionIndex(x, y, z);
IBlockState state = bsc.get(x, y1, z);
boolean[] bits = getPathingBlockType(state).getBits();
boolean[] bits = getPathingBlockType(state, chunk, x, y, z).getBits();
bitSet.set(index, bits[0]);
bitSet.set(index + 1, bits[1]);
Block block = state.getBlock();
@@ -93,7 +90,8 @@ public final class ChunkPacker {
IBlockState[] blocks = new IBlockState[256];
for (int z = 0; z < 16; z++) {
https://www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html
https:
//www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html
for (int x = 0; x < 16; x++) {
for (int y = 255; y >= 0; y--) {
int index = CachedChunk.getPositionIndex(x, y, z);
@@ -122,11 +120,23 @@ public final class ChunkPacker {
return resourceCache.computeIfAbsent(name, n -> Block.getBlockFromName(n.contains(":") ? n : "minecraft:" + n));
}
private static PathingBlockType getPathingBlockType(IBlockState state) {
private static PathingBlockType getPathingBlockType(IBlockState state, Chunk chunk, int x, int y, int z) {
Block block = state.getBlock();
if ((block == Blocks.WATER || block == Blocks.FLOWING_WATER) && !MovementHelper.isFlowing(state)) {
if (block == Blocks.WATER || block == Blocks.FLOWING_WATER) {
// only water source blocks are plausibly usable, flowing water should be avoid
// FLOWING_WATER is a waterfall, it doesn't really matter and caching it as AVOID just makes it look wrong
if (MovementHelper.possiblyFlowing(state)) {
return PathingBlockType.AVOID;
}
if (x == 0 || x == 15 || z == 0 || z == 15) {
if (BlockLiquid.getSlopeAngle(chunk.getWorld(), new BlockPos(x + chunk.x << 4, y, z + chunk.z << 4), state.getMaterial(), state) == -1000.0F) {
return PathingBlockType.WATER;
}
return PathingBlockType.AVOID;
}
if (MovementHelper.possiblyFlowing(chunk.getBlockState(x + 1, y, z)) || MovementHelper.possiblyFlowing(chunk.getBlockState(x - 1, y, z)) || MovementHelper.possiblyFlowing(chunk.getBlockState(x, y, z + 1)) || MovementHelper.possiblyFlowing(chunk.getBlockState(x, y, z - 1))) {
return PathingBlockType.AVOID;
}
return PathingBlockType.WATER;
}

View File

@@ -70,7 +70,7 @@ public class ContainerMemory implements IContainerMemory {
}
public synchronized void save() throws IOException {
if (!Baritone.settings().containerMemory.get()) {
if (!Baritone.settings().containerMemory.value) {
return;
}
ByteBuf buf = Unpooled.buffer(0, Integer.MAX_VALUE);

View File

@@ -62,20 +62,20 @@ public final class AStarPathFinder extends AbstractNodeCostSearch {
MutableMoveResult res = new MutableMoveResult();
BetterWorldBorder worldBorder = new BetterWorldBorder(calcContext.world.getWorldBorder());
long startTime = System.currentTimeMillis();
boolean slowPath = Baritone.settings().slowPath.get();
boolean slowPath = Baritone.settings().slowPath.value;
if (slowPath) {
logDebug("slowPath is on, path timeout will be " + Baritone.settings().slowPathTimeoutMS.<Long>get() + "ms instead of " + primaryTimeout + "ms");
logDebug("slowPath is on, path timeout will be " + Baritone.settings().slowPathTimeoutMS.value + "ms instead of " + primaryTimeout + "ms");
}
long primaryTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.<Long>get() : primaryTimeout);
long failureTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.<Long>get() : failureTimeout);
long primaryTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.value : primaryTimeout);
long failureTimeoutTime = startTime + (slowPath ? Baritone.settings().slowPathTimeoutMS.value : failureTimeout);
boolean failing = true;
int numNodes = 0;
int numMovementsConsidered = 0;
int numEmptyChunk = 0;
boolean isFavoring = !favoring.isEmpty();
int timeCheckInterval = 1 << 6;
int pathingMaxChunkBorderFetch = Baritone.settings().pathingMaxChunkBorderFetch.get(); // grab all settings beforehand so that changing settings during pathing doesn't cause a crash or unpredictable behavior
double minimumImprovement = Baritone.settings().minimumImprovementRepropagation.get() ? MIN_IMPROVEMENT : 0;
int pathingMaxChunkBorderFetch = Baritone.settings().pathingMaxChunkBorderFetch.value; // grab all settings beforehand so that changing settings during pathing doesn't cause a crash or unpredictable behavior
double minimumImprovement = Baritone.settings().minimumImprovementRepropagation.value ? MIN_IMPROVEMENT : 0;
while (!openSet.isEmpty() && numEmptyChunk < pathingMaxChunkBorderFetch && !cancelRequested) {
if ((numNodes & (timeCheckInterval - 1)) == 0) { // only call this once every 64 nodes (about half a millisecond)
long now = System.currentTimeMillis(); // since nanoTime is slow on windows (takes many microseconds)
@@ -85,7 +85,7 @@ public final class AStarPathFinder extends AbstractNodeCostSearch {
}
if (slowPath) {
try {
Thread.sleep(Baritone.settings().slowPathTimeDelayMS.<Long>get());
Thread.sleep(Baritone.settings().slowPathTimeDelayMS.value);
} catch (InterruptedException ex) {
}
}

View File

@@ -87,7 +87,7 @@ public abstract class AbstractNodeCostSearch implements IPathFinder, Helper {
this.startZ = startZ;
this.goal = goal;
this.context = context;
this.map = new Long2ObjectOpenHashMap<>(Baritone.settings().pathingMapDefaultSize.value, Baritone.settings().pathingMapLoadFactor.get());
this.map = new Long2ObjectOpenHashMap<>(Baritone.settings().pathingMapDefaultSize.value, Baritone.settings().pathingMapLoadFactor.value);
}
public void cancel() {

View File

@@ -34,6 +34,8 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import static baritone.api.pathing.movement.ActionCosts.COST_INF;
/**
* @author Brady
* @since 8/7/2018
@@ -42,6 +44,7 @@ public class CalculationContext {
private static final ItemStack STACK_BUCKET_WATER = new ItemStack(Items.WATER_BUCKET);
public final boolean safeForThreadedUse;
public final IBaritone baritone;
public final World world;
public final WorldData worldData;
@@ -50,7 +53,7 @@ public class CalculationContext {
public final boolean hasWaterBucket;
public final boolean hasThrowaway;
public final boolean canSprint;
public final double placeBlockCost;
protected final double placeBlockCost; // protected because you should call the function instead
public final boolean allowBreak;
public final boolean allowParkour;
public final boolean allowParkourPlace;
@@ -61,7 +64,8 @@ public class CalculationContext {
public final int maxFallHeightBucket;
public final double waterWalkSpeed;
public final double breakBlockAdditionalCost;
public final double jumpPenalty;
public double backtrackCostFavoringCoefficient;
public double jumpPenalty;
public final double walkOnWaterOnePenalty;
public final BetterWorldBorder worldBorder;
@@ -70,33 +74,35 @@ public class CalculationContext {
}
public CalculationContext(IBaritone baritone, boolean forUseOnAnotherThread) {
this.safeForThreadedUse = forUseOnAnotherThread;
this.baritone = baritone;
EntityPlayerSP player = baritone.getPlayerContext().player();
this.world = baritone.getPlayerContext().world();
this.worldData = (WorldData) baritone.getWorldProvider().getCurrentWorld();
this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); // TODO TODO TODO
this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread);
this.toolSet = new ToolSet(player);
this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(baritone.getPlayerContext(), false);
this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether();
this.canSprint = Baritone.settings().allowSprint.get() && player.getFoodStats().getFoodLevel() > 6;
this.placeBlockCost = Baritone.settings().blockPlacementPenalty.get();
this.allowBreak = Baritone.settings().allowBreak.get();
this.allowParkour = Baritone.settings().allowParkour.get();
this.allowParkourPlace = Baritone.settings().allowParkourPlace.get();
this.allowJumpAt256 = Baritone.settings().allowJumpAt256.get();
this.assumeWalkOnWater = Baritone.settings().assumeWalkOnWater.get();
this.allowDiagonalDescend = Baritone.settings().allowDiagonalDescend.get();
this.maxFallHeightNoWater = Baritone.settings().maxFallHeightNoWater.get();
this.maxFallHeightBucket = Baritone.settings().maxFallHeightBucket.get();
this.hasThrowaway = Baritone.settings().allowPlace.value && ((Baritone) baritone).getInventoryBehavior().hasGenericThrowaway();
this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.value && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether();
this.canSprint = Baritone.settings().allowSprint.value && player.getFoodStats().getFoodLevel() > 6;
this.placeBlockCost = Baritone.settings().blockPlacementPenalty.value;
this.allowBreak = Baritone.settings().allowBreak.value;
this.allowParkour = Baritone.settings().allowParkour.value;
this.allowParkourPlace = Baritone.settings().allowParkourPlace.value;
this.allowJumpAt256 = Baritone.settings().allowJumpAt256.value;
this.assumeWalkOnWater = Baritone.settings().assumeWalkOnWater.value;
this.allowDiagonalDescend = Baritone.settings().allowDiagonalDescend.value;
this.maxFallHeightNoWater = Baritone.settings().maxFallHeightNoWater.value;
this.maxFallHeightBucket = Baritone.settings().maxFallHeightBucket.value;
int depth = EnchantmentHelper.getDepthStriderModifier(player);
if (depth > 3) {
depth = 3;
}
float mult = depth / 3.0F;
this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - mult) + ActionCosts.WALK_ONE_BLOCK_COST * mult;
this.breakBlockAdditionalCost = Baritone.settings().blockBreakAdditionalPenalty.get();
this.jumpPenalty = Baritone.settings().jumpPenalty.get();
this.walkOnWaterOnePenalty = Baritone.settings().walkOnWaterOnePenalty.get();
this.breakBlockAdditionalCost = Baritone.settings().blockBreakAdditionalPenalty.value;
this.backtrackCostFavoringCoefficient = Baritone.settings().backtrackCostFavoringCoefficient.value;
this.jumpPenalty = Baritone.settings().jumpPenalty.value;
this.walkOnWaterOnePenalty = Baritone.settings().walkOnWaterOnePenalty.value;
// why cache these things here, why not let the movements just get directly from settings?
// because if some movements are calculated one way and others are calculated another way,
// then you get a wildly inconsistent path that isn't optimal for either scenario.
@@ -123,21 +129,32 @@ public class CalculationContext {
return get(x, y, z).getBlock();
}
public boolean canPlaceThrowawayAt(int x, int y, int z) {
public double costOfPlacingAt(int x, int y, int z) {
if (!hasThrowaway) { // only true if allowPlace is true, see constructor
return false;
return COST_INF;
}
if (isPossiblyProtected(x, y, z)) {
return false;
return COST_INF;
}
return worldBorder.canPlaceAt(x, z); // TODO perhaps MovementHelper.canPlaceAgainst could also use this?
if (!worldBorder.canPlaceAt(x, z)) {
// TODO perhaps MovementHelper.canPlaceAgainst could also use this?
return COST_INF;
}
return placeBlockCost;
}
public boolean canBreakAt(int x, int y, int z) {
public double breakCostMultiplierAt(int x, int y, int z) {
if (!allowBreak) {
return false;
return COST_INF;
}
return !isPossiblyProtected(x, y, z);
if (isPossiblyProtected(x, y, z)) {
return COST_INF;
}
return 1;
}
public double placeBucketCost() {
return placeBlockCost; // shrug
}
public boolean isPossiblyProtected(int x, int y, int z) {

View File

@@ -34,7 +34,7 @@ import java.util.Optional;
public abstract class Movement implements IMovement, MovementHelper {
protected static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN};
public static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN};
protected final IBaritone baritone;
protected final IPlayerContext ctx;
@@ -76,31 +76,28 @@ public abstract class Movement implements IMovement, MovementHelper {
this(baritone, src, dest, toBreak, null);
}
@Override
public double getCost() {
public double getCost() throws NullPointerException {
return cost;
}
public double getCost(CalculationContext context) {
if (cost == null) {
cost = calculateCost(new CalculationContext(baritone));
cost = calculateCost(context);
}
return cost;
}
public abstract double calculateCost(CalculationContext context);
@Override
public double recalculateCost() {
public double recalculateCost(CalculationContext context) {
cost = null;
return getCost();
return getCost(context);
}
public void override(double cost) {
this.cost = cost;
}
@Override
public double calculateCostWithoutCaching() {
return calculateCost(new CalculationContext(baritone));
}
/**
* Handles the execution of the latest Movement
* State, and offers a Status to the calling class.

View File

@@ -30,16 +30,14 @@ import baritone.utils.ToolSet;
import net.minecraft.block.*;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemPickaxe;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import java.util.Optional;
import static baritone.pathing.movement.Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP;
/**
@@ -74,7 +72,7 @@ public interface MovementHelper extends ActionCosts, Helper {
if (block == Blocks.AIR) { // early return for most common case
return true;
}
if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.WEB || block == Blocks.END_PORTAL || block == Blocks.COCOA) {
if (block == Blocks.FIRE || block == Blocks.TRIPWIRE || block == Blocks.WEB || block == Blocks.END_PORTAL || block == Blocks.COCOA || block instanceof BlockSkull) {
return false;
}
if (block instanceof BlockDoor || block instanceof BlockFenceGate) {
@@ -83,6 +81,9 @@ public interface MovementHelper extends ActionCosts, Helper {
// be opened by just interacting.
return block != Blocks.IRON_DOOR;
}
if (block == Blocks.CARPET) {
return canWalkOn(bsi, x, y - 1, z);
}
boolean snow = block instanceof BlockSnow;
boolean trapdoor = block instanceof BlockTrapDoor;
if (snow || trapdoor) {
@@ -107,11 +108,11 @@ public interface MovementHelper extends ActionCosts, Helper {
}
throw new IllegalStateException();
}
if (isFlowing(state)) {
if (isFlowing(x, y, z, state, bsi)) {
return false; // Don't walk through flowing liquids
}
if (block instanceof BlockLiquid) {
if (Baritone.settings().assumeWalkOnWater.get()) {
if (Baritone.settings().assumeWalkOnWater.value) {
return false;
}
IBlockState up = bsi.get0(x, y + 1, z);
@@ -157,7 +158,8 @@ public interface MovementHelper extends ActionCosts, Helper {
|| block instanceof BlockSnow
|| block instanceof BlockLiquid
|| block instanceof BlockTrapDoor
|| block instanceof BlockEndPortal) {
|| block instanceof BlockEndPortal
|| block instanceof BlockSkull) {
return false;
}
// door, fence gate, liquid, trapdoor have been accounted for, nothing else uses the world or pos parameters
@@ -272,7 +274,7 @@ public interface MovementHelper extends ActionCosts, Helper {
if (state.isBlockNormalCube()) {
return true;
}
if (block == Blocks.LADDER || (block == Blocks.VINE && Baritone.settings().allowVines.get())) { // TODO reconsider this
if (block == Blocks.LADDER || (block == Blocks.VINE && Baritone.settings().allowVines.value)) { // TODO reconsider this
return true;
}
if (block == Blocks.FARMLAND || block == Blocks.GRASS_PATH) {
@@ -285,22 +287,22 @@ public interface MovementHelper extends ActionCosts, Helper {
// since this is called literally millions of times per second, the benefit of not allocating millions of useless "pos.up()"
// BlockPos s that we'd just garbage collect immediately is actually noticeable. I don't even think its a decrease in readability
Block up = bsi.get0(x, y + 1, z).getBlock();
if (up == Blocks.WATERLILY) {
if (up == Blocks.WATERLILY || up == Blocks.CARPET) {
return true;
}
if (isFlowing(state) || block == Blocks.FLOWING_WATER) {
if (isFlowing(x, y, z, state, bsi) || block == Blocks.FLOWING_WATER) {
// the only scenario in which we can walk on flowing water is if it's under still water with jesus off
return isWater(up) && !Baritone.settings().assumeWalkOnWater.get();
return isWater(up) && !Baritone.settings().assumeWalkOnWater.value;
}
// if assumeWalkOnWater is on, we can only walk on water if there isn't water above it
// if assumeWalkOnWater is off, we can only walk on water if there is water above it
return isWater(up) ^ Baritone.settings().assumeWalkOnWater.get();
return isWater(up) ^ Baritone.settings().assumeWalkOnWater.value;
}
if (block == Blocks.GLASS || block == Blocks.STAINED_GLASS) {
return true;
}
if (block instanceof BlockSlab) {
if (!Baritone.settings().allowWalkOnBottomSlab.get()) {
if (!Baritone.settings().allowWalkOnBottomSlab.value) {
if (((BlockSlab) block).isDouble()) {
return true;
}
@@ -324,20 +326,22 @@ public interface MovementHelper extends ActionCosts, Helper {
}
static boolean canPlaceAgainst(BlockStateInterface bsi, int x, int y, int z) {
return canPlaceAgainst(bsi.get0(x, y, z));
return canPlaceAgainst(bsi, x, y, z, bsi.get0(x, y, z));
}
static boolean canPlaceAgainst(BlockStateInterface bsi, BlockPos pos) {
return canPlaceAgainst(bsi.get0(pos.getX(), pos.getY(), pos.getZ()));
return canPlaceAgainst(bsi, pos.getX(), pos.getY(), pos.getZ());
}
static boolean canPlaceAgainst(IPlayerContext ctx, BlockPos pos) {
return canPlaceAgainst(new BlockStateInterface(ctx), pos);
}
static boolean canPlaceAgainst(IBlockState state) {
// TODO isBlockNormalCube isn't the best check for whether or not we can place a block against it. e.g. glass isn't normalCube but we can place against it
return state.isBlockNormalCube();
static boolean canPlaceAgainst(BlockStateInterface bsi, int x, int y, int z, IBlockState state) {
// can we look at the center of a side face of this block and likely be able to place?
// (thats how this check is used)
// therefore dont include weird things that we technically could place against (like carpet) but practically can't
return state.isBlockNormalCube() || state.isFullBlock() || state.getBlock() == Blocks.GLASS || state.getBlock() == Blocks.STAINED_GLASS;
}
static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, boolean includeFalling) {
@@ -347,7 +351,8 @@ public interface MovementHelper extends ActionCosts, Helper {
static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, IBlockState state, boolean includeFalling) {
Block block = state.getBlock();
if (!canWalkThrough(context.bsi, x, y, z, state)) {
if (!context.canBreakAt(x, y, z)) {
double mult = context.breakCostMultiplierAt(x, y, z);
if (mult >= COST_INF) {
return COST_INF;
}
if (avoidBreaking(context.bsi, x, y, z, state)) {
@@ -364,6 +369,7 @@ public interface MovementHelper extends ActionCosts, Helper {
double result = m / strVsBlock;
result += context.breakBlockAdditionalCost;
result *= mult;
if (includeFalling) {
IBlockState above = context.get(x, y + 1, z);
if (above.getBlock() instanceof BlockFalling) {
@@ -402,42 +408,6 @@ public interface MovementHelper extends ActionCosts, Helper {
ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock());
}
static boolean throwaway(IPlayerContext ctx, boolean select) {
EntityPlayerSP p = ctx.player();
NonNullList<ItemStack> inv = p.inventory.mainInventory;
for (byte i = 0; i < 9; i++) {
ItemStack item = inv.get(i);
// this usage of settings() is okay because it's only called once during pathing
// (while creating the CalculationContext at the very beginning)
// and then it's called during execution
// since this function is never called during cost calculation, we don't need to migrate
// acceptableThrowawayItems to the CalculationContext
if (Baritone.settings().acceptableThrowawayItems.get().contains(item.getItem())) {
if (select) {
p.inventory.currentItem = i;
}
return true;
}
}
if (Baritone.settings().acceptableThrowawayItems.get().contains(p.inventory.offHandInventory.get(0).getItem())) {
// main hand takes precedence over off hand
// that means that if we have block A selected in main hand and block B in off hand, right clicking places block B
// we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem
// so we need to select in the main hand something that doesn't right click
// so not a shovel, not a hoe, not a block, etc
for (byte i = 0; i < 9; i++) {
ItemStack item = inv.get(i);
if (item.isEmpty() || item.getItem() instanceof ItemPickaxe) {
if (select) {
p.inventory.currentItem = i;
}
return true;
}
}
}
return false;
}
static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) {
state.setTarget(new MovementTarget(
new Rotation(RotationUtils.calcRotationFromVec3d(ctx.playerHead(),
@@ -485,20 +455,38 @@ public interface MovementHelper extends ActionCosts, Helper {
return BlockStateInterface.getBlock(ctx, p) instanceof BlockLiquid;
}
static boolean isFlowing(IBlockState state) {
static boolean possiblyFlowing(IBlockState state) {
// Will be IFluidState in 1.13
return state.getBlock() instanceof BlockLiquid
&& state.getValue(BlockLiquid.LEVEL) != 0;
}
static boolean isFlowing(int x, int y, int z, IBlockState state, BlockStateInterface bsi) {
if (!(state.getBlock() instanceof BlockLiquid)) {
return false;
}
if (state.getValue(BlockLiquid.LEVEL) != 0) {
return true;
}
return possiblyFlowing(bsi.get0(x + 1, y, z))
|| possiblyFlowing(bsi.get0(x - 1, y, z))
|| possiblyFlowing(bsi.get0(x, y, z + 1))
|| possiblyFlowing(bsi.get0(x, y, z - 1));
}
static PlaceResult attemptToPlaceABlock(MovementState state, IBaritone baritone, BlockPos placeAt, boolean preferDown) {
IPlayerContext ctx = baritone.getPlayerContext();
Optional<Rotation> direct = RotationUtils.reachable(ctx, placeAt); // we assume that if there is a block there, it must be replacable
boolean found = false;
if (direct.isPresent()) {
state.setTarget(new MovementState.MovementTarget(direct.get(), true));
found = true;
}
for (int i = 0; i < 5; i++) {
BlockPos against1 = placeAt.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]);
if (MovementHelper.canPlaceAgainst(ctx, against1)) {
//if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(placeAt.getX(), placeAt.getY(), placeAt.getZ())) { // get ready to place a throwaway block
if (!throwaway(ctx, true)) {
if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(placeAt.getX(), placeAt.getY(), placeAt.getZ())) { // get ready to place a throwaway block
Helper.HELPER.logDebug("bb pls get me some blocks. dirt or cobble");
state.setStatus(MovementStatus.UNREACHABLE);
return PlaceResult.NO_OPTION;

View File

@@ -53,14 +53,16 @@ public class MovementAscend extends Movement {
public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) {
IBlockState toPlace = context.get(destX, y, destZ);
boolean hasToPlace = false;
double additionalPlacementCost = 0;
if (!MovementHelper.canWalkOn(context.bsi, destX, y, destZ, toPlace)) {
if (!context.canPlaceThrowawayAt(destX, y, destZ)) {
additionalPlacementCost = context.costOfPlacingAt(destX, y, destZ);
if (additionalPlacementCost >= COST_INF) {
return COST_INF;
}
if (!MovementHelper.isReplacable(destX, y, destZ, toPlace, context.bsi)) {
return COST_INF;
}
boolean foundPlaceOption = false;
for (int i = 0; i < 5; i++) {
int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset();
int againstY = y + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getYOffset();
@@ -69,11 +71,11 @@ public class MovementAscend extends Movement {
continue;
}
if (MovementHelper.canPlaceAgainst(context.bsi, againstX, againstY, againstZ)) {
hasToPlace = true;
foundPlaceOption = true;
break;
}
}
if (!hasToPlace) { // didn't find a valid place =(
if (!foundPlaceOption) { // didn't find a valid place =(
return COST_INF;
}
}
@@ -124,10 +126,7 @@ public class MovementAscend extends Movement {
walk += context.jumpPenalty;
}
double totalCost = walk;
if (hasToPlace) {
totalCost += context.placeBlockCost;
}
double totalCost = walk + additionalPlacementCost;
// start with srcUp2 since we already have its state
// includeFalling isn't needed because of the falling check above -- if srcUp3 is falling we will have already exited with COST_INF if we'd actually have to break it
totalCost += MovementHelper.getMiningDurationTicks(context, x, y + 2, z, srcUp2, false);
@@ -155,6 +154,10 @@ public class MovementAscend extends Movement {
return state.setStatus(MovementStatus.SUCCESS);
}
if (ctx.playerFeet().y < src.y) {
return state.setStatus(MovementStatus.UNREACHABLE);
}
IBlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace);
if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) {
ticksWithoutPlacement++;
@@ -176,19 +179,26 @@ public class MovementAscend extends Movement {
return state; // don't jump while walking from a non double slab into a bottom slab
}
if (Baritone.settings().assumeStep.get() || ctx.playerFeet().equals(src.up())) {
if (Baritone.settings().assumeStep.value || ctx.playerFeet().equals(src.up())) {
// no need to hit space if we're already jumping
return state;
}
int xAxis = Math.abs(src.getX() - dest.getX()); // either 0 or 1
int zAxis = Math.abs(src.getZ() - dest.getZ()); // either 0 or 1
double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
double lateralMotion = xAxis * ctx.player().motionZ + zAxis * ctx.player().motionX;
if (Math.abs(lateralMotion) > 0.1) {
return state;
}
if (headBonkClear()) {
return state.setInput(Input.JUMP, true);
}
int xAxis = Math.abs(src.getX() - dest.getX()); // either 0 or 1
int zAxis = Math.abs(src.getZ() - dest.getZ()); // either 0 or 1
double flatDistToNext = xAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + zAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
double sideDist = zAxis * Math.abs((dest.getX() + 0.5D) - ctx.player().posX) + xAxis * Math.abs((dest.getZ() + 0.5D) - ctx.player().posZ);
// System.out.println(flatDistToNext + " " + sideDist);
if (flatDistToNext > 1.2 || sideDist > 0.2) {
return state;
@@ -211,4 +221,10 @@ public class MovementAscend extends Movement {
}
return true;
}
@Override
public boolean safeToCancel(MovementState state) {
// if we had to place, don't allow pause
return state.getStatus() != MovementStatus.RUNNING || ticksWithoutPlacement == 0;
}
}

View File

@@ -122,7 +122,7 @@ public class MovementDescend extends Movement {
// and potentially replace the water we're going to fall into
return false;
}
if (!MovementHelper.canWalkThrough(context.bsi, destX, y - 2, destZ, below) && below.getBlock() != Blocks.WATER) {
if (!MovementHelper.canWalkThrough(context.bsi, destX, y - 2, destZ, below)) {
return false;
}
double costSoFar = 0;
@@ -137,13 +137,14 @@ public class MovementDescend extends Movement {
IBlockState ontoBlock = context.get(destX, newY, destZ);
int unprotectedFallHeight = fallHeight - (y - effectiveStartHeight); // equal to fallHeight - y + effectiveFallHeight, which is equal to -newY + effectiveFallHeight, which is equal to effectiveFallHeight - newY
double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[unprotectedFallHeight] + frontBreak + costSoFar;
if ((ontoBlock.getBlock() == Blocks.WATER || ontoBlock.getBlock() == Blocks.FLOWING_WATER) && context.getBlock(destX, newY + 1, destZ) != Blocks.WATERLILY) {
// lilypads are canWalkThrough, but we can't end a fall that should be broken by water if it's covered by a lilypad
// however, don't return impossible in the lilypad scenario, because we could still jump right on it (water that's below a lilypad is canWalkOn so it works)
if (MovementHelper.isWater(ontoBlock.getBlock())) {
if (!MovementHelper.canWalkThrough(context.bsi, destX, newY, destZ, ontoBlock)) {
return false;
}
if (context.assumeWalkOnWater) {
return false; // TODO fix
}
if (MovementHelper.isFlowing(ontoBlock)) {
if (MovementHelper.isFlowing(destX, newY, destZ, ontoBlock, context.bsi)) {
return false; // TODO flowing check required here?
}
if (!MovementHelper.canWalkOn(context.bsi, destX, newY - 1, destZ)) {
@@ -186,7 +187,7 @@ public class MovementDescend extends Movement {
res.x = destX;
res.y = newY + 1;// this is the block we're falling onto, so dest is +1
res.z = destZ;
res.cost = tentativeCost + context.placeBlockCost;
res.cost = tentativeCost + context.placeBucketCost();
return true;
} else {
return false;
@@ -202,7 +203,8 @@ public class MovementDescend extends Movement {
}
BlockPos playerFeet = ctx.playerFeet();
if (playerFeet.equals(dest) && (MovementHelper.isLiquid(ctx, dest) || ctx.player().posY - playerFeet.getY() < 0.094)) { // lilypads
BlockPos fakeDest = new BlockPos(dest.getX() * 2 - src.getX(), dest.getY(), dest.getZ() * 2 - src.getZ());
if ((playerFeet.equals(dest) || playerFeet.equals(fakeDest)) && (MovementHelper.isLiquid(ctx, dest) || ctx.player().posY - dest.getY() < 0.5)) { // lilypads
// Wait until we're actually on the ground before saying we're done because sometimes we continue to fall if the next action starts immediately
return state.setStatus(MovementStatus.SUCCESS);
/* else {
@@ -228,12 +230,8 @@ public class MovementDescend extends Movement {
double z = ctx.player().posZ - (src.getZ() + 0.5);
double fromStart = Math.sqrt(x * x + z * z);
if (!playerFeet.equals(dest) || ab > 0.25) {
BlockPos fakeDest = new BlockPos(dest.getX() * 2 - src.getX(), dest.getY(), dest.getZ() * 2 - src.getZ());
if (numTicks++ < 20) {
if (numTicks++ < 20 && fromStart < 1.25) {
MovementHelper.moveTowards(ctx, state, fakeDest);
if (fromStart > 1.25) {
state.getTarget().rotation = new Rotation(state.getTarget().rotation.getYaw() + 180F, state.getTarget().rotation.getPitch());
}
} else {
MovementHelper.moveTowards(ctx, state, dest);
}

View File

@@ -182,7 +182,7 @@ public class MovementDiagonal extends Movement {
}
public boolean sprint() {
if (MovementHelper.isLiquid(ctx, ctx.playerFeet()) && !Baritone.settings().sprintInWater.get()) {
if (MovementHelper.isLiquid(ctx, ctx.playerFeet()) && !Baritone.settings().sprintInWater.value) {
return false;
}
for (int i = 0; i < 4; i++) {

View File

@@ -78,7 +78,7 @@ public class MovementFall extends Movement {
}
BlockPos playerFeet = ctx.playerFeet();
Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest),ctx.playerRotations());
Rotation toDest = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations());
Rotation targetRotation = null;
Block destBlock = ctx.world().getBlockState(dest).getBlock();
boolean isWater = destBlock == Blocks.WATER || destBlock == Blocks.FLOWING_WATER;
@@ -141,7 +141,7 @@ public class MovementFall extends Movement {
}
if (targetRotation == null) {
Vec3d destCenterOffset = new Vec3d(destCenter.x + 0.125 * avoid.getX(), destCenter.y, destCenter.z + 0.125 * avoid.getZ());
state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), destCenterOffset,ctx.playerRotations()), false));
state.setTarget(new MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), destCenterOffset, ctx.playerRotations()), false));
}
return state;
}

View File

@@ -28,6 +28,7 @@ import baritone.pathing.movement.MovementState;
import baritone.utils.BlockStateInterface;
import baritone.utils.pathing.MutableMoveResult;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.BlockStairs;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
@@ -85,7 +86,7 @@ public class MovementParkour extends Movement {
return;
}
IBlockState standingOn = context.get(x, y - 1, z);
if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || standingOn.getBlock() instanceof BlockStairs || MovementHelper.isBottomSlab(standingOn)) {
if (standingOn.getBlock() == Blocks.VINE || standingOn.getBlock() == Blocks.LADDER || standingOn.getBlock() instanceof BlockStairs || MovementHelper.isBottomSlab(standingOn) || standingOn.getBlock() instanceof BlockLiquid) {
return;
}
int maxJump;
@@ -119,9 +120,11 @@ public class MovementParkour extends Movement {
if (!context.allowParkourPlace) {
return;
}
// time 2 pop off with that dank skynet parkour place
int destX = x + 4 * xDiff;
int destZ = z + 4 * zDiff;
if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) {
double placeCost = context.costOfPlacingAt(destX, y - 1, destZ);
if (placeCost >= COST_INF) {
return;
}
IBlockState toReplace = context.get(destX, y - 1, destZ);
@@ -139,7 +142,7 @@ public class MovementParkour extends Movement {
res.x = destX;
res.y = y;
res.z = destZ;
res.cost = costFromJumpDistance(4) + context.placeBlockCost + context.jumpPenalty;
res.cost = costFromJumpDistance(4) + placeCost + context.jumpPenalty;
return;
}
}

View File

@@ -17,6 +17,7 @@
package baritone.pathing.movement.movements;
import baritone.Baritone;
import baritone.api.IBaritone;
import baritone.api.pathing.movement.MovementStatus;
import baritone.api.utils.BetterBlockPos;
@@ -36,6 +37,7 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import java.util.Objects;
import java.util.Optional;
public class MovementPillar extends Movement {
@@ -75,8 +77,16 @@ public class MovementPillar extends Movement {
return LADDER_UP_ONE_COST; // allow ascending pillars of water, but only if we're already in one
}
}
if (!ladder && !context.canPlaceThrowawayAt(x, y, z)) { // we need to place a block where we started to jump on it
return COST_INF;
double placeCost = 0;
if (!ladder) {
// we need to place a block where we started to jump on it
placeCost = context.costOfPlacingAt(x, y, z);
if (placeCost >= COST_INF) {
return COST_INF;
}
if (fromDown.getBlock() == Blocks.AIR) {
placeCost += 0.1; // slightly (1/200th of a second) penalize pillaring on what's currently air
}
}
if (from instanceof BlockLiquid || (fromDown.getBlock() instanceof BlockLiquid && context.assumeWalkOnWater)) {
// otherwise, if we're standing in water, we cannot pillar
@@ -114,7 +124,7 @@ public class MovementPillar extends Movement {
if (ladder) {
return LADDER_UP_ONE_COST + hardness * 5;
} else {
return JUMP_ONE_BLOCK_COST + context.placeBlockCost + context.jumpPenalty + hardness;
return JUMP_ONE_BLOCK_COST + placeCost + context.jumpPenalty + hardness;
}
}
@@ -148,10 +158,14 @@ public class MovementPillar extends Movement {
return state;
}
if (ctx.playerFeet().y < src.y) {
return state.setStatus(MovementStatus.UNREACHABLE);
}
IBlockState fromDown = BlockStateInterface.get(ctx, src);
if (MovementHelper.isWater(fromDown.getBlock()) && MovementHelper.isWater(ctx, dest)) {
// stay centered while swimming up a water column
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest),ctx.playerRotations()), false));
state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()), false));
Vec3d destCenter = VecUtils.getBlockPosCenter(dest);
if (Math.abs(ctx.player().posX - destCenter.x) > 0.2 || Math.abs(ctx.player().posZ - destCenter.z) > 0.2) {
state.setInput(Input.MOVE_FORWARD, true);
@@ -194,7 +208,7 @@ public class MovementPillar extends Movement {
return state;
} else {
// Get ready to place a throwaway block
if (!MovementHelper.throwaway(ctx, true)) {
if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(src.x, src.y, src.z)) {
return state.setStatus(MovementStatus.UNREACHABLE);
}
@@ -222,11 +236,18 @@ public class MovementPillar extends Movement {
if (!blockIsThere) {
Block fr = BlockStateInterface.get(ctx, src).getBlock();
if (!(fr instanceof BlockAir || fr.isReplaceable(ctx.world(), src))) {
IBlockState frState = BlockStateInterface.get(ctx, src);
Block fr = frState.getBlock();
// TODO: Evaluate usage of getMaterial().isReplaceable()
if (!(fr instanceof BlockAir || frState.getMaterial().isReplaceable())) {
Optional<Rotation> reachable = RotationUtils.reachable(ctx.player(), src, ctx.playerController().getBlockReachDistance());
if (reachable.isPresent()) {
state.setTarget(new MovementState.MovementTarget(reachable.get(), true));
}
state.setInput(Input.JUMP, false); // breaking is like 5x slower when you're jumping
state.setInput(Input.CLICK_LEFT, true);
blockIsThere = false;
} else if (ctx.player().isSneaking() && (Objects.equals(src.down(), ctx.objectMouseOver().getBlockPos()) || Objects.equals(src, ctx.objectMouseOver().getBlockPos()))) {
} else if (ctx.player().isSneaking() && (Objects.equals(src.down(), ctx.objectMouseOver().getBlockPos()) || Objects.equals(src, ctx.objectMouseOver().getBlockPos())) && ctx.player().posY > dest.getY() + 0.1) {
state.setInput(Input.CLICK_RIGHT, true);
}
}

View File

@@ -113,7 +113,8 @@ public class MovementTraverse extends Movement {
// this happens when assume walk on water is true and this is a traverse in water, which isn't allowed
return COST_INF;
}
if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) {
double placeCost = context.costOfPlacingAt(destX, y - 1, destZ);
if (placeCost >= COST_INF) {
return COST_INF;
}
double hardness1 = MovementHelper.getMiningDurationTicks(context, destX, y, destZ, pb1, false);
@@ -130,7 +131,7 @@ public class MovementTraverse extends Movement {
continue;
}
if (MovementHelper.canPlaceAgainst(context.bsi, againstX, againstY, againstZ)) { // found a side place option
return WC + context.placeBlockCost + hardness1 + hardness2;
return WC + placeCost + hardness1 + hardness2;
}
}
// now that we've checked all possible directions to side place, we actually need to backplace
@@ -141,7 +142,7 @@ public class MovementTraverse extends Movement {
return COST_INF; // this is obviously impossible
}
WC = WC * (SNEAK_ONE_BLOCK_COST / WALK_ONE_BLOCK_COST);//since we are sneak backplacing, we are sneaking lol
return WC + context.placeBlockCost + hardness1 + hardness2;
return WC + placeCost + hardness1 + hardness2;
}
return COST_INF;
}
@@ -152,7 +153,7 @@ public class MovementTraverse extends Movement {
super.updateState(state);
if (state.getStatus() != MovementStatus.RUNNING) {
// if the setting is enabled
if (!Baritone.settings().walkWhileBreaking.get()) {
if (!Baritone.settings().walkWhileBreaking.value) {
return state;
}
// and if we're prepping (aka mining the block in front)
@@ -178,7 +179,7 @@ public class MovementTraverse extends Movement {
float pitchToBreak = state.getTarget().getRotation().get().getPitch();
state.setTarget(new MovementState.MovementTarget(new Rotation(yawToDest, pitchToBreak), true));
return state.setInput(Input.MOVE_FORWARD, true);
return state.setInput(Input.MOVE_FORWARD, true).setInput(Input.SPRINT, true);
}
//sneak may have been set to true in the PREPPING state while mining an adjacent block
@@ -231,10 +232,17 @@ public class MovementTraverse extends Movement {
if (ctx.playerFeet().equals(dest)) {
return state.setStatus(MovementStatus.SUCCESS);
}
Block low = BlockStateInterface.get(ctx, src).getBlock();
Block high = BlockStateInterface.get(ctx, src.up()).getBlock();
if (!ctx.player().onGround && (low == Blocks.VINE || low == Blocks.LADDER || high == Blocks.VINE || high == Blocks.LADDER)) {
// hitting W could cause us to climb the ladder instead of going forward
// wait until we're on the ground
return state;
}
BlockPos into = dest.subtract(src).add(dest);
Block intoBelow = BlockStateInterface.get(ctx, into).getBlock();
Block intoAbove = BlockStateInterface.get(ctx, into.up()).getBlock();
if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, ctx.playerFeet()) || Baritone.settings().sprintInWater.get()) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) {
if (wasTheBridgeBlockAlwaysThere && (!MovementHelper.isLiquid(ctx, ctx.playerFeet()) || Baritone.settings().sprintInWater.value) && (!MovementHelper.avoidWalkingInto(intoBelow) || MovementHelper.isWater(intoBelow)) && !MovementHelper.avoidWalkingInto(intoAbove)) {
state.setInput(Input.SPRINT, true);
}
Block destDown = BlockStateInterface.get(ctx, dest.down()).getBlock();
@@ -257,12 +265,12 @@ public class MovementTraverse extends Movement {
}
double dist1 = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D)));
PlaceResult p = MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false);
if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.get()) {
if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.value) {
state.setInput(Input.SNEAK, true);
}
switch (p) {
case READY_TO_PLACE: {
if (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) {
if (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.value) {
state.setInput(Input.CLICK_RIGHT, true);
}
return state;
@@ -336,4 +344,4 @@ public class MovementTraverse extends Movement {
}
return super.prepared(state);
}
}
}

View File

@@ -106,33 +106,31 @@ public class PathExecutor implements IPathExecutor, Helper {
}
BetterBlockPos whereShouldIBe = path.positions().get(pathPosition);
BetterBlockPos whereAmI = ctx.playerFeet();
if (!whereShouldIBe.equals(whereAmI)) {
if (!Blocks.AIR.equals(BlockStateInterface.getBlock(ctx, whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip
for (int i = 0; i < pathPosition - 1 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks
if (whereAmI.equals(path.positions().get(i))) {
logDebug("Skipping back " + (pathPosition - i) + " steps, to " + i);
int previousPos = pathPosition;
pathPosition = Math.max(i - 1, 0); // previous step might not actually be done
for (int j = pathPosition; j <= previousPos; j++) {
path.movements().get(j).reset();
}
onChangeInPathPosition();
onTick();
return false;
if (!whereShouldIBe.equals(whereAmI) && !Blocks.AIR.equals(BlockStateInterface.getBlock(ctx, whereAmI.down()))) {//do not skip if standing on air, because our position isn't stable to skip
for (int i = 0; i < pathPosition - 1 && i < path.length(); i++) {//this happens for example when you lag out and get teleported back a couple blocks
if (whereAmI.equals(path.positions().get(i))) {
logDebug("Skipping back " + (pathPosition - i) + " steps, to " + i);
int previousPos = pathPosition;
pathPosition = Math.max(i - 1, 0); // previous step might not actually be done
for (int j = pathPosition; j <= previousPos; j++) {
path.movements().get(j).reset();
}
onChangeInPathPosition();
onTick();
return false;
}
for (int i = pathPosition + 3; i < path.length(); i++) { //dont check pathPosition+1. the movement tells us when it's done (e.g. sneak placing)
// also don't check pathPosition+2 because reasons
if (whereAmI.equals(path.positions().get(i))) {
if (i - pathPosition > 2) {
logDebug("Skipping forward " + (i - pathPosition) + " steps, to " + i);
}
//System.out.println("Double skip sundae");
pathPosition = i - 1;
onChangeInPathPosition();
onTick();
return false;
}
for (int i = pathPosition + 3; i < path.length(); i++) { //dont check pathPosition+1. the movement tells us when it's done (e.g. sneak placing)
// also don't check pathPosition+2 because reasons
if (whereAmI.equals(path.positions().get(i))) {
if (i - pathPosition > 2) {
logDebug("Skipping forward " + (i - pathPosition) + " steps, to " + i);
}
//System.out.println("Double skip sundae");
pathPosition = i - 1;
onChangeInPathPosition();
onTick();
return false;
}
}
}
@@ -231,21 +229,21 @@ public class PathExecutor implements IPathExecutor, Helper {
costEstimateIndex = pathPosition;
// do this only once, when the movement starts, and deliberately get the cost as cached when this path was calculated, not the cost as it is right now
currentMovementOriginalCostEstimate = movement.getCost();
for (int i = 1; i < Baritone.settings().costVerificationLookahead.get() && pathPosition + i < path.length() - 1; i++) {
if (path.movements().get(pathPosition + i).calculateCostWithoutCaching() >= ActionCosts.COST_INF && canCancel) {
for (int i = 1; i < Baritone.settings().costVerificationLookahead.value && pathPosition + i < path.length() - 1; i++) {
if (((Movement) path.movements().get(pathPosition + i)).calculateCost(behavior.secretInternalGetCalculationContext()) >= ActionCosts.COST_INF && canCancel) {
logDebug("Something has changed in the world and a future movement has become impossible. Cancelling.");
cancel();
return true;
}
}
}
double currentCost = movement.recalculateCost();
double currentCost = ((Movement) movement).recalculateCost(behavior.secretInternalGetCalculationContext());
if (currentCost >= ActionCosts.COST_INF && canCancel) {
logDebug("Something has changed in the world and this movement has become impossible. Cancelling.");
cancel();
return true;
}
if (!movement.calculatedWhileLoaded() && currentCost - currentMovementOriginalCostEstimate > Baritone.settings().maxCostIncrease.get() && canCancel) {
if (!movement.calculatedWhileLoaded() && currentCost - currentMovementOriginalCostEstimate > Baritone.settings().maxCostIncrease.value && canCancel) {
// don't do this if the movement was calculated while loaded
// that means that this isn't a cache error, it's just part of the path interfering with a later part
logDebug("Original cost " + currentMovementOriginalCostEstimate + " current cost " + currentCost + ". Cancelling.");
@@ -275,7 +273,7 @@ public class PathExecutor implements IPathExecutor, Helper {
ctx.player().setSprinting(false); // letting go of control doesn't make you stop sprinting actually
}
ticksOnCurrent++;
if (ticksOnCurrent > currentMovementOriginalCostEstimate + Baritone.settings().movementTimeoutTicks.get()) {
if (ticksOnCurrent > currentMovementOriginalCostEstimate + Baritone.settings().movementTimeoutTicks.value) {
// only cancel if the total time has exceeded the initial estimate
// as you break the blocks required, the remaining cost goes down, to the point where
// ticksOnCurrent is greater than recalculateCost + 100
@@ -391,7 +389,7 @@ public class PathExecutor implements IPathExecutor, Helper {
if (current instanceof MovementTraverse && pathPosition < path.length() - 3) {
IMovement next = path.movements().get(pathPosition + 1);
if (next instanceof MovementAscend && sprintableAscend(ctx, (MovementTraverse) current, (MovementAscend) next, path.movements().get(pathPosition + 2))) {
if (skipNow(ctx, current, next)) {
if (skipNow(ctx, current)) {
logDebug("Skipping traverse to straight ascend");
pathPosition++;
onChangeInPathPosition();
@@ -479,6 +477,9 @@ public class PathExecutor implements IPathExecutor, Helper {
if (dir.getY() < -3) {
return null;
}
if (!movement.toBreakCached.isEmpty()) {
return null; // it's breaking
}
Vec3i flatDir = new Vec3i(dir.getX(), 0, dir.getZ());
int i;
outer:
@@ -510,7 +511,7 @@ public class PathExecutor implements IPathExecutor, Helper {
movement.getDest().add(flatDir.getX() * (i - pathPosition), 0, flatDir.getZ() * (i - pathPosition)));
}
private static boolean skipNow(IPlayerContext ctx, IMovement current, IMovement next) {
private static boolean skipNow(IPlayerContext ctx, IMovement current) {
double offTarget = Math.abs(current.getDirection().getX() * (current.getSrc().z + 0.5D - ctx.player().posZ)) + Math.abs(current.getDirection().getZ() * (current.getSrc().x + 0.5D - ctx.player().posX));
if (offTarget > 0.1) {
return false;
@@ -526,7 +527,7 @@ public class PathExecutor implements IPathExecutor, Helper {
}
private static boolean sprintableAscend(IPlayerContext ctx, MovementTraverse current, MovementAscend next, IMovement nextnext) {
if (!Baritone.settings().sprintAscends.get()) {
if (!Baritone.settings().sprintAscends.value) {
return false;
}
if (!current.getDirection().equals(next.getDirection().down())) {
@@ -538,6 +539,12 @@ public class PathExecutor implements IPathExecutor, Helper {
if (!MovementHelper.canWalkOn(ctx, current.getDest().down())) {
return false;
}
if (!MovementHelper.canWalkOn(ctx, next.getDest().down())) {
return false;
}
if (!next.toBreakCached.isEmpty()) {
return false; // it's breaking
}
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 3; y++) {
BlockPos chk = current.getSrc().up(y);
@@ -552,10 +559,7 @@ public class PathExecutor implements IPathExecutor, Helper {
if (MovementHelper.avoidWalkingInto(ctx.world().getBlockState(current.getSrc().up(3)).getBlock())) {
return false;
}
if (MovementHelper.avoidWalkingInto(ctx.world().getBlockState(next.getDest().up(2)).getBlock())) {
return false;
}
return true;
return !MovementHelper.avoidWalkingInto(ctx.world().getBlockState(next.getDest().up(2)).getBlock()); // codacy smh my head
}
private static boolean canSprintFromDescendInto(IPlayerContext ctx, IMovement current, IMovement next) {
@@ -565,7 +569,7 @@ public class PathExecutor implements IPathExecutor, Helper {
if (next instanceof MovementTraverse && next.getDirection().down().equals(current.getDirection()) && MovementHelper.canWalkOn(ctx, next.getDest().down())) {
return true;
}
return next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.get();
return next instanceof MovementDiagonal && Baritone.settings().allowOvershootDiagonalDescend.value;
}
private void onChangeInPathPosition() {
@@ -608,8 +612,8 @@ public class PathExecutor implements IPathExecutor, Helper {
}
private PathExecutor cutIfTooLong() {
if (pathPosition > Baritone.settings().maxPathHistoryLength.get()) {
int cutoffAmt = Baritone.settings().pathHistoryCutoffAmount.get();
if (pathPosition > Baritone.settings().maxPathHistoryLength.value) {
int cutoffAmt = Baritone.settings().pathHistoryCutoffAmount.value;
CutoffPath newPath = new CutoffPath(path, cutoffAmt, path.length() - 1);
if (!newPath.getDest().equals(path.getDest())) {
throw new IllegalStateException();

View File

@@ -0,0 +1,661 @@
/*
* 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.process;
import baritone.Baritone;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.pathing.goals.GoalComposite;
import baritone.api.pathing.goals.GoalGetToBlock;
import baritone.api.process.IBuilderProcess;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.api.utils.*;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.BaritoneProcessHelper;
import baritone.utils.BlockStateInterface;
import baritone.utils.PathingCommandContext;
import baritone.utils.schematic.AirSchematic;
import baritone.utils.schematic.Schematic;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.Tuple;
import net.minecraft.util.math.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import static baritone.api.pathing.movement.ActionCosts.COST_INF;
public class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess {
public BuilderProcess(Baritone baritone) {
super(baritone);
}
private HashSet<BetterBlockPos> incorrectPositions;
private String name;
private ISchematic schematic;
private Vec3i origin;
private int ticks;
public boolean build(String schematicFile, BlockPos origin) {
File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile);
System.out.println(file + " " + file.exists());
return build(schematicFile, file, origin);
}
@Override
public void build(String name, ISchematic schematic, Vec3i origin) {
this.name = name;
this.schematic = schematic;
this.origin = origin;
}
@Override
public boolean build(String name, File schematic, Vec3i origin) {
NBTTagCompound tag;
try (FileInputStream fileIn = new FileInputStream(schematic)) {
tag = CompressedStreamTools.readCompressed(fileIn);
} catch (IOException e) {
e.printStackTrace();
return false;
}
if (tag == null) {
return false;
}
build(name, parse(tag), origin);
return true;
}
public void clearArea(BlockPos corner1, BlockPos corner2) {
BlockPos origin = new BlockPos(Math.min(corner1.getX(), corner2.getX()), Math.min(corner1.getY(), corner2.getY()), Math.min(corner1.getZ(), corner2.getZ()));
int widthX = Math.abs(corner1.getX() - corner2.getX()) + 1;
int heightY = Math.abs(corner1.getY() - corner2.getY()) + 1;
int lengthZ = Math.abs(corner1.getZ() - corner2.getZ()) + 1;
build("clear area", new AirSchematic(widthX, heightY, lengthZ), origin);
}
private static ISchematic parse(NBTTagCompound schematic) {
return new Schematic(schematic);
}
@Override
public boolean isActive() {
return schematic != null;
}
public IBlockState placeAt(int x, int y, int z) {
if (!isActive()) {
return null;
}
if (!schematic.inSchematic(x - origin.getX(), y - origin.getY(), z - origin.getZ())) {
return null;
}
IBlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ());
if (state.getBlock() == Blocks.AIR) {
return null;
}
return state;
}
public Optional<Tuple<BetterBlockPos, Rotation>> toBreakNearPlayer(BuilderCalculationContext bcc) {
BetterBlockPos center = ctx.playerFeet();
for (int dx = -5; dx <= 5; dx++) {
for (int dy = 0; dy <= 5; dy++) {
for (int dz = -5; dz <= 5; dz++) {
int x = center.x + dx;
int y = center.y + dy;
int z = center.z + dz;
IBlockState desired = bcc.getSchematic(x, y, z);
if (desired == null) {
continue; // irrelevant
}
IBlockState curr = bcc.bsi.get0(x, y, z);
if (curr.getBlock() != Blocks.AIR && !valid(curr, desired)) {
BetterBlockPos pos = new BetterBlockPos(x, y, z);
Optional<Rotation> rot = RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance());
if (rot.isPresent()) {
return Optional.of(new Tuple<>(pos, rot.get()));
}
}
}
}
}
return Optional.empty();
}
public class Placement {
final int hotbarSelection;
final BlockPos placeAgainst;
final EnumFacing side;
final Rotation rot;
public Placement(int hotbarSelection, BlockPos placeAgainst, EnumFacing side, Rotation rot) {
this.hotbarSelection = hotbarSelection;
this.placeAgainst = placeAgainst;
this.side = side;
this.rot = rot;
}
}
public Optional<Placement> searchForPlacables(BuilderCalculationContext bcc, List<IBlockState> desirableOnHotbar) {
BetterBlockPos center = ctx.playerFeet();
for (int dx = -5; dx <= 5; dx++) {
for (int dy = -5; dy <= 1; dy++) {
for (int dz = -5; dz <= 5; dz++) {
int x = center.x + dx;
int y = center.y + dy;
int z = center.z + dz;
IBlockState desired = bcc.getSchematic(x, y, z);
if (desired == null) {
continue; // irrelevant
}
IBlockState curr = bcc.bsi.get0(x, y, z);
if (MovementHelper.isReplacable(x, y, z, curr, bcc.bsi) && !valid(curr, desired)) {
if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() == Blocks.AIR) {
continue;
}
desirableOnHotbar.add(desired);
Optional<Placement> opt = possibleToPlace(desired, x, y, z, bcc.bsi);
if (opt.isPresent()) {
return opt;
}
}
}
}
}
return Optional.empty();
}
public Optional<Placement> possibleToPlace(IBlockState toPlace, int x, int y, int z, BlockStateInterface bsi) {
for (EnumFacing against : EnumFacing.values()) {
BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against);
IBlockState placeAgainstState = bsi.get0(placeAgainstPos);
if (MovementHelper.isReplacable(placeAgainstPos.x, placeAgainstPos.y, placeAgainstPos.z, placeAgainstState, bsi)) {
continue;
}
if (!ctx.world().mayPlace(toPlace.getBlock(), new BetterBlockPos(x, y, z), false, against, null)) {
continue;
}
AxisAlignedBB aabb = placeAgainstState.getBoundingBox(ctx.world(), placeAgainstPos);
for (Vec3d placementMultiplier : aabbSideMultipliers(against)) {
double placeX = placeAgainstPos.x + aabb.minX * placementMultiplier.x + aabb.maxX * (1 - placementMultiplier.x);
double placeY = placeAgainstPos.y + aabb.minY * placementMultiplier.y + aabb.maxY * (1 - placementMultiplier.y);
double placeZ = placeAgainstPos.z + aabb.minZ * placementMultiplier.z + aabb.maxZ * (1 - placementMultiplier.z);
Rotation rot = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(placeX, placeY, placeZ), ctx.playerRotations());
RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot, ctx.playerController().getBlockReachDistance());
if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK && result.getBlockPos().equals(placeAgainstPos) && result.sideHit == against.getOpposite()) {
OptionalInt hotbar = hasAnyItemThatWouldPlace(toPlace, result, rot);
if (hotbar.isPresent()) {
return Optional.of(new Placement(hotbar.getAsInt(), placeAgainstPos, against.getOpposite(), rot));
}
}
}
}
return Optional.empty();
}
public OptionalInt hasAnyItemThatWouldPlace(IBlockState desired, RayTraceResult result, Rotation rot) {
for (int i = 0; i < 9; i++) {
ItemStack stack = ctx.player().inventory.mainInventory.get(i);
if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) {
continue;
}
float originalYaw = ctx.player().rotationYaw;
float originalPitch = ctx.player().rotationPitch;
// the state depends on the facing of the player sometimes
ctx.player().rotationYaw = rot.getYaw();
ctx.player().rotationPitch = rot.getPitch();
IBlockState wouldBePlaced = ((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(
ctx.world(),
result.getBlockPos().offset(result.sideHit),
result.sideHit,
(float) result.hitVec.x - result.getBlockPos().getX(), // as in PlayerControllerMP
(float) result.hitVec.y - result.getBlockPos().getY(),
(float) result.hitVec.z - result.getBlockPos().getZ(),
stack.getItem().getMetadata(stack.getMetadata()),
ctx.player()
);
ctx.player().rotationYaw = originalYaw;
ctx.player().rotationPitch = originalPitch;
if (valid(wouldBePlaced, desired)) {
return OptionalInt.of(i);
}
}
return OptionalInt.empty();
}
private static Vec3d[] aabbSideMultipliers(EnumFacing side) {
switch (side) {
case UP:
return new Vec3d[]{new Vec3d(0.5, 1, 0.5), new Vec3d(0.1, 1, 0.5), new Vec3d(0.9, 1, 0.5), new Vec3d(0.5, 1, 0.1), new Vec3d(0.5, 1, 0.9)};
case DOWN:
return new Vec3d[]{new Vec3d(0.5, 0, 0.5), new Vec3d(0.1, 0, 0.5), new Vec3d(0.9, 0, 0.5), new Vec3d(0.5, 0, 0.1), new Vec3d(0.5, 0, 0.9)};
case NORTH:
case SOUTH:
case EAST:
case WEST:
double x = side.getXOffset() == 0 ? 0.5 : (1 + side.getXOffset()) / 2D;
double z = side.getZOffset() == 0 ? 0.5 : (1 + side.getZOffset()) / 2D;
return new Vec3d[]{new Vec3d(x, 0.25, z), new Vec3d(x, 0.75, z)};
default: // null
throw new NullPointerException();
}
}
@Override
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
// TODO somehow tell inventorybehavior what we'd like to have on the hotbar
// perhaps take the 16 closest positions in incorrectPositions to ctx.playerFeet that aren't desired to be air, and then snag the top 4 most common block states, then request those on the hotbar
// this will work as is, but it'll be trashy
// need to iterate over incorrectPositions and see which ones we can "correct" from our current standing position
baritone.getInputOverrideHandler().clearAllKeys();
BuilderCalculationContext bcc = new BuilderCalculationContext();
if (!recalc(bcc)) {
logDirect("Done building");
onLostControl();
return null;
}
trim(bcc);
if (baritone.getInputOverrideHandler().isInputForcedDown(Input.CLICK_LEFT)) {
ticks = 5;
} else {
ticks--;
}
Optional<Tuple<BetterBlockPos, Rotation>> toBreak = toBreakNearPlayer(bcc);
baritone.getInputOverrideHandler().clearAllKeys();
if (toBreak.isPresent() && isSafeToCancel && ctx.player().onGround) {
// we'd like to pause to break this block
// only change look direction if it's safe (don't want to fuck up an in progress parkour for example
Rotation rot = toBreak.get().getSecond();
BetterBlockPos pos = toBreak.get().getFirst();
baritone.getLookBehavior().updateTarget(rot, true);
MovementHelper.switchToBestToolFor(ctx, bcc.get(pos));
if (ctx.player().isSneaking()) {
// really horrible bug where a block is visible for breaking while sneaking but not otherwise
// so you can't see it, it goes to place something else, sneaks, then the next tick it tries to break
// and is unable since it's unsneaked in the intermediary tick
baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true);
}
if (Objects.equals(ctx.objectMouseOver().getBlockPos(), pos) || ctx.playerRotations().isReallyCloseTo(rot)) {
baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true);
}
return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE);
}
List<IBlockState> desirableOnHotbar = new ArrayList<>();
Optional<Placement> toPlace = searchForPlacables(bcc, desirableOnHotbar);
if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround && ticks <= 0) {
Rotation rot = toPlace.get().rot;
baritone.getLookBehavior().updateTarget(rot, true);
ctx.player().inventory.currentItem = toPlace.get().hotbarSelection;
baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true);
if ((Objects.equals(ctx.objectMouseOver().getBlockPos(), toPlace.get().placeAgainst) && ctx.objectMouseOver().sideHit.equals(toPlace.get().side)) || ctx.playerRotations().isReallyCloseTo(rot)) {
baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true);
}
return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE);
}
List<IBlockState> approxPlacable = placable(36);
if (Baritone.settings().allowInventory.value) {
ArrayList<Integer> usefulSlots = new ArrayList<>();
List<IBlockState> noValidHotbarOption = new ArrayList<>();
outer:
for (IBlockState desired : desirableOnHotbar) {
for (int i = 0; i < 9; i++) {
if (valid(approxPlacable.get(i), desired)) {
usefulSlots.add(i);
continue outer;
}
}
noValidHotbarOption.add(desired);
}
outer:
for (int i = 9; i < 36; i++) {
for (IBlockState desired : noValidHotbarOption) {
if (valid(approxPlacable.get(i), desired)) {
baritone.getInventoryBehavior().attemptToPutOnHotbar(i, usefulSlots::contains);
break outer;
}
}
}
}
Goal goal = assemble(bcc, approxPlacable.subList(0, 9));
if (goal == null) {
goal = assemble(bcc, approxPlacable); // we're far away, so assume that we have our whole inventory to recalculate placable properly
if (goal == null) {
logDirect("Unable to do it =(");
onLostControl();
return null;
}
}
return new PathingCommandContext(goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc);
}
public boolean recalc(BuilderCalculationContext bcc) {
if (incorrectPositions == null) {
incorrectPositions = new HashSet<>();
fullRecalc(bcc);
if (incorrectPositions.isEmpty()) {
return false;
}
}
recalcNearby(bcc);
if (incorrectPositions.isEmpty()) {
fullRecalc(bcc);
}
return !incorrectPositions.isEmpty();
}
public void trim(BuilderCalculationContext bcc) {
HashSet<BetterBlockPos> copy = new HashSet<>(incorrectPositions);
copy.removeIf(pos -> pos.distanceSq(ctx.player().posX, ctx.player().posY, ctx.player().posZ) > 200);
if (!copy.isEmpty()) {
incorrectPositions = copy;
}
}
public void recalcNearby(BuilderCalculationContext bcc) {
BetterBlockPos center = ctx.playerFeet();
for (int dx = -5; dx <= 5; dx++) {
for (int dy = -5; dy <= 5; dy++) {
for (int dz = -5; dz <= 5; dz++) {
int x = center.x + dx;
int y = center.y + dy;
int z = center.z + dz;
IBlockState desired = bcc.getSchematic(x, y, z);
if (desired != null) {
// we care about this position
if (valid(bcc.bsi.get0(x, y, z), desired)) {
incorrectPositions.remove(new BetterBlockPos(x, y, z));
} else {
incorrectPositions.add(new BetterBlockPos(x, y, z));
}
}
}
}
}
}
public void fullRecalc(BuilderCalculationContext bcc) {
incorrectPositions = new HashSet<>();
for (int y = 0; y < schematic.heightY(); y++) {
for (int z = 0; z < schematic.lengthZ(); z++) {
for (int x = 0; x < schematic.widthX(); x++) {
if (schematic.inSchematic(x, y, z)) {
if (!valid(bcc.bsi.get0(x + origin.getX(), y + origin.getY(), z + origin.getZ()), schematic.desiredState(x, y, z))) {
incorrectPositions.add(new BetterBlockPos(x + origin.getX(), y + origin.getY(), z + origin.getZ()));
}
}
}
}
}
}
private Goal assemble(BuilderCalculationContext bcc, List<IBlockState> approxPlacable) {
List<BetterBlockPos> placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList());
Goal[] toBreak = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new);
Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(pos -> placementgoal(pos, bcc)).toArray(Goal[]::new);
if (toPlace.length != 0) {
return new JankyGoalComposite(new GoalComposite(toPlace), new GoalComposite(toBreak));
}
if (toBreak.length == 0) {
return null;
}
return new GoalComposite(toBreak);
}
public static class JankyGoalComposite implements Goal {
private final Goal primary;
private final Goal fallback;
public JankyGoalComposite(Goal primary, Goal fallback) {
this.primary = primary;
this.fallback = fallback;
}
@Override
public boolean isInGoal(int x, int y, int z) {
return primary.isInGoal(x, y, z) || fallback.isInGoal(x, y, z);
}
@Override
public double heuristic(int x, int y, int z) {
return primary.heuristic(x, y, z);
}
@Override
public String toString() {
return "JankyComposite Primary: " + primary + " Fallback: " + fallback;
}
}
public static class GoalBreak extends GoalGetToBlock {
public GoalBreak(BlockPos pos) {
super(pos);
}
@Override
public boolean isInGoal(int x, int y, int z) {
// can't stand right on top of a block, that might not work (what if it's unsupported, can't break then)
if (y > this.y) {
return false;
}
// but any other adjacent works for breaking, including inside or below
return super.isInGoal(x, y, z);
}
}
public Goal placementgoal(BlockPos pos, BuilderCalculationContext bcc) {
if (ctx.world().getBlockState(pos).getBlock() != Blocks.AIR) {
return new GoalPlace(pos);
}
boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR;
for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP) {
if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ()).getBlock(), pos, false, facing, null)) {
return new GoalAdjacent(pos, allowSameLevel);
}
}
return new GoalPlace(pos);
}
public static class GoalAdjacent extends GoalGetToBlock {
boolean allowSameLevel;
public GoalAdjacent(BlockPos pos, boolean allowSameLevel) {
super(pos);
this.allowSameLevel = allowSameLevel;
}
public boolean isInGoal(int x, int y, int z) {
if (x == this.x && y == this.y && z == this.z) {
return false;
}
if (!allowSameLevel && y == this.y - 1) {
return false;
}
if (y < this.y - 1) {
return false;
}
return super.isInGoal(x, y, z);
}
public double heuristic(int x, int y, int z) {
// prioritize lower y coordinates
return this.y * 100 + super.heuristic(x, y, z);
}
}
public static class GoalPlace extends GoalBlock {
public GoalPlace(BlockPos placeAt) {
super(placeAt.up());
}
public double heuristic(int x, int y, int z) {
// prioritize lower y coordinates
return this.y * 100 + super.heuristic(x, y, z);
}
}
@Override
public void onLostControl() {
incorrectPositions = null;
name = null;
schematic = null;
}
@Override
public String displayName0() {
return "Building " + name;
}
public List<IBlockState> placable(int size) {
List<IBlockState> result = new ArrayList<>();
for (int i = 0; i < size; i++) {
ItemStack stack = ctx.player().inventory.mainInventory.get(i);
if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) {
result.add(Blocks.AIR.getDefaultState());
continue;
}
// <toxic cloud>
result.add(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(ctx.world(), ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ, stack.getItem().getMetadata(stack.getMetadata()), ctx.player()));
// </toxic cloud>
}
return result;
}
public boolean valid(IBlockState current, IBlockState desired) {
// TODO more complicated comparison logic I guess
return desired == null || current.equals(desired);
}
public class BuilderCalculationContext extends CalculationContext {
private final List<IBlockState> placable;
private final ISchematic schematic;
private final int originX;
private final int originY;
private final int originZ;
public BuilderCalculationContext() {
super(BuilderProcess.this.baritone, true); // wew lad
this.placable = placable(9);
this.schematic = BuilderProcess.this.schematic;
this.originX = origin.getX();
this.originY = origin.getY();
this.originZ = origin.getZ();
this.jumpPenalty += 10;
this.backtrackCostFavoringCoefficient = 1;
}
private IBlockState getSchematic(int x, int y, int z) {
if (schematic.inSchematic(x - originX, y - originY, z - originZ)) {
return schematic.desiredState(x - originX, y - originY, z - originZ);
} else {
return null;
}
}
@Override
public double costOfPlacingAt(int x, int y, int z) {
if (isPossiblyProtected(x, y, z) || !worldBorder.canPlaceAt(x, z)) { // make calculation fail properly if we can't build
return COST_INF;
}
IBlockState sch = getSchematic(x, y, z);
if (sch != null) {
// TODO this can return true even when allowPlace is off.... is that an issue?
if (sch.getBlock() == Blocks.AIR) {
// we want this to be air, but they're asking if they can place here
// this won't be a schematic block, this will be a throwaway
return placeBlockCost * 2; // we're going to have to break it eventually
}
if (placable.contains(sch)) {
return 0; // thats right we gonna make it FREE to place a block where it should go in a structure
// no place block penalty at all 😎
// i'm such an idiot that i just tried to copy and paste the epic gamer moment emoji too
// get added to unicode when?
}
if (!hasThrowaway) {
return COST_INF;
}
// we want it to be something that we don't have
// even more of a pain to place something wrong
return placeBlockCost * 3;
} else {
if (hasThrowaway) {
return placeBlockCost;
} else {
return COST_INF;
}
}
}
@Override
public double breakCostMultiplierAt(int x, int y, int z) {
if (!allowBreak || isPossiblyProtected(x, y, z)) {
return COST_INF;
}
IBlockState sch = getSchematic(x, y, z);
if (sch != null) {
if (sch.getBlock() == Blocks.AIR) {
// it should be air
// regardless of current contents, we can break it
return 1;
}
// it should be a real block
// is it already that block?
if (valid(bsi.get0(x, y, z), sch)) {
return 3;
} else {
// can break if it's wrong
// would be great to return less than 1 here, but that would actually make the cost calculation messed up
// since we're breaking a block, if we underestimate the cost, then it'll fail when it really takes the correct amount of time
return 1;
}
// TODO do blocks in render distace only?
// TODO allow breaking blocks that we have a tool to harvest and immediately place back?
} else {
return 1; // why not lol
}
}
}
}

View File

@@ -24,8 +24,6 @@ import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.utils.BaritoneProcessHelper;
import java.util.Objects;
/**
* As set by ExampleBaritoneControl or something idk
*
@@ -46,7 +44,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG
private State state;
public CustomGoalProcess(Baritone baritone) {
super(baritone, 3);
super(baritone);
}
@Override
@@ -55,6 +53,9 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG
if (this.state == State.NONE) {
this.state = State.GOAL_SET;
}
if (this.state == State.EXECUTING) {
this.state = State.PATH_REQUESTED;
}
}
@Override
@@ -76,20 +77,20 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
switch (this.state) {
case GOAL_SET:
if (!baritone.getPathingBehavior().isPathing() && Objects.equals(baritone.getPathingBehavior().getGoal() + "", this.goal + "")) {
this.state = State.NONE;
}
return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL);
case PATH_REQUESTED:
PathingCommand ret = new PathingCommand(this.goal, PathingCommandType.SET_GOAL_AND_PATH);
// return FORCE_REVALIDATE_GOAL_AND_PATH just once
PathingCommand ret = new PathingCommand(this.goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH);
this.state = State.EXECUTING;
return ret;
case EXECUTING:
if (calcFailed) {
onLostControl();
return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL);
}
if (this.goal == null || this.goal.isInGoal(ctx.playerFeet())) {
if (this.goal == null || (this.goal.isInGoal(ctx.playerFeet()) && this.goal.isInGoal(baritone.getPathingBehavior().pathStart()))) {
onLostControl(); // we're there xd
return new PathingCommand(this.goal, PathingCommandType.CANCEL_AND_SET_GOAL);
}
return new PathingCommand(this.goal, PathingCommandType.SET_GOAL_AND_PATH);
default:
@@ -104,7 +105,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG
}
@Override
public String displayName() {
public String displayName0() {
return "Custom Goal " + this.goal;
}

View File

@@ -0,0 +1,100 @@
/*
* 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.process;
import baritone.Baritone;
import baritone.api.cache.ICachedWorld;
import baritone.api.pathing.goals.GoalXZ;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.cache.CachedWorld;
import baritone.utils.BaritoneProcessHelper;
import net.minecraft.util.math.BlockPos;
public class ExploreProcess extends BaritoneProcessHelper {
private BlockPos explorationOrigin;
public ExploreProcess(Baritone baritone) {
super(baritone);
}
@Override
public boolean isActive() {
return explorationOrigin != null;
}
public void explore(int centerX, int centerZ) {
explorationOrigin = new BlockPos(centerX, 0, centerZ);
}
@Override
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
if (calcFailed) {
logDirect("Failed");
onLostControl();
return null;
}
BlockPos closestUncached = closestUncachedChunk(explorationOrigin);
if (closestUncached == null) {
logDebug("awaiting region load from disk");
return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE);
}
System.out.println("Closest uncached: " + closestUncached);
return new PathingCommand(new GoalXZ(closestUncached.getX(), closestUncached.getZ()), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH);
}
private BlockPos closestUncachedChunk(BlockPos pos) {
int chunkX = pos.getX() >> 4;
int chunkZ = pos.getZ() >> 4;
ICachedWorld cache = baritone.getWorldProvider().getCurrentWorld().getCachedWorld();
for (int dist = 0; ; dist++) {
for (int dx = -dist; dx <= dist; dx++) {
for (int dz = -dist; dz <= dist; dz++) {
int trueDist = Baritone.settings().exploreUsePythagorean.value ? dx * dx + dz + dz : Math.abs(dx) + Math.abs(dz);
if (trueDist != dist) {
continue; // not considering this one just yet in our expanding search
}
int centerX = (chunkX + dx) * 16 + 8;
int centerZ = (chunkZ + dz) * 18 + 8;
if (cache.isCached(centerX, centerZ)) {
continue;
}
if (!((CachedWorld) cache).regionLoaded(centerX, centerZ)) {
Baritone.getExecutor().execute(() -> {
((CachedWorld) cache).tryLoadFromDisk(centerX >> 9, centerZ >> 9);
});
return null; // we still need to load regions from disk in order to decide properly
}
return new BlockPos(centerX, 0, centerZ);
}
}
}
}
@Override
public void onLostControl() {
explorationOrigin = null;
}
@Override
public String displayName0() {
return "Exploring around " + explorationOrigin + ", currently going to " + closestUncachedChunk(explorationOrigin);
}
}

View File

@@ -46,7 +46,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo
private List<Entity> cache;
public FollowProcess(Baritone baritone) {
super(baritone, 1);
super(baritone);
}
@Override
@@ -58,13 +58,13 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo
private Goal towards(Entity following) {
BlockPos pos;
if (Baritone.settings().followOffsetDistance.get() == 0) {
if (Baritone.settings().followOffsetDistance.value == 0) {
pos = new BlockPos(following);
} else {
GoalXZ g = GoalXZ.fromDirection(following.getPositionVector(), Baritone.settings().followOffsetDirection.get(), Baritone.settings().followOffsetDistance.get());
GoalXZ g = GoalXZ.fromDirection(following.getPositionVector(), Baritone.settings().followOffsetDirection.value, Baritone.settings().followOffsetDistance.value);
pos = new BlockPos(g.getX(), following.posY, g.getZ());
}
return new GoalNear(pos, Baritone.settings().followRadius.get());
return new GoalNear(pos, Baritone.settings().followRadius.value);
}
@@ -101,7 +101,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo
}
@Override
public String displayName() {
public String displayName0() {
return "Follow " + cache;
}

View File

@@ -44,7 +44,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
private int tickCount = 0;
public GetToBlockProcess(Baritone baritone) {
super(baritone, 2);
super(baritone);
}
@Override
@@ -67,7 +67,7 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
rescan(new ArrayList<>(), new CalculationContext(baritone));
}
if (knownLocations.isEmpty()) {
if (Baritone.settings().exploreForBlocks.get() && !calcFailed) {
if (Baritone.settings().exploreForBlocks.value && !calcFailed) {
return new PathingCommand(new GoalRunAway(1, start) {
@Override
public boolean isInGoal(int x, int y, int z) {
@@ -83,8 +83,8 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
}
Goal goal = new GoalComposite(knownLocations.stream().map(this::createGoal).toArray(Goal[]::new));
if (calcFailed) {
if (Baritone.settings().blacklistOnGetToBlockFailure.get()) {
logDirect("Unable to find any path to " + gettingTo + ", blacklisting presumably unreachable closest instances");
if (Baritone.settings().blacklistClosestOnFailure.value) {
logDirect("Unable to find any path to " + gettingTo + ", blacklisting presumably unreachable closest instances...");
blacklistClosest();
return onTick(false, isSafeToCancel); // gamer moment
} else {
@@ -95,13 +95,13 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
return new PathingCommand(goal, PathingCommandType.CANCEL_AND_SET_GOAL);
}
}
int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get();
int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.value;
if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain
List<BlockPos> current = new ArrayList<>(knownLocations);
CalculationContext context = new CalculationContext(baritone, true);
Baritone.getExecutor().execute(() -> rescan(current, context));
}
if (goal.isInGoal(ctx.playerFeet()) && isSafeToCancel) {
if (goal.isInGoal(ctx.playerFeet()) && goal.isInGoal(baritone.getPathingBehavior().pathStart()) && isSafeToCancel) {
// we're there
if (rightClickOnArrival(gettingTo)) {
if (rightClick()) {
@@ -131,8 +131,11 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
}
}
}
if (true) {
break; // codacy gets mad if i just end on a break LOL
// i can't do break; (codacy gets mad), and i can't do if(true){break}; (codacy gets mad)
// so i will do this
switch (newBlacklist.size()) {
default:
break outer;
}
}
logDebug("Blacklisting unreachable locations " + newBlacklist);
@@ -157,18 +160,27 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
}
@Override
public String displayName() {
return "Get To Block " + gettingTo;
public String displayName0() {
if (knownLocations.isEmpty()) {
return "Exploring randomly to find " + gettingTo + ", no known locations";
}
return "Get To " + gettingTo + ", " + knownLocations.size() + " known locations";
}
private synchronized void rescan(List<BlockPos> known, CalculationContext context) {
List<BlockPos> positions = MineProcess.searchWorld(context, Collections.singletonList(gettingTo), 64, known);
List<BlockPos> positions = MineProcess.searchWorld(context, Collections.singletonList(gettingTo), 64, known, blacklist);
positions.removeIf(blacklist::contains);
knownLocations = positions;
}
private Goal createGoal(BlockPos pos) {
return walkIntoInsteadOfAdjacent(gettingTo) ? new GoalTwoBlocks(pos) : new GoalGetToBlock(pos);
if (walkIntoInsteadOfAdjacent(gettingTo)) {
return new GoalTwoBlocks(pos);
}
if (blockOnTopMustBeRemoved(gettingTo) && baritone.bsi.get0(pos.up()).isBlockNormalCube()) {
return new GoalBlock(pos.up());
}
return new GoalGetToBlock(pos);
}
private boolean rightClick() {
@@ -191,16 +203,24 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl
}
private boolean walkIntoInsteadOfAdjacent(Block block) {
if (!Baritone.settings().enterPortal.get()) {
if (!Baritone.settings().enterPortal.value) {
return false;
}
return block == Blocks.PORTAL;
}
private boolean rightClickOnArrival(Block block) {
if (!Baritone.settings().rightClickContainerOnArrival.get()) {
if (!Baritone.settings().rightClickContainerOnArrival.value) {
return false;
}
return block == Blocks.CRAFTING_TABLE || block == Blocks.FURNACE || block == Blocks.ENDER_CHEST || block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST;
}
private boolean blockOnTopMustBeRemoved(Block block) {
if (!rightClickOnArrival(block)) { // only if we plan to actually open it on arrival
return false;
}
// only these chests; you can open a crafting table or furnace even with a block on top
return block == Blocks.ENDER_CHEST || block == Blocks.CHEST || block == Blocks.TRAPPED_CHEST;
}
}

View File

@@ -54,13 +54,14 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
private List<Block> mining;
private List<BlockPos> knownOreLocations;
private List<BlockPos> blacklist; // inaccessible
private BlockPos branchPoint;
private GoalRunAway branchPointRunaway;
private int desiredQuantity;
private int tickCount;
public MineProcess(Baritone baritone) {
super(baritone, 0);
super(baritone);
}
@Override
@@ -80,18 +81,24 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
return null;
}
}
if (calcFailed && !knownOreLocations.isEmpty() && Baritone.settings().blacklistClosestOnFailure.value) {
logDirect("Unable to find any path to " + mining + ", blacklisting presumably unreachable closest instance...");
knownOreLocations.stream().sorted(Comparator.comparingDouble(ctx.player()::getDistanceSq)).findFirst().ifPresent(blacklist::add);
knownOreLocations.removeIf(blacklist::contains);
calcFailed = false; // 😎
}
if (calcFailed) {
logDirect("Unable to find any path to " + mining + ", canceling Mine");
cancel();
return null;
}
int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.get();
int mineGoalUpdateInterval = Baritone.settings().mineGoalUpdateInterval.value;
if (mineGoalUpdateInterval != 0 && tickCount++ % mineGoalUpdateInterval == 0) { // big brain
List<BlockPos> curr = new ArrayList<>(knownOreLocations);
CalculationContext context = new CalculationContext(baritone, true);
Baritone.getExecutor().execute(() -> rescan(curr, context));
}
if (Baritone.settings().legitMine.get()) {
if (Baritone.settings().legitMine.value) {
addNearby();
}
PathingCommand command = updateGoal();
@@ -110,15 +117,15 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
}
@Override
public String displayName() {
public String displayName0() {
return "Mine " + mining;
}
private PathingCommand updateGoal() {
boolean legit = Baritone.settings().legitMine.get();
boolean legit = Baritone.settings().legitMine.value;
List<BlockPos> locs = knownOreLocations;
if (!locs.isEmpty()) {
List<BlockPos> locs2 = prune(new CalculationContext(baritone), new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT);
List<BlockPos> locs2 = prune(new CalculationContext(baritone), new ArrayList<>(locs), mining, ORE_LOCATIONS_COUNT, blacklist);
// can't reassign locs, gotta make a new var locs2, because we use it in a lambda right here, and variables you use in a lambda must be effectively final
Goal goal = new GoalComposite(locs2.stream().map(loc -> coalesce(ctx, loc, locs2)).toArray(Goal[]::new));
knownOreLocations = locs2;
@@ -129,7 +136,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
return null;
}
// only in non-Xray mode (aka legit mode) do we do this
int y = Baritone.settings().legitMineYLevel.get();
int y = Baritone.settings().legitMineYLevel.value;
if (branchPoint == null) {
/*if (!baritone.getPathingBehavior().isPathing() && playerFeet().y == y) {
// cool, path is over and we are at desired y
@@ -157,13 +164,13 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
if (mining == null) {
return;
}
if (Baritone.settings().legitMine.get()) {
if (Baritone.settings().legitMine.value) {
return;
}
List<BlockPos> locs = searchWorld(context, mining, ORE_LOCATIONS_COUNT, already);
List<BlockPos> locs = searchWorld(context, mining, ORE_LOCATIONS_COUNT, already, blacklist);
locs.addAll(droppedItemsScan(mining, ctx.world()));
if (locs.isEmpty()) {
logDebug("No locations for " + mining + " known, cancelling");
logDirect("No locations for " + mining + " known, cancelling");
cancel();
return;
}
@@ -171,18 +178,18 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
}
private static Goal coalesce(IPlayerContext ctx, BlockPos loc, List<BlockPos> locs) {
if (!Baritone.settings().forceInternalMining.get()) {
if (!Baritone.settings().forceInternalMining.value) {
return new GoalTwoBlocks(loc);
}
// Here, BlockStateInterface is used because the position may be in a cached chunk (the targeted block is one that is kept track of)
boolean upwardGoal = locs.contains(loc.up()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(ctx, loc.up()) == Blocks.AIR);
boolean downwardGoal = locs.contains(loc.down()) || (Baritone.settings().internalMiningAirException.get() && BlockStateInterface.getBlock(ctx, loc.down()) == Blocks.AIR);
boolean upwardGoal = locs.contains(loc.up()) || (Baritone.settings().internalMiningAirException.value && BlockStateInterface.getBlock(ctx, loc.up()) == Blocks.AIR);
boolean downwardGoal = locs.contains(loc.down()) || (Baritone.settings().internalMiningAirException.value && BlockStateInterface.getBlock(ctx, loc.down()) == Blocks.AIR);
return upwardGoal == downwardGoal ? new GoalTwoBlocks(loc) : upwardGoal ? new GoalBlock(loc) : new GoalBlock(loc.down());
}
public static List<BlockPos> droppedItemsScan(List<Block> mining, World world) {
if (!Baritone.settings().mineScanDroppedItems.get()) {
if (!Baritone.settings().mineScanDroppedItems.value) {
return new ArrayList<>();
}
Set<Item> searchingFor = new HashSet<>();
@@ -204,28 +211,30 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
return ret;
}
public static List<BlockPos> searchWorld(CalculationContext ctx, List<Block> mining, int max, List<BlockPos> alreadyKnown) {
public static List<BlockPos> searchWorld(CalculationContext ctx, List<Block> mining, int max, List<BlockPos> alreadyKnown, List<BlockPos> blacklist) {
List<BlockPos> locs = new ArrayList<>();
List<Block> uninteresting = new ArrayList<>();
//long b = System.currentTimeMillis();
for (Block m : mining) {
if (CachedChunk.BLOCKS_TO_KEEP_TRACK_OF.contains(m)) {
locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), 1, ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 2));
// maxRegionDistanceSq 2 means adjacent directly or adjacent diagonally; nothing further than that
locs.addAll(ctx.worldData.getCachedWorld().getLocationsOf(ChunkPacker.blockToString(m), Baritone.settings().maxCachedWorldScanCount.value, ctx.getBaritone().getPlayerContext().playerFeet().getX(), ctx.getBaritone().getPlayerContext().playerFeet().getZ(), 2));
} else {
uninteresting.add(m);
}
}
locs = prune(ctx, locs, mining, max, blacklist);
//System.out.println("Scan of cached chunks took " + (System.currentTimeMillis() - b) + "ms");
if (locs.isEmpty()) {
uninteresting = mining;
}
if (!uninteresting.isEmpty()) {
//long before = System.currentTimeMillis();
locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), uninteresting, max, 10, 26));
locs.addAll(WorldScanner.INSTANCE.scanChunkRadius(ctx.getBaritone().getPlayerContext(), uninteresting, max, 10, 32)); // maxSearchRadius is NOT sq
//System.out.println("Scan of loaded chunks took " + (System.currentTimeMillis() - before) + "ms");
}
locs.addAll(alreadyKnown);
return prune(ctx, locs, mining, max);
return prune(ctx, locs, mining, max, blacklist);
}
private void addNearby() {
@@ -241,17 +250,17 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
// is an x-ray and it'll get caught
if (mining.contains(bsi.get0(x, y, z).getBlock())) {
BlockPos pos = new BlockPos(x, y, z);
if ((Baritone.settings().legitMineIncludeDiagonals.get() && knownOreLocations.stream().anyMatch(ore -> ore.distanceSq(pos) <= 2 /* sq means this is pytha dist <= sqrt(2) */)) || RotationUtils.reachable(ctx.player(), pos, fakedBlockReachDistance).isPresent()) {
if ((Baritone.settings().legitMineIncludeDiagonals.value && knownOreLocations.stream().anyMatch(ore -> ore.distanceSq(pos) <= 2 /* sq means this is pytha dist <= sqrt(2) */)) || RotationUtils.reachable(ctx.player(), pos, fakedBlockReachDistance).isPresent()) {
knownOreLocations.add(pos);
}
}
}
}
}
knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, mining, ORE_LOCATIONS_COUNT);
knownOreLocations = prune(new CalculationContext(baritone), knownOreLocations, mining, ORE_LOCATIONS_COUNT, blacklist);
}
public static List<BlockPos> prune(CalculationContext ctx, List<BlockPos> locs2, List<Block> mining, int max) {
private static List<BlockPos> prune(CalculationContext ctx, List<BlockPos> locs2, List<Block> mining, int max, List<BlockPos> blacklist) {
List<BlockPos> dropped = droppedItemsScan(mining, ctx.world);
dropped.removeIf(drop -> {
for (BlockPos pos : locs2) {
@@ -271,6 +280,8 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
// remove any that are implausible to mine (encased in bedrock, or touching lava)
.filter(pos -> MineProcess.plausibleToBreak(ctx.bsi, pos))
.filter(pos -> !blacklist.contains(pos))
.sorted(Comparator.comparingDouble(ctx.getBaritone().getPlayerContext().playerFeet()::distanceSq))
.collect(Collectors.toList());
@@ -299,6 +310,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro
this.mining = blocks == null || blocks.length == 0 ? null : Arrays.asList(blocks);
this.desiredQuantity = quantity;
this.knownOreLocations = new ArrayList<>();
this.blacklist = new ArrayList<>();
this.branchPoint = null;
this.branchPointRunaway = null;
if (mining != null) {

View File

@@ -115,7 +115,9 @@ public class BaritoneAutoTest implements AbstractGameEventListener, Helper {
}
// Setup Baritone's pathing goal and (if needed) begin pathing
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(GOAL);
if (!BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().isActive()) {
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(GOAL);
}
// If we have reached our goal, print a message and safely close the game
if (GOAL.isInGoal(ctx.playerFeet())) {

View File

@@ -25,12 +25,10 @@ public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper
protected final Baritone baritone;
protected final IPlayerContext ctx;
private final double priority;
public BaritoneProcessHelper(Baritone baritone, double priority) {
public BaritoneProcessHelper(Baritone baritone) {
this.baritone = baritone;
this.ctx = baritone.getPlayerContext();
this.priority = priority;
baritone.getPathingControlManager().registerProcess(this);
}
@@ -38,9 +36,4 @@ public abstract class BaritoneProcessHelper implements IBaritoneProcess, Helper
public boolean isTemporary() {
return false;
}
@Override
public double priority() {
return priority;
}
}

View File

@@ -31,7 +31,7 @@ public final class BlockBreakHelper implements Helper {
private boolean didBreakLastTick;
private IPlayerContext playerContext;
private final IPlayerContext playerContext;
public BlockBreakHelper(IPlayerContext playerContext) {
this.playerContext = playerContext;

View File

@@ -0,0 +1,51 @@
/*
* 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.utils;
import baritone.Baritone;
import baritone.api.utils.IPlayerContext;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.RayTraceResult;
public class BlockPlaceHelper implements Helper {
private final IPlayerContext ctx;
private int rightClickTimer;
public BlockPlaceHelper(IPlayerContext playerContext) {
this.ctx = playerContext;
}
public void tick(boolean rightClickRequested) {
if (rightClickTimer > 0) {
rightClickTimer--;
return;
}
RayTraceResult mouseOver = ctx.objectMouseOver();
if (!rightClickRequested || ctx.player().isRowingBoat() || mouseOver == null || mouseOver.getBlockPos() == null || mouseOver.typeOfHit != RayTraceResult.Type.BLOCK) {
return;
}
rightClickTimer = Baritone.settings().rightClickSpeed.value;
for (EnumHand hand : EnumHand.values()) {
if (ctx.playerController().processRightClickBlock(ctx.player(), ctx.world(), mouseOver.getBlockPos(), mouseOver.sideHit, mouseOver.hitVec, hand) == EnumActionResult.SUCCESS) {
ctx.player().swingArm(hand);
return;
}
}
}
}

View File

@@ -66,7 +66,7 @@ public class BlockStateInterface {
} else {
this.loadedChunks = worldLoaded; // this will only be used on the main thread
}
this.useTheRealWorld = !Baritone.settings().pathThroughCachedOnly.get();
this.useTheRealWorld = !Baritone.settings().pathThroughCachedOnly.value;
if (!Minecraft.getMinecraft().isCallingFromMinecraftThread()) {
throw new IllegalStateException();
}

View File

@@ -24,6 +24,7 @@ import baritone.api.cache.IWaypoint;
import baritone.api.event.events.ChatEvent;
import baritone.api.pathing.goals.*;
import baritone.api.pathing.movement.ActionCosts;
import baritone.api.process.IBaritoneProcess;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.SettingsUtil;
import baritone.behavior.Behavior;
@@ -77,7 +78,8 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
"sethome - Sets \"home\"\n" +
"home - Paths towards \"home\" \n" +
"costs - (debug) all movement costs from current location\n" +
"damn - Daniel ";
"damn - Daniel\n" +
"Go to https://github.com/cabaletta/baritone/blob/master/USAGE.md for more information";
private static final String COMMAND_PREFIX = "#";
@@ -88,14 +90,14 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
@Override
public void onSendChatMessage(ChatEvent event) {
String msg = event.getMessage();
if (Baritone.settings().prefixControl.get() && msg.startsWith(COMMAND_PREFIX)) {
if (Baritone.settings().prefixControl.value && msg.startsWith(COMMAND_PREFIX)) {
if (!runCommand(msg.substring(COMMAND_PREFIX.length()))) {
logDirect("Invalid command");
}
event.cancel(); // always cancel if using prefixControl
return;
}
if (!Baritone.settings().chatControl.get() && !Baritone.settings().removePrefix.get()) {
if (!Baritone.settings().chatControl.value && !Baritone.settings().removePrefix.value) {
return;
}
if (runCommand(msg)) {
@@ -116,12 +118,33 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true;
}
}
if (msg.equals("baritone") || msg.equals("settings")) {
for (Settings.Setting<?> setting : Baritone.settings().allSettings) {
if (msg.equals("baritone") || msg.equals("modifiedsettings") || msg.startsWith("settings m") || msg.equals("modified")) {
logDirect("All settings that have been modified from their default values:");
for (Settings.Setting<?> setting : SettingsUtil.modifiedSettings(Baritone.settings())) {
logDirect(setting.toString());
}
return true;
}
if (msg.startsWith("settings")) {
String rest = msg.substring("settings".length());
try {
int page = Integer.parseInt(rest.trim());
int min = page * 10;
int max = Math.min(Baritone.settings().allSettings.size(), (page + 1) * 10);
logDirect("Settings " + min + " to " + (max - 1) + ":");
for (int i = min; i < max; i++) {
logDirect(Baritone.settings().allSettings.get(i).toString());
}
} catch (Exception ex) { // NumberFormatException | ArrayIndexOutOfBoundsException and probably some others I'm forgetting lol
ex.printStackTrace();
logDirect("All settings:");
for (Settings.Setting<?> setting : Baritone.settings().allSettings) {
logDirect(setting.toString());
}
logDirect("To get one page of ten settings at a time, do settings <num>");
}
return true;
}
if (msg.equals("") || msg.equals("help") || msg.equals("?")) {
for (String line : HELP_MSG.split("\n")) {
logDirect(line);
@@ -129,31 +152,24 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true;
}
if (msg.contains(" ")) {
String[] data = msg.split(" ");
if (data.length == 2) {
Settings.Setting setting = Baritone.settings().byLowerName.get(data[0]);
if (setting != null) {
String settingName = msg.substring(0, msg.indexOf(' '));
String settingValue = msg.substring(msg.indexOf(' ') + 1);
Settings.Setting setting = Baritone.settings().byLowerName.get(settingName);
if (setting != null) {
if (settingValue.equals("reset")) {
logDirect("Resetting setting " + settingName + " to default value.");
setting.reset();
} else {
try {
if (setting.value.getClass() == Long.class) {
setting.value = Long.parseLong(data[1]);
}
if (setting.value.getClass() == Integer.class) {
setting.value = Integer.parseInt(data[1]);
}
if (setting.value.getClass() == Double.class) {
setting.value = Double.parseDouble(data[1]);
}
if (setting.value.getClass() == Float.class) {
setting.value = Float.parseFloat(data[1]);
}
} catch (NumberFormatException e) {
logDirect("Unable to parse " + data[1]);
SettingsUtil.parseAndApply(Baritone.settings(), settingName, settingValue);
} catch (Exception ex) {
logDirect("Unable to parse setting");
return true;
}
SettingsUtil.save(Baritone.settings());
logDirect(setting.toString());
return true;
}
SettingsUtil.save(Baritone.settings());
logDirect(setting.toString());
return true;
}
}
if (Baritone.settings().byLowerName.containsKey(msg)) {
@@ -210,6 +226,20 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
}
return true;
}
if (msg.equals("proc")) {
Optional<IBaritoneProcess> proc = baritone.getPathingControlManager().mostRecentInControl();
if (!proc.isPresent()) {
logDirect("No process is in control");
return true;
}
IBaritoneProcess p = proc.get();
logDirect("Class: " + p.getClass());
logDirect("Priority: " + p.priority());
logDirect("Temporary: " + p.isTemporary());
logDirect("Display name: " + p.displayName());
logDirect("Command: " + baritone.getPathingControlManager().mostRecentCommand());
return true;
}
if (msg.equals("version")) {
String version = ExampleBaritoneControl.class.getPackage().getImplementationVersion();
if (version == null) {
@@ -236,6 +266,27 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
logDirect("Queued " + count + " chunks for repacking");
return true;
}
if (msg.startsWith("build")) {
String file;
BlockPos origin;
try {
String[] coords = msg.substring("build".length()).trim().split(" ");
file = coords[0] + ".schematic";
origin = new BlockPos(parseOrDefault(coords[1], ctx.playerFeet().x), parseOrDefault(coords[2], ctx.playerFeet().y), parseOrDefault(coords[3], ctx.playerFeet().z));
} catch (Exception ex) {
file = msg.substring(5).trim() + ".schematic";
origin = ctx.playerFeet();
}
logDirect("Loading '" + file + "' to build from origin " + origin);
boolean success = baritone.getBuilderProcess().build(file, origin);
logDirect(success ? "Loaded" : "Unable to load");
return true;
}
if (msg.equals("come")) {
customGoalProcess.setGoalAndPath(new GoalBlock(new BlockPos(mc.getRenderViewEntity())));
logDirect("Coming");
return true;
}
if (msg.equals("axis") || msg.equals("highway")) {
customGoalProcess.setGoalAndPath(new GoalAxis());
return true;
@@ -276,8 +327,37 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
});
return true;
}
if (msg.startsWith("cleararea")) {
String suffix = msg.substring("cleararea".length());
BlockPos corner1;
BlockPos corner2;
if (suffix.isEmpty()) {
// clear the area from the current goal to here
Goal goal = baritone.getPathingBehavior().getGoal();
if (goal == null || !(goal instanceof GoalBlock)) {
logDirect("Need to specify goal of opposite corner");
return true;
}
corner1 = ((GoalBlock) goal).getGoalPos();
corner2 = ctx.playerFeet();
} else {
try {
String[] spl = suffix.split(" ");
corner1 = ctx.playerFeet();
corner2 = new BlockPos(Integer.parseInt(spl[0]), Integer.parseInt(spl[1]), Integer.parseInt(spl[2]));
} catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {
logDirect("unable to parse");
return true;
}
}
baritone.getBuilderProcess().clearArea(corner1, corner2);
return true;
}
if (msg.equals("reset")) {
Baritone.settings().reset();
for (Settings.Setting setting : Baritone.settings().allSettings) {
setting.reset();
}
SettingsUtil.save(Baritone.settings());
logDirect("Baritone settings reset");
return true;
}
@@ -351,9 +431,24 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
logDirect("ok");
return true;
}
if (msg.startsWith("explore")) {
String rest = msg.substring("explore".length()).trim();
int centerX;
int centerZ;
try {
centerX = Integer.parseInt(rest.split(" ")[0]);
centerZ = Integer.parseInt(rest.split(" ")[1]);
} catch (Exception ex) {
centerX = ctx.playerFeet().x;
centerZ = ctx.playerFeet().z;
}
baritone.getExploreProcess().explore(centerX, centerZ);
logDirect("Exploring from " + centerX + "," + centerZ);
return true;
}
if (msg.startsWith("find")) {
String blockType = msg.substring(4).trim();
LinkedList<BlockPos> locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 4);
ArrayList<BlockPos> locs = baritone.getWorldProvider().getCurrentWorld().getCachedWorld().getLocationsOf(blockType, 1, ctx.playerFeet().getX(), ctx.playerFeet().getZ(), 4);
logDirect("Have " + locs.size() + " locations");
for (BlockPos pos : locs) {
Block actually = BlockStateInterface.get(ctx, pos).getBlock();
@@ -384,7 +479,17 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
logDirect("Started mining blocks of type " + Arrays.toString(blockTypes));
return true;
}
if (msg.startsWith("thisway")) {
if (msg.equals("click")) {
new Thread(() -> {
try {
Thread.sleep(100);
mc.addScheduledTask(() -> mc.displayGuiScreen(new GuiClick()));
} catch (Exception ignored) {}
}).start();
logDirect("aight dude");
return true;
}
if (msg.startsWith("thisway") || msg.startsWith("forward")) {
try {
Goal goal = GoalXZ.fromDirection(ctx.playerFeetAsVec(), ctx.player().rotationYaw, Double.parseDouble(msg.substring(7).trim()));
customGoalProcess.setGoal(goal);
@@ -470,7 +575,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return true;
}
}
Goal goal = new GoalBlock(waypoint.getLocation());
Goal goal = waypoint.getTag() == Waypoint.Tag.BED ? new GoalGetToBlock(waypoint.getLocation()) : new GoalBlock(waypoint.getLocation());
customGoalProcess.setGoalAndPath(goal);
return true;
}
@@ -510,7 +615,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
while (moves.contains(null)) {
moves.remove(null);
}
moves.sort(Comparator.comparingDouble(Movement::getCost));
moves.sort(Comparator.comparingDouble(move -> move.getCost(new CalculationContext(baritone))));
for (Movement move : moves) {
String[] parts = move.getClass().toString().split("\\.");
double cost = move.getCost();
@@ -528,6 +633,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper {
return false;
}
private int parseOrDefault(String str, int i) {
return str.equals("~") ? i : str.startsWith("~") ? Integer.parseInt(str.substring(1)) + i : Integer.parseInt(str);
}
private void log(List<ItemStack> stacks) {
for (ItemStack stack : stacks) {
if (!stack.isEmpty()) {

View File

@@ -0,0 +1,134 @@
/*
* 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.utils;
import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.pathing.goals.GoalTwoBlocks;
import baritone.api.utils.BetterBlockPos;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import org.lwjgl.BufferUtils;
import org.lwjgl.input.Mouse;
import org.lwjgl.util.glu.GLU;
import java.awt.*;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.Collections;
import static org.lwjgl.opengl.GL11.*;
public class GuiClick extends GuiScreen {
// My name is Brady and I grant leijurv permission to use this pasted code
private final FloatBuffer MODELVIEW = BufferUtils.createFloatBuffer(16);
private final FloatBuffer PROJECTION = BufferUtils.createFloatBuffer(16);
private final IntBuffer VIEWPORT = BufferUtils.createIntBuffer(16);
private final FloatBuffer TO_WORLD_BUFFER = BufferUtils.createFloatBuffer(3);
private BlockPos clickStart;
private BlockPos currentMouseOver;
@Override
public boolean doesGuiPauseGame() {
return false;
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
int mx = Mouse.getX();
int my = Mouse.getY();
Vec3d near = toWorld(mx, my, 0);
Vec3d far = toWorld(mx, my, 1); // "Use 0.945 that's what stack overflow says" - leijurv
if (near != null && far != null) {
Vec3d viewerPos = new Vec3d(mc.getRenderManager().viewerPosX, mc.getRenderManager().viewerPosY, mc.getRenderManager().viewerPosZ);
RayTraceResult result = mc.world.rayTraceBlocks(near.add(viewerPos), far.add(viewerPos), false, false, true);
if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) {
currentMouseOver = result.getBlockPos();
}
}
}
@Override
protected void mouseReleased(int mouseX, int mouseY, int mouseButton) {
if (mouseButton == 0) {
if (clickStart != null && !clickStart.equals(currentMouseOver)) {
((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getBuilderProcess().clearArea(clickStart, currentMouseOver);
clickStart = null;
} else {
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalTwoBlocks(currentMouseOver));
}
} else if (mouseButton == 1) {
BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(currentMouseOver.up()));
}
clickStart = null;
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) {
clickStart = currentMouseOver;
}
public void onRender() {
GlStateManager.getFloat(GL_MODELVIEW_MATRIX, (FloatBuffer) MODELVIEW.clear());
GlStateManager.getFloat(GL_PROJECTION_MATRIX, (FloatBuffer) PROJECTION.clear());
GlStateManager.glGetInteger(GL_VIEWPORT, (IntBuffer) VIEWPORT.clear());
if (currentMouseOver != null) {
Entity e = mc.getRenderViewEntity();
// drawSingleSelectionBox WHEN?
PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(currentMouseOver), Color.CYAN);
if (clickStart != null && !clickStart.equals(currentMouseOver)) {
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
GlStateManager.color(Color.RED.getColorComponents(null)[0], Color.RED.getColorComponents(null)[1], Color.RED.getColorComponents(null)[2], 0.4F);
GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value);
GlStateManager.disableTexture2D();
GlStateManager.depthMask(false);
GlStateManager.disableDepth();
BetterBlockPos a = new BetterBlockPos(currentMouseOver);
BetterBlockPos b = new BetterBlockPos(clickStart);
PathRenderer.drawAABB(new AxisAlignedBB(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z), Math.max(a.x, b.x) + 1, Math.max(a.y, b.y) + 1, Math.max(a.z, b.z) + 1));
GlStateManager.enableDepth();
GlStateManager.depthMask(true);
GlStateManager.enableTexture2D();
GlStateManager.disableBlend();
}
}
}
public Vec3d toWorld(double x, double y, double z) {
boolean result = GLU.gluUnProject((float) x, (float) y, (float) z, MODELVIEW, PROJECTION, VIEWPORT, (FloatBuffer) TO_WORLD_BUFFER.clear());
if (result) {
return new Vec3d(TO_WORLD_BUFFER.get(0), TO_WORLD_BUFFER.get(1), TO_WORLD_BUFFER.get(2));
}
return null;
}
}

View File

@@ -1,72 +1,72 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.utils;
import baritone.Baritone;
import net.minecraft.client.Minecraft;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
/**
* @author Brady
* @since 8/1/2018
*/
public interface Helper {
/**
* Instance of {@link Helper}. Used for static-context reference.
*/
Helper HELPER = new Helper() {};
ITextComponent MESSAGE_PREFIX = new TextComponentString(String.format(
"%s[%sBaritone%s]%s",
TextFormatting.DARK_PURPLE,
TextFormatting.LIGHT_PURPLE,
TextFormatting.DARK_PURPLE,
TextFormatting.GRAY
));
Minecraft mc = Minecraft.getMinecraft();
/**
* Send a message to chat only if chatDebug is on
*
* @param message The message to display in chat
*/
default void logDebug(String message) {
if (!Baritone.settings().chatDebug.get()) {
//System.out.println("Suppressed debug message:");
//System.out.println(message);
return;
}
logDirect(message);
}
/**
* Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a direct response to a chat command)
*
* @param message The message to display in chat
*/
default void logDirect(String message) {
ITextComponent component = MESSAGE_PREFIX.createCopy();
component.getStyle().setColor(TextFormatting.GRAY);
component.appendSibling(new TextComponentString(" " + message));
Minecraft.getMinecraft().addScheduledTask(() -> Baritone.settings().logger.get().accept(component));
}
}
/*
* 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.utils;
import baritone.Baritone;
import net.minecraft.client.Minecraft;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
/**
* @author Brady
* @since 8/1/2018
*/
public interface Helper {
/**
* Instance of {@link Helper}. Used for static-context reference.
*/
Helper HELPER = new Helper() {};
ITextComponent MESSAGE_PREFIX = new TextComponentString(String.format(
"%s[%sBaritone%s]%s",
TextFormatting.DARK_PURPLE,
TextFormatting.LIGHT_PURPLE,
TextFormatting.DARK_PURPLE,
TextFormatting.GRAY
));
Minecraft mc = Minecraft.getMinecraft();
/**
* Send a message to chat only if chatDebug is on
*
* @param message The message to display in chat
*/
default void logDebug(String message) {
if (!Baritone.settings().chatDebug.value) {
//System.out.println("Suppressed debug message:");
//System.out.println(message);
return;
}
logDirect(message);
}
/**
* Send a message to chat regardless of chatDebug (should only be used for critically important messages, or as a direct response to a chat command)
*
* @param message The message to display in chat
*/
default void logDirect(String message) {
ITextComponent component = MESSAGE_PREFIX.createCopy();
component.getStyle().setColor(TextFormatting.GRAY);
component.appendSibling(new TextComponentString(" " + message));
Minecraft.getMinecraft().addScheduledTask(() -> Baritone.settings().logger.value.accept(component));
}
}

View File

@@ -1,133 +1,118 @@
/*
* 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.utils;
import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.event.events.TickEvent;
import baritone.api.utils.IInputOverrideHandler;
import baritone.api.utils.input.Input;
import baritone.behavior.Behavior;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.util.MovementInputFromOptions;
import java.util.HashMap;
import java.util.Map;
/**
* An interface with the game's control system allowing the ability to
* force down certain controls, having the same effect as if we were actually
* physically forcing down the assigned key.
*
* @author Brady
* @since 7/31/2018
*/
public final class InputOverrideHandler extends Behavior implements IInputOverrideHandler {
/**
* Maps inputs to whether or not we are forcing their state down.
*/
private final Map<Input, Boolean> inputForceStateMap = new HashMap<>();
private final BlockBreakHelper blockBreakHelper;
public InputOverrideHandler(Baritone baritone) {
super(baritone);
this.blockBreakHelper = new BlockBreakHelper(baritone.getPlayerContext());
}
/**
* Returns whether or not we are forcing down the specified {@link KeyBinding}.
*
* @param key The KeyBinding object
* @return Whether or not it is being forced down
*/
@Override
public final Boolean isInputForcedDown(KeyBinding key) {
Input input = Input.getInputForBind(key);
if (input == null || !inControl()) {
return null;
}
if (input == Input.CLICK_LEFT) {
return false;
}
if (input == Input.CLICK_RIGHT) {
return isInputForcedDown(Input.CLICK_RIGHT);
}
return null;
}
/**
* Returns whether or not we are forcing down the specified {@link Input}.
*
* @param input The input
* @return Whether or not it is being forced down
*/
@Override
public final boolean isInputForcedDown(Input input) {
return input == null ? false : this.inputForceStateMap.getOrDefault(input, false);
}
/**
* Sets whether or not the specified {@link Input} is being forced down.
*
* @param input The {@link Input}
* @param forced Whether or not the state is being forced
*/
@Override
public final void setInputForceState(Input input, boolean forced) {
this.inputForceStateMap.put(input, forced);
}
/**
* Clears the override state for all keys
*/
@Override
public final void clearAllKeys() {
this.inputForceStateMap.clear();
}
@Override
public final void onTick(TickEvent event) {
if (event.getType() == TickEvent.Type.OUT) {
return;
}
blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT));
if (inControl()) {
if (ctx.player().movementInput.getClass() != PlayerMovementInput.class) {
ctx.player().movementInput = new PlayerMovementInput(this);
}
} else {
if (ctx.player().movementInput.getClass() == PlayerMovementInput.class) { // allow other movement inputs that aren't this one, e.g. for a freecam
ctx.player().movementInput = new MovementInputFromOptions(Minecraft.getMinecraft().gameSettings);
}
}
// only set it if it was previously incorrect
// gotta do it this way, or else it constantly thinks you're beginning a double tap W sprint lol
}
private boolean inControl() {
return baritone.getPathingBehavior().isPathing() || baritone != BaritoneAPI.getProvider().getPrimaryBaritone();
}
public BlockBreakHelper getBlockBreakHelper() {
return blockBreakHelper;
}
}
/*
* 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.utils;
import baritone.Baritone;
import baritone.api.BaritoneAPI;
import baritone.api.event.events.TickEvent;
import baritone.api.utils.IInputOverrideHandler;
import baritone.api.utils.input.Input;
import baritone.behavior.Behavior;
import net.minecraft.client.Minecraft;
import net.minecraft.util.MovementInputFromOptions;
import java.util.HashMap;
import java.util.Map;
/**
* An interface with the game's control system allowing the ability to
* force down certain controls, having the same effect as if we were actually
* physically forcing down the assigned key.
*
* @author Brady
* @since 7/31/2018
*/
public final class InputOverrideHandler extends Behavior implements IInputOverrideHandler {
/**
* Maps inputs to whether or not we are forcing their state down.
*/
private final Map<Input, Boolean> inputForceStateMap = new HashMap<>();
private final BlockBreakHelper blockBreakHelper;
private final BlockPlaceHelper blockPlaceHelper;
public InputOverrideHandler(Baritone baritone) {
super(baritone);
this.blockBreakHelper = new BlockBreakHelper(baritone.getPlayerContext());
this.blockPlaceHelper = new BlockPlaceHelper(baritone.getPlayerContext());
}
/**
* Returns whether or not we are forcing down the specified {@link Input}.
*
* @param input The input
* @return Whether or not it is being forced down
*/
@Override
public final boolean isInputForcedDown(Input input) {
return input == null ? false : this.inputForceStateMap.getOrDefault(input, false);
}
/**
* Sets whether or not the specified {@link Input} is being forced down.
*
* @param input The {@link Input}
* @param forced Whether or not the state is being forced
*/
@Override
public final void setInputForceState(Input input, boolean forced) {
this.inputForceStateMap.put(input, forced);
}
/**
* Clears the override state for all keys
*/
@Override
public final void clearAllKeys() {
this.inputForceStateMap.clear();
}
@Override
public final void onTick(TickEvent event) {
if (event.getType() == TickEvent.Type.OUT) {
return;
}
if (isInputForcedDown(Input.CLICK_LEFT)) {
setInputForceState(Input.CLICK_RIGHT, false);
}
blockBreakHelper.tick(isInputForcedDown(Input.CLICK_LEFT));
blockPlaceHelper.tick(isInputForcedDown(Input.CLICK_RIGHT));
if (inControl()) {
if (ctx.player().movementInput.getClass() != PlayerMovementInput.class) {
ctx.player().movementInput = new PlayerMovementInput(this);
}
} else {
if (ctx.player().movementInput.getClass() == PlayerMovementInput.class) { // allow other movement inputs that aren't this one, e.g. for a freecam
ctx.player().movementInput = new MovementInputFromOptions(Minecraft.getMinecraft().gameSettings);
}
}
// only set it if it was previously incorrect
// gotta do it this way, or else it constantly thinks you're beginning a double tap W sprint lol
}
private boolean inControl() {
// if we are not primary (a bot) we should set the movementinput even when idle (not pathing)
return baritone.getPathingBehavior().isPathing() || baritone != BaritoneAPI.getProvider().getPrimaryBaritone();
}
public BlockBreakHelper getBlockBreakHelper() {
return blockBreakHelper;
}
}

View File

@@ -57,10 +57,11 @@ public final class PathRenderer implements Helper {
private PathRenderer() {}
public static void render(RenderEvent event, PathingBehavior behavior) {
// System.out.println("Render passing");
// System.out.println(event.getPartialTicks());
float partialTicks = event.getPartialTicks();
Goal goal = behavior.getGoal();
if (mc.currentScreen instanceof GuiClick) {
((GuiClick) mc.currentScreen).onRender();
}
int thisPlayerDimension = behavior.baritone.getPlayerContext().world().provider.getDimensionType().getId();
int currentRenderViewDimension = BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext().world().provider.getDimensionType().getId();
@@ -80,9 +81,9 @@ public final class PathRenderer implements Helper {
}
if (goal != null && Baritone.settings().renderGoal.value) {
drawLitDankGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.get());
drawDankLitGoalBox(renderView, goal, partialTicks, Baritone.settings().colorGoalBox.value);
}
if (!Baritone.settings().renderPath.get()) {
if (!Baritone.settings().renderPath.value) {
return;
}
@@ -96,28 +97,28 @@ public final class PathRenderer implements Helper {
// Render the current path, if there is one
if (current != null && current.getPath() != null) {
int renderBegin = Math.max(current.getPosition() - 3, 0);
drawPath(current.getPath(), renderBegin, renderView, partialTicks, Baritone.settings().colorCurrentPath.get(), Baritone.settings().fadePath.get(), 10, 20);
drawPath(current.getPath(), renderBegin, renderView, partialTicks, Baritone.settings().colorCurrentPath.value, Baritone.settings().fadePath.value, 10, 20);
}
if (next != null && next.getPath() != null) {
drawPath(next.getPath(), 0, renderView, partialTicks, Baritone.settings().colorNextPath.get(), Baritone.settings().fadePath.get(), 10, 20);
drawPath(next.getPath(), 0, renderView, partialTicks, Baritone.settings().colorNextPath.value, Baritone.settings().fadePath.value, 10, 20);
}
//long split = System.nanoTime();
if (current != null) {
drawManySelectionBoxes(renderView, current.toBreak(), partialTicks, Baritone.settings().colorBlocksToBreak.get());
drawManySelectionBoxes(renderView, current.toPlace(), partialTicks, Baritone.settings().colorBlocksToPlace.get());
drawManySelectionBoxes(renderView, current.toWalkInto(), partialTicks, Baritone.settings().colorBlocksToWalkInto.get());
drawManySelectionBoxes(renderView, current.toBreak(), Baritone.settings().colorBlocksToBreak.value);
drawManySelectionBoxes(renderView, current.toPlace(), Baritone.settings().colorBlocksToPlace.value);
drawManySelectionBoxes(renderView, current.toWalkInto(), Baritone.settings().colorBlocksToWalkInto.value);
}
// If there is a path calculation currently running, render the path calculation process
behavior.getInProgress().ifPresent(currentlyRunning -> {
currentlyRunning.bestPathSoFar().ifPresent(p -> {
drawPath(p, 0, renderView, partialTicks, Baritone.settings().colorBestPathSoFar.get(), Baritone.settings().fadePath.get(), 10, 20);
drawPath(p, 0, renderView, partialTicks, Baritone.settings().colorBestPathSoFar.value, Baritone.settings().fadePath.value, 10, 20);
});
currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> {
drawPath(mr, 0, renderView, partialTicks, Baritone.settings().colorMostRecentConsidered.get(), Baritone.settings().fadePath.get(), 10, 20);
drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), partialTicks, Baritone.settings().colorMostRecentConsidered.get());
drawPath(mr, 0, renderView, partialTicks, Baritone.settings().colorMostRecentConsidered.value, Baritone.settings().fadePath.value, 10, 20);
drawManySelectionBoxes(renderView, Collections.singletonList(mr.getDest()), Baritone.settings().colorMostRecentConsidered.value);
});
});
//long end = System.nanoTime();
@@ -131,10 +132,10 @@ public final class PathRenderer implements Helper {
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F);
GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get());
GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value);
GlStateManager.disableTexture2D();
GlStateManager.depthMask(false);
if (Baritone.settings().renderPathIgnoreDepth.get()) {
if (Baritone.settings().renderPathIgnoreDepth.value) {
GlStateManager.disableDepth();
}
List<BetterBlockPos> positions = path.positions();
@@ -174,10 +175,10 @@ public final class PathRenderer implements Helper {
}
GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], alpha);
}
drawLine(player, x1, y1, z1, x2, y2, z2, partialTicks);
drawLine(player, x1, y1, z1, x2, y2, z2);
tessellator.draw();
}
if (Baritone.settings().renderPathIgnoreDepth.get()) {
if (Baritone.settings().renderPathIgnoreDepth.value) {
GlStateManager.enableDepth();
}
//GlStateManager.color(0.0f, 0.0f, 0.0f, 0.4f);
@@ -186,10 +187,10 @@ public final class PathRenderer implements Helper {
GlStateManager.disableBlend();
}
public static void drawLine(Entity player, double bp1x, double bp1y, double bp1z, double bp2x, double bp2y, double bp2z, float partialTicks) {
double d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks;
double d1 = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks;
double d2 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks;
public static void drawLine(Entity player, double bp1x, double bp1y, double bp1z, double bp2x, double bp2y, double bp2z) {
double d0 = mc.getRenderManager().viewerPosX;
double d1 = mc.getRenderManager().viewerPosY;
double d2 = mc.getRenderManager().viewerPosZ;
BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION);
BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).endVertex();
BUFFER.pos(bp2x + 0.5D - d0, bp2y + 0.5D - d1, bp2z + 0.5D - d2).endVertex();
@@ -198,24 +199,20 @@ public final class PathRenderer implements Helper {
BUFFER.pos(bp1x + 0.5D - d0, bp1y + 0.5D - d1, bp1z + 0.5D - d2).endVertex();
}
public static void drawManySelectionBoxes(Entity player, Collection<BlockPos> positions, float partialTicks, Color color) {
public static void drawManySelectionBoxes(Entity player, Collection<BlockPos> positions, Color color) {
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.4F);
GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get());
GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value);
GlStateManager.disableTexture2D();
GlStateManager.depthMask(false);
if (Baritone.settings().renderSelectionBoxesIgnoreDepth.get()) {
if (Baritone.settings().renderSelectionBoxesIgnoreDepth.value) {
GlStateManager.disableDepth();
}
float expand = 0.002F;
//BlockPos blockpos = movingObjectPositionIn.getBlockPos();
double renderPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks;
double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks;
double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks;
//BlockPos blockpos = movingObjectPositionIn.getBlockPos();
BlockStateInterface bsi = new BlockStateInterface(BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext()); // TODO this assumes same dimension between primary baritone and render view? is this safe?
positions.forEach(pos -> {
IBlockState state = bsi.get0(pos);
@@ -225,34 +222,10 @@ public final class PathRenderer implements Helper {
} else {
toDraw = state.getSelectedBoundingBox(player.world, pos);
}
toDraw = toDraw.expand(expand, expand, expand).offset(-renderPosX, -renderPosY, -renderPosZ);
BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION);
BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex();
TESSELLATOR.draw();
BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION);
BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex();
TESSELLATOR.draw();
BUFFER.begin(GL_LINES, DefaultVertexFormats.POSITION);
BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex();
TESSELLATOR.draw();
drawAABB(toDraw);
});
if (Baritone.settings().renderSelectionBoxesIgnoreDepth.get()) {
if (Baritone.settings().renderSelectionBoxesIgnoreDepth.value) {
GlStateManager.enableDepth();
}
@@ -261,11 +234,39 @@ public final class PathRenderer implements Helper {
GlStateManager.disableBlend();
}
public static void drawLitDankGoalBox(Entity player, Goal goal, float partialTicks, Color color) {
double renderPosX = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks;
double renderPosY = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks;
double renderPosZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks;
public static void drawAABB(AxisAlignedBB aabb) {
float expand = 0.002F;
AxisAlignedBB toDraw = aabb.expand(expand, expand, expand).offset(-mc.getRenderManager().viewerPosX, -mc.getRenderManager().viewerPosY, -mc.getRenderManager().viewerPosZ);
BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION);
BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex();
TESSELLATOR.draw();
BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION);
BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex();
TESSELLATOR.draw();
BUFFER.begin(GL_LINES, DefaultVertexFormats.POSITION);
BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex();
BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex();
TESSELLATOR.draw();
}
public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTicks, Color color) {
double renderPosX = mc.getRenderManager().viewerPosX;
double renderPosY = mc.getRenderManager().viewerPosY;
double renderPosZ = mc.getRenderManager().viewerPosZ;
double minX;
double maxX;
double minZ;
@@ -296,10 +297,12 @@ public final class PathRenderer implements Helper {
} else if (goal instanceof GoalXZ) {
GoalXZ goalPos = (GoalXZ) goal;
if (Baritone.settings().renderGoalXZBeacon.get()) {
if (Baritone.settings().renderGoalXZBeacon.value) {
glPushAttrib(GL_LIGHTING_BIT);
mc.getTextureManager().bindTexture(TileEntityBeaconRenderer.TEXTURE_BEACON_BEAM);
if (Baritone.settings().renderGoalIgnoreDepth.get()) {
if (Baritone.settings().renderGoalIgnoreDepth.value) {
GlStateManager.disableDepth();
}
@@ -315,9 +318,11 @@ public final class PathRenderer implements Helper {
color.getColorComponents(null)
);
if (Baritone.settings().renderGoalIgnoreDepth.get()) {
if (Baritone.settings().renderGoalIgnoreDepth.value) {
GlStateManager.enableDepth();
}
glPopAttrib();
return;
}
@@ -332,7 +337,7 @@ public final class PathRenderer implements Helper {
maxY = 256 - renderPosY;
} else if (goal instanceof GoalComposite) {
for (Goal g : ((GoalComposite) goal).goals()) {
drawLitDankGoalBox(player, g, partialTicks, color);
drawDankLitGoalBox(player, g, partialTicks, color);
}
return;
} else {
@@ -342,10 +347,10 @@ public final class PathRenderer implements Helper {
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
GlStateManager.color(color.getColorComponents(null)[0], color.getColorComponents(null)[1], color.getColorComponents(null)[2], 0.6F);
GlStateManager.glLineWidth(Baritone.settings().goalRenderLineWidthPixels.get());
GlStateManager.glLineWidth(Baritone.settings().goalRenderLineWidthPixels.value);
GlStateManager.disableTexture2D();
GlStateManager.depthMask(false);
if (Baritone.settings().renderGoalIgnoreDepth.get()) {
if (Baritone.settings().renderGoalIgnoreDepth.value) {
GlStateManager.disableDepth();
}
@@ -363,7 +368,7 @@ public final class PathRenderer implements Helper {
BUFFER.pos(minX, maxY, maxZ).endVertex();
TESSELLATOR.draw();
if (Baritone.settings().renderGoalIgnoreDepth.get()) {
if (Baritone.settings().renderGoalIgnoreDepth.value) {
GlStateManager.enableDepth();
}
GlStateManager.depthMask(true);

View File

@@ -0,0 +1,32 @@
/*
* 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.utils;
import baritone.api.pathing.goals.Goal;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.pathing.movement.CalculationContext;
public class PathingCommandContext extends PathingCommand {
public final CalculationContext desiredCalcContext;
public PathingCommandContext(Goal goal, PathingCommandType commandType, CalculationContext context) {
super(goal, commandType);
this.desiredCalcContext = context;
}
}

View File

@@ -24,16 +24,17 @@ import baritone.api.pathing.calc.IPathingControlManager;
import baritone.api.pathing.goals.Goal;
import baritone.api.process.IBaritoneProcess;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.behavior.PathingBehavior;
import baritone.pathing.path.PathExecutor;
import net.minecraft.util.math.BlockPos;
import java.util.*;
import java.util.stream.Stream;
public class PathingControlManager implements IPathingControlManager {
private final Baritone baritone;
private final HashSet<IBaritoneProcess> processes; // unGh
private final List<IBaritoneProcess> active;
private IBaritoneProcess inControlLastTick;
private IBaritoneProcess inControlThisTick;
private PathingCommand command;
@@ -41,13 +42,13 @@ public class PathingControlManager implements IPathingControlManager {
public PathingControlManager(Baritone baritone) {
this.baritone = baritone;
this.processes = new HashSet<>();
this.active = new ArrayList<>();
baritone.getGameEventHandler().registerEventListener(new AbstractGameEventListener() { // needs to be after all behavior ticks
@Override
public void onTick(TickEvent event) {
if (event.getType() == TickEvent.Type.OUT) {
return;
if (event.getType() == TickEvent.Type.IN) {
postTick();
}
postTick();
}
});
}
@@ -62,6 +63,7 @@ public class PathingControlManager implements IPathingControlManager {
inControlLastTick = null;
inControlThisTick = null;
command = null;
active.clear();
for (IBaritoneProcess proc : processes) {
proc.onLostControl();
if (proc.isActive() && !proc.isTemporary()) { // it's okay only for a temporary thing (like combat pause) to maintain control even if you say to cancel
@@ -82,12 +84,19 @@ public class PathingControlManager implements IPathingControlManager {
public void preTick() {
inControlLastTick = inControlThisTick;
inControlThisTick = null;
PathingBehavior p = baritone.getPathingBehavior();
command = executeProcesses();
if (command == null) {
p.cancelSegmentIfSafe();
p.secretInternalSetGoal(null);
return;
}
if (inControlThisTick != inControlLastTick && command.commandType != PathingCommandType.REQUEST_PAUSE) {
// if control has changed, and the new process wants to do something
p.cancelSegmentIfSafe();
// get rid of the in progress stuff from the last process
}
switch (command.commandType) {
case REQUEST_PAUSE:
p.requestPause();
@@ -98,18 +107,18 @@ public class PathingControlManager implements IPathingControlManager {
break;
case FORCE_REVALIDATE_GOAL_AND_PATH:
if (!p.isPathing() && !p.getInProgress().isPresent()) {
p.secretInternalSetGoalAndPath(command.goal);
p.secretInternalSetGoalAndPath(command);
}
break;
case REVALIDATE_GOAL_AND_PATH:
if (!p.isPathing() && !p.getInProgress().isPresent()) {
p.secretInternalSetGoalAndPath(command.goal);
p.secretInternalSetGoalAndPath(command);
}
break;
case SET_GOAL_AND_PATH:
// now this i can do
if (command.goal != null) {
baritone.getPathingBehavior().secretInternalSetGoalAndPath(command.goal);
baritone.getPathingBehavior().secretInternalSetGoalAndPath(command);
}
break;
default:
@@ -132,13 +141,13 @@ public class PathingControlManager implements IPathingControlManager {
// pwnage
p.softCancelIfSafe();
}
p.secretInternalSetGoalAndPath(command.goal);
p.secretInternalSetGoalAndPath(command);
break;
case REVALIDATE_GOAL_AND_PATH:
if (Baritone.settings().cancelOnGoalInvalidation.get() && (command.goal == null || revalidateGoal(command.goal))) {
if (Baritone.settings().cancelOnGoalInvalidation.value && (command.goal == null || revalidateGoal(command.goal))) {
p.softCancelIfSafe();
}
p.secretInternalSetGoalAndPath(command.goal);
p.secretInternalSetGoalAndPath(command);
break;
default:
}
@@ -171,12 +180,20 @@ public class PathingControlManager implements IPathingControlManager {
public PathingCommand executeProcesses() {
Stream<IBaritoneProcess> inContention = processes.stream()
.filter(IBaritoneProcess::isActive)
.sorted(Comparator.comparingDouble(IBaritoneProcess::priority).reversed());
for (IBaritoneProcess process : processes) {
if (process.isActive()) {
if (!active.contains(process)) {
// put a newly active process at the very front of the queue
active.add(0, process);
}
} else {
active.remove(process);
}
}
// ties are broken by which was added to the beginning of the list first
active.sort(Comparator.comparingDouble(IBaritoneProcess::priority).reversed());
Iterator<IBaritoneProcess> iterator = inContention.iterator();
Iterator<IBaritoneProcess> iterator = active.iterator();
while (iterator.hasNext()) {
IBaritoneProcess proc = iterator.next();

View File

@@ -31,7 +31,7 @@ public class PlayerMovementInput extends MovementInput {
this.moveStrafe = 0.0F;
this.moveForward = 0.0F;
jump = handler.isInputForcedDown(Input.JUMP); // oppa
jump = handler.isInputForcedDown(Input.JUMP); // oppa gangnam
if (this.forwardKeyDown = handler.isInputForcedDown(Input.MOVE_FORWARD)) {
this.moveForward++;

View File

@@ -55,7 +55,7 @@ public class ToolSet {
breakStrengthCache = new HashMap<>();
this.player = player;
if (Baritone.settings().considerPotionEffects.get()) {
if (Baritone.settings().considerPotionEffects.value) {
double amplifier = potionAmplifier();
Function<Double, Double> amplify = x -> amplifier * x;
backendCalculation = amplify.compose(this::getBestDestructionTime);

View File

@@ -57,17 +57,17 @@ public class Avoidance {
}
public static List<Avoidance> create(IPlayerContext ctx) {
if (!Baritone.settings().avoidance.get()) {
if (!Baritone.settings().avoidance.value) {
return Collections.emptyList();
}
List<Avoidance> res = new ArrayList<>();
double mobSpawnerCoeff = Baritone.settings().mobSpawnerAvoidanceCoefficient.get();
double mobCoeff = Baritone.settings().mobAvoidanceCoefficient.get();
double mobSpawnerCoeff = Baritone.settings().mobSpawnerAvoidanceCoefficient.value;
double mobCoeff = Baritone.settings().mobAvoidanceCoefficient.value;
if (mobSpawnerCoeff != 1.0D) {
ctx.worldData().getCachedWorld().getLocationsOf("mob_spawner", 1, ctx.playerFeet().x, ctx.playerFeet().z, 2).forEach(mobspawner -> res.add(new Avoidance(mobspawner, mobSpawnerCoeff, Baritone.settings().mobSpawnerAvoidanceRadius.get())));
ctx.worldData().getCachedWorld().getLocationsOf("mob_spawner", 1, ctx.playerFeet().x, ctx.playerFeet().z, 2).forEach(mobspawner -> res.add(new Avoidance(mobspawner, mobSpawnerCoeff, Baritone.settings().mobSpawnerAvoidanceRadius.value)));
}
if (mobCoeff != 1.0D) {
ctx.world().loadedEntityList.stream().filter(entity -> entity instanceof EntityMob).forEach(entity -> res.add(new Avoidance(new BlockPos(entity), mobCoeff, Baritone.settings().mobAvoidanceRadius.get())));
ctx.world().loadedEntityList.stream().filter(entity -> entity instanceof EntityMob).forEach(entity -> res.add(new Avoidance(new BlockPos(entity), mobCoeff, Baritone.settings().mobAvoidanceRadius.value)));
}
return res;
}

View File

@@ -17,27 +17,27 @@
package baritone.utils.pathing;
import baritone.Baritone;
import baritone.api.pathing.calc.IPath;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.IPlayerContext;
import baritone.pathing.movement.CalculationContext;
import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap;
public final class Favoring {
private final Long2DoubleOpenHashMap favorings;
public Favoring(IPlayerContext ctx, IPath previous) {
this(previous);
public Favoring(IPlayerContext ctx, IPath previous, CalculationContext context) {
this(previous, context);
for (Avoidance avoid : Avoidance.create(ctx)) {
avoid.applySpherical(favorings);
}
System.out.println("Favoring size: " + favorings.size());
}
public Favoring(IPath previous) { // create one just from previous path, no mob avoidances
public Favoring(IPath previous, CalculationContext context) { // create one just from previous path, no mob avoidances
favorings = new Long2DoubleOpenHashMap();
favorings.defaultReturnValue(1.0D);
double coeff = Baritone.settings().backtrackCostFavoringCoefficient.get();
double coeff = context.backtrackCostFavoringCoefficient;
if (coeff != 1D && previous != null) {
previous.positions().forEach(pos -> favorings.put(BetterBlockPos.longHash(pos), coeff));
}

View File

@@ -28,7 +28,7 @@ import net.minecraft.util.math.BlockPos;
public abstract class PathBase implements IPath {
@Override
public PathBase cutoffAtLoadedChunks(Object bsi0) { // <-- cursed cursed cursed
if (!Baritone.settings().cutoffAtLoadBoundary.get()) {
if (!Baritone.settings().cutoffAtLoadBoundary.value) {
return this;
}
BlockStateInterface bsi = (BlockStateInterface) bsi0;
@@ -43,14 +43,14 @@ public abstract class PathBase implements IPath {
@Override
public PathBase staticCutoff(Goal destination) {
int min = BaritoneAPI.getSettings().pathCutoffMinimumLength.get();
int min = BaritoneAPI.getSettings().pathCutoffMinimumLength.value;
if (length() < min) {
return this;
}
if (destination == null || destination.isInGoal(getDest())) {
return this;
}
double factor = BaritoneAPI.getSettings().pathCutoffFactor.get();
double factor = BaritoneAPI.getSettings().pathCutoffFactor.value;
int newLength = (int) ((length() - min) * factor) + min - 1;
return new CutoffPath(this, newLength);
}

View File

@@ -87,8 +87,8 @@ public class SegmentedCalculator {
private PathCalculationResult segment(Optional<IPath> previous) {
BetterBlockPos segmentStart = previous.map(IPath::getDest).orElse(start); // <-- e p i c
AbstractNodeCostSearch search = new AStarPathFinder(segmentStart.x, segmentStart.y, segmentStart.z, goal, new Favoring(previous.orElse(null)), context); // this is on another thread, so cannot include mob avoidances.
return search.calculate(Baritone.settings().primaryTimeoutMS.get(), Baritone.settings().failureTimeoutMS.get()); // use normal time settings, not the plan ahead settings, so as to not overwhelm the computer
AbstractNodeCostSearch search = new AStarPathFinder(segmentStart.x, segmentStart.y, segmentStart.z, goal, new Favoring(previous.orElse(null), context), context); // this is on another thread, so cannot include mob avoidances.
return search.calculate(Baritone.settings().primaryTimeoutMS.value, Baritone.settings().failureTimeoutMS.value); // use normal time settings, not the plan ahead settings, so as to not overwhelm the computer
}
public static void calculateSegmentsThreaded(BetterBlockPos start, Goal goal, CalculationContext context, Consumer<IPath> onCompletion, Runnable onFailure) {

View File

@@ -21,6 +21,7 @@ import baritone.api.BaritoneAPI;
import baritone.api.cache.IWorldData;
import baritone.api.utils.IPlayerContext;
import baritone.api.utils.IPlayerController;
import baritone.api.utils.RayTraceUtils;
import baritone.utils.Helper;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.util.math.RayTraceResult;
@@ -58,6 +59,6 @@ public enum PrimaryPlayerContext implements IPlayerContext, Helper {
@Override
public RayTraceResult objectMouseOver() {
return mc.objectMouseOver;
return RayTraceUtils.rayTraceTowards(player(), playerRotations(), playerController().getBlockReachDistance());
}
}

View File

@@ -19,12 +19,18 @@ package baritone.utils.player;
import baritone.api.utils.IPlayerController;
import baritone.utils.Helper;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ClickType;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.GameType;
import net.minecraft.world.World;
/**
* Implementation of {@link IPlayerController} that chains to the primary player controller's methods
@@ -60,4 +66,10 @@ public enum PrimaryPlayerController implements IPlayerController, Helper {
public GameType getGameType() {
return mc.playerController.getCurrentGameType();
}
@Override
public EnumActionResult processRightClickBlock(EntityPlayerSP player, World world, BlockPos pos, EnumFacing direction, Vec3d vec, EnumHand hand) {
// primaryplayercontroller is always in a WorldClient so this is ok
return mc.playerController.processRightClickBlock(player, (WorldClient) world, pos, direction, vec, hand);
}
}

View File

@@ -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.utils.schematic;
import baritone.api.utils.ISchematic;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
public class AirSchematic implements ISchematic {
private final int widthX;
private final int heightY;
private final int lengthZ;
public AirSchematic(int widthX, int heightY, int lengthZ) {
this.widthX = widthX;
this.heightY = heightY;
this.lengthZ = lengthZ;
}
@Override
public IBlockState desiredState(int x, int y, int z) {
return Blocks.AIR.getDefaultState();
}
@Override
public int widthX() {
return widthX;
}
@Override
public int heightY() {
return heightY;
}
@Override
public int lengthZ() {
return lengthZ;
}
}

View File

@@ -0,0 +1,66 @@
/*
* 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.utils.schematic;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import java.util.OptionalInt;
import java.util.function.Predicate;
public class MapArtSchematic extends Schematic {
private final int[][] heightMap;
public MapArtSchematic(NBTTagCompound schematic) {
super(schematic);
heightMap = new int[widthX][lengthZ];
for (int x = 0; x < widthX; x++) {
for (int z = 0; z < lengthZ; z++) {
IBlockState[] column = states[x][z];
OptionalInt lowestBlockY = lastIndexMatching(column, block -> block != Blocks.AIR);
if (lowestBlockY.isPresent()) {
heightMap[x][z] = lowestBlockY.getAsInt();
} else {
System.out.println("Column " + x + "," + z + " has no blocks, but it's apparently map art? wtf");
System.out.println("Letting it be whatever");
heightMap[x][z] = 256;
}
}
}
}
private static <T> OptionalInt lastIndexMatching(T[] arr, Predicate<? super T> predicate) {
for (int y = arr.length - 1; y >= 0; y--) {
if (predicate.test(arr[y])) {
return OptionalInt.of(y);
}
}
return OptionalInt.empty();
}
@Override
public boolean inSchematic(int x, int y, int z) {
// in map art, we only care about coordinates in or above the art
return super.inSchematic(x, y, z) && y >= heightMap[x][z];
}
}

View File

@@ -0,0 +1,89 @@
/*
* 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.utils.schematic;
import baritone.api.utils.ISchematic;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
public class Schematic implements ISchematic {
public final int widthX;
public final int heightY;
public final int lengthZ;
protected final IBlockState[][][] states;
public Schematic(NBTTagCompound schematic) {
String type = schematic.getString("Materials");
if (!type.equals("Alpha")) {
throw new IllegalStateException("bad schematic " + type);
}
widthX = schematic.getInteger("Width");
heightY = schematic.getInteger("Height");
lengthZ = schematic.getInteger("Length");
byte[] blocks = schematic.getByteArray("Blocks");
byte[] metadata = schematic.getByteArray("Data");
byte[] additional = null;
if (schematic.hasKey("AddBlocks")) {
byte[] addBlocks = schematic.getByteArray("AddBlocks");
additional = new byte[addBlocks.length * 2];
for (int i = 0; i < addBlocks.length; i++) {
additional[i * 2 + 0] = (byte) ((addBlocks[i] >> 4) & 0xF); // lower nibble
additional[i * 2 + 1] = (byte) ((addBlocks[i] >> 0) & 0xF); // upper nibble
}
}
states = new IBlockState[widthX][lengthZ][heightY];
for (int y = 0; y < heightY; y++) {
for (int z = 0; z < lengthZ; z++) {
for (int x = 0; x < widthX; x++) {
int blockInd = (y * lengthZ + z) * widthX + x;
int blockID = blocks[blockInd] & 0xFF;
if (additional != null) {
// additional is 0 through 15 inclusive since it's & 0xF above
blockID |= additional[blockInd] << 8;
}
Block block = Block.REGISTRY.getObjectById(blockID);
int meta = metadata[blockInd] & 0xFF;
states[x][z][y] = block.getStateFromMeta(meta);
}
}
}
}
@Override
public IBlockState desiredState(int x, int y, int z) {
return states[x][z][y];
}
@Override
public int widthX() {
return widthX;
}
@Override
public int heightY() {
return heightY;
}
@Override
public int lengthZ() {
return lengthZ;
}
}