Compare commits

..

347 Commits

Author SHA1 Message Date
Leijurv
105c7d438a v1.3.5 2019-10-11 17:29:27 -07:00
Leijurv
1c00e167ca Merge branch 'master' into 1.13.2 2019-10-11 16:56:04 -07:00
Leijurv
861ee5049a unscuff 2019-10-11 16:15:38 -07:00
Brady
2f9efae457 Refactors to improve consistency 2019-10-11 18:15:14 -05:00
Brady
c1fe588de4 Leijurv is crying and shaking right now 2019-10-11 18:08:39 -05:00
Brady
8fa2dac261 This should fix tab complete scuff 2019-10-11 17:59:36 -05:00
Leijurv
5e9b439591 avery byte scuff btfo 2019-10-10 17:47:26 -07:00
Leijurv
f0ae31f455 fake merge of master into 1.13.2 2019-10-09 20:45:55 -07:00
Leijurv
dc7d64fb88 Merge commit 'ce2fc6f2514245987659b378687f795ab641cf1e' into 1.13.2 2019-10-09 20:44:22 -07:00
Brady
42306055ee Backport anti-poz from 1.13.2 branch to 1.12.2/master 2019-10-09 21:29:48 -05:00
Brady
62df244db7 Initial Brigadier overriden tab completion 2019-10-09 21:19:58 -05:00
Leijurv
ce2fc6f251 no more allowVines crash 2019-10-09 10:50:12 -07:00
Brady
0b2bab6549 Clean up performance Mixins 2019-10-07 17:25:09 -05:00
Brady
eb619adf4a Whoops! 2019-10-07 16:50:43 -05:00
Brady
4d05b152f0 Create ICommand to go alongside Command default implementation 2019-10-07 16:46:21 -05:00
Brady
c908552174 Clarify the default arg parsers 2019-10-07 10:08:52 -05:00
Brady
f1bbdc177f Collapse the sub-packages under helpers 2019-10-07 10:06:05 -05:00
Brady
9591b6fdef Move IArgConsumer from *.helpers.arguments to *.argument 2019-10-07 10:00:04 -05:00
Leijurv
2b4d6f4aa0 Merge branch 'master' into 1.13.2 2019-10-06 17:32:35 -07:00
Leijurv
8f0a8b6f56 fix inefficient schematic block lookups 2019-10-06 17:32:25 -07:00
Leijurv
7e505fc68f fix dropped items scanning 2019-10-06 16:00:26 -07:00
Leijurv
9c323aba91 Merge branch 'master' into 1.13.2 2019-10-06 15:51:27 -07:00
Leijurv
d1c2a0491c only one goto target 2019-10-06 13:49:24 -07:00
Leijurv
d19039e3e5 goto is back 2019-10-06 13:44:37 -07:00
Leijurv
22d5cb8068 loiter around ores to anticipate a possible drop 2019-10-06 13:26:29 -07:00
Leijurv
5f0d3a4018 resume builder too 2019-10-06 13:24:50 -07:00
Brady
889e288524 Refactor *.util.command to *.command 2019-10-06 15:21:21 -05:00
Leijurv
06805057d4 unscuff js code 2019-10-05 19:49:38 -07:00
Leijurv
6e1e355a61 Merge pull request #1016 from joerez/feature/1015/goal-revamps
#1015 Feature/1015/goal revamps
2019-10-05 19:42:02 -07:00
Joerez
9843e8048d issue-1015 better handling
Delete org.eclipse.buildship.core.prefs

Delete .project

issue-1015 removed unessesary conversion

issue-1015 users can use k in their #todo arguments to multiply the goal by 1000
2019-10-05 19:31:32 -07:00
Brady
29d8ab43f2 un-poz some Command stuff 2019-10-04 19:22:15 -05:00
Brady
1440e81ea4 IArgParser API 2019-10-04 18:12:36 -05:00
Brady
bfd8773efa Make getBaritoneForPlayer null-safe 2019-10-04 09:20:26 -05:00
Brady
3a3d880d81 ArgConsumer API separation 2019-10-04 08:55:02 -05:00
Leijurv
089c5fb095 fix buildinlayers crash 2019-10-01 14:29:19 -07:00
Brady
f1fb109d40 Remove ICommandExecution due to redundancy 2019-09-30 21:41:30 -05:00
Leijurv
ae9671bff0 meme fix, things work now 2019-09-30 17:57:09 -07:00
Leijurv
d256f05787 Merge branch 'master' into 1.13.2 2019-09-30 17:52:47 -07:00
Leijurv
47e6a039ef delet 2019-09-30 17:04:33 -07:00
Brady
b8c8b1eb69 Merge pull request #952 from cabaletta/commands
Commands
2019-09-30 18:45:22 -05:00
Leijurv
8a396db80e fix brainlet block breaking issue 2019-09-28 16:28:58 -07:00
Brady
6a90b57ced Some basic API/Main separation 2019-09-28 10:21:07 -05:00
Brady
a75b90fcef crucial performance optimization 2019-09-27 17:07:40 -05:00
Brady
9981af67d5 Remove debug code 2019-09-27 11:10:57 -05:00
Brady
cf60a5f3bd Clean up some things with DefaultCommands 2019-09-27 10:18:46 -05:00
Brady
a04742085e Add documentation to datatypes 2019-09-27 09:54:55 -05:00
Brady
b75a78f3d3 Fix the scuff 2019-09-26 23:33:37 -05:00
Brady
45bea50c91 Fix remaining usages to be in-line with previous commit 2019-09-26 23:20:45 -05:00
Brady
5ba1e67ea0 Don't print stack-traces to chat, just inform the user of the error 2019-09-26 23:18:05 -05:00
Brady
1064a79e1d Fix javadoc errors 2019-09-26 22:59:15 -05:00
Brady
3803bc631b Basically game on the imports 2019-09-26 19:02:21 -05:00
Brady
0b39b3e7b4 FORCE_COMMAND_PREFIX should be exposed to the API 2019-09-26 18:59:29 -05:00
Brady
2f480fcec2 BaritoneChatControl -> main 2019-09-26 18:57:08 -05:00
Brady
a8b1badd8a Remove the special command system exclusions from proguard config 2019-09-26 18:55:15 -05:00
Brady
f8f214ca90 Fix some null substitutions 2019-09-26 18:52:29 -05:00
Brady
595f5a35e0 Datatype Singletons 2019-09-26 18:49:26 -05:00
Brady
9f271b1f44 Future-compatibility for multiple Baritone instances 2019-09-25 18:27:47 -05:00
Brady
7292245b55 Rename PlayerByUsername to NearbyPlayer 2019-09-22 14:41:30 -05:00
Brady
9ffca6ad66 Minor javadoc tidy up 2019-09-21 17:45:53 -05:00
Brady
376c93bd3b Consistent Stream.of usage over Arrays.stream 2019-09-21 17:37:13 -05:00
Brady
204f9d2e31 Fix redundant Stream.of usage 2019-09-21 17:25:20 -05:00
Brady
e4353e489f Get rid of default implementation of IArgParser 2019-09-21 17:11:15 -05:00
Brady
b88af1d682 CommandManager is now Baritone instance dependent 2019-09-21 02:40:03 -05:00
Brady
9d2f83d8d6 Fix unused imports 2019-09-21 02:11:46 -05:00
Brady
ea4f34cb0f No more passing Settings to execute and tabComplete 2019-09-21 02:07:10 -05:00
Brady
b7eaae88a8 Checked Command Exceptions 2019-09-20 18:32:43 -05:00
Leijurv
e70d18f046 Merge pull request #963 from 0-x-2-2/commands
Merge master into commands.
2019-09-20 13:34:09 -07:00
0x22
5a83b791bb Merge remote-tracking branch 'upstream/master' into commands 2019-09-20 16:29:54 -04:00
Brady
eaa426dd66 Fix poor usage of Cloneable
Because super.clone() isn't being called, the idea of "Cloneable" isn't upheld.
2019-09-20 09:51:57 -05:00
Leijurv
fc43ef9308 Merge pull request #956 from LoganDark/commands
Pulling in logandark's uncommitted changes to commands staging
2019-09-19 21:49:27 -07:00
Logan Darklock
8b4ac3893e Tweaks and \n fix 2019-09-19 21:40:55 -07:00
Brady
a0f412f255 Some ArgParser cleanups 2019-09-19 21:24:44 -05:00
Leijurv
0a2e3f98f9 freecam meme 2019-09-19 18:23:05 -07:00
Leijurv
6cc29712e2 fix mine ordering 2019-09-19 17:53:50 -07:00
Leijurv
fae24beaed Merge pull request #954 from 0-x-2-2/commands
Attempt to "fix" travis.
2019-09-19 17:10:26 -07:00
0x22
394775fb9a Attempt to "fix" travis. 2019-09-19 20:06:18 -04:00
Leijurv
5d9209ce80 Merge pull request #953 from 0-x-2-2/commands
Removed very angry code. Started feeding Codacy.
2019-09-19 16:30:42 -07:00
Leijurv
aff3103f36 Merge pull request #941 from BlueBlazeTech/patch-1
Updated Standards section of CODE_OF_CONDUCT.md
2019-09-19 16:07:05 -07:00
0x22
6f2529c243 Removed very angry code. Started feeding Codacy. 2019-09-19 18:54:24 -04:00
Leijurv
e976224258 a moderate amount of gamer 2019-09-19 15:31:21 -07:00
Leijurv
050b6046d7 small tweaks 2019-09-19 14:43:18 -07:00
Leijurv
f0c78751bf no more asList static 2019-09-19 14:40:58 -07:00
Leijurv
2870d2d69e Merge pull request #951 from 0-x-2-2/commands
Fix a MAJOR bug caused by the JetBrains™ AutoFormatter™
2019-09-19 14:38:00 -07:00
0x22
fbabbe69c0 Fix a MAJOR bug caused by the JetBrains™ AutoFormatter™ 2019-09-19 17:36:06 -04:00
Leijurv
b63c54b657 remove isNull and nonNull 2019-09-19 14:34:45 -07:00
Leijurv
3c914de690 Merge pull request #950 from 0-x-2-2/commands
Remove retarded MC field.
2019-09-19 14:07:59 -07:00
0x22
307d6a0628 Remove retarded MC field 2019-09-19 17:05:15 -04:00
Leijurv
61d4f102ba its too many blank lines 2019-09-19 13:43:40 -07:00
Leijurv
0a38e6f690 standardize on this 2019-09-19 13:40:46 -07:00
Leijurv
23a592ec01 it launches 2019-09-19 13:30:40 -07:00
Leijurv
396a96d604 reformat 2019-09-19 12:53:15 -07:00
Leijurv
0504a1d4bf Merge pull request #949 from LoganDark/commands
Commands
2019-09-19 12:51:21 -07:00
Leijurv
fa905b8844 fix breaking blocks 2019-09-19 12:29:33 -07:00
BlueBlazeTech
7f58847f88 Updated Standards section of CODE_OF_CONDUCT.md
added additional details to standards
-line 20
-line 17
-line 32
2019-09-18 09:37:40 -06:00
Leijurv
5f674b86f8 add a setting to scan a larger radius every tick 2019-09-16 23:17:20 -07:00
Leijurv
cccd61e050 add ability to build from opposite corner 2019-09-15 11:37:09 -07:00
Leijurv
bf03a000d1 diagonal ascend 2019-09-09 23:06:36 -07:00
Logan Darklock
fc63c16ee0 initialize chat control only once ever 2019-09-07 00:21:54 -07:00
Logan Darklock
1bb4e44b71 bom import * 2019-09-06 17:50:55 -07:00
Logan Darklock
147884f76d mineprocess reformat too 2019-09-06 17:46:26 -07:00
Logan Darklock
240af75ff7 that specific continuation indent 2019-09-06 17:45:34 -07:00
Logan Darklock
c54dcdba24 "stAnDaRd" ConTinuATion InDEnT 2019-09-06 17:41:27 -07:00
Logan Darklock
9db07faf49 import * 2019-09-06 17:31:41 -07:00
Logan Darklock
aefc82e47c Review 2 2019-09-06 17:22:55 -07:00
Logan Darklock
957f62ffbb Merge branch 'upstream' into commands 2019-09-06 04:01:16 -07:00
Logan Darklock
8a001a2438 Review 2019-09-06 03:59:10 -07:00
Leijurv
f8d4e22b13 Update SETUP.md 2019-09-04 17:15:46 -07:00
Leijurv
243e6e3b99 Update README.md 2019-09-04 17:15:27 -07:00
Logan Darklock
69e3481a32 move default commands to main module 2019-09-04 11:17:36 -07:00
Logan Darklock
daa0d0c859 copyright notices 2019-09-04 09:16:36 -07:00
Logan Darklock
72402052ae Merge branch 'master' into commands 2019-09-04 09:06:43 -07:00
Logan Darklock
5ee1e738f4 Fix RelativePath and build command 2019-09-04 02:30:24 -07:00
Logan Darklock
382ad0079c DrawAABB changes, set command bugfix, sel rendering change, selection setting name changes 2019-09-03 23:46:20 -07:00
Logan Darklock
8dc4ff26d6 Persistent renderManager, selection transparency setting, drawAABB fixes 2019-09-03 22:55:56 -07:00
Logan Darklock
755a3f0154 Fix #sel selectors 2019-09-03 21:58:20 -07:00
Logan Darklock
b51dccc737 DON'T THROW EXCEPTIONS IN SCHEMATICS AA 2019-09-03 21:57:20 -07:00
Logan Darklock
620fc9af64 Sliiightly more efficient AbstractSchematic#approxPlaceable() 2019-09-03 21:44:45 -07:00
Logan Darklock
991283182c Fix some bugs with schematics 2019-09-03 08:35:16 -07:00
Logan Darklock
1413bd2f05 LOL CONTACT 2019-09-03 06:27:36 -07:00
Logan Darklock
faa8c727c3 correct sel help 2019-09-03 06:14:22 -07:00
Logan Darklock
65d2bdaf2b Selection shifting and such 2019-09-03 06:09:02 -07:00
Leijurv
17ca9ec43d Update USAGE.md 2019-09-02 23:13:14 -07:00
Logan Darklock
289971557a Fix bug with a few old commands that causes pagination to not work 2019-09-02 19:50:14 -07:00
Logan Darklock
d1a0b735d9 First working version of WorldEdit-like commands(!!!) 2019-09-02 16:18:07 -07:00
Logan Darklock
bc0f2b59da First version of selection stuff; nothing supports it yet 2019-09-02 11:29:48 -07:00
Logan Darklock
98bb3fba9c Pass current blockstate to schematics 2019-09-02 03:00:21 -07:00
Logan Darklock
b405a610bb ground work for more build commands 2019-09-01 15:53:13 -07:00
Leijurv
3e3df0b493 Merge pull request #894 from LoganDark/prefer-silk-touch
Setting to prefer silk touch, fixes #883
2019-09-01 15:33:14 -07:00
Logan Darklock
c1749057d9 Merge branch 'prefer-silk-touch' into commands 2019-09-01 15:19:17 -07:00
Logan Darklock
150f7a9fd9 extra parenthesis 2019-09-01 15:18:59 -07:00
Logan Darklock
6411fd80aa Merge prefer-silk-touch 2019-09-01 15:02:09 -07:00
Logan Darklock
0b953a237d Fix logic error 2019-09-01 15:01:02 -07:00
Logan Darklock
48f6d338a6 Merge upstream master 2019-09-01 14:48:42 -07:00
Logan Darklock
afc575d080 Setting to prefer silk touch, fixes #883 2019-09-01 14:47:01 -07:00
Logan Darklock
384b9b4704 Prefer silk touch setting 2019-09-01 14:45:31 -07:00
Logan Darklock
ce329d7fb3 Waypoints command 2019-09-01 14:18:59 -07:00
Logan Darklock
287615b0a1 Merge branch 'master' of https://github.com/cabaletta/baritone into commands 2019-09-01 13:22:03 -07:00
Logan Darklock
b96692f2d9 Save settings... 2019-09-01 13:12:06 -07:00
Leijurv
1b8aea2e6d Merge pull request #890 from LoganDark/censoring
Coordinate censoring
2019-09-01 10:30:24 -07:00
Logan Darklock
97ce377b9c Merge branch 'censoring' into commands 2019-09-01 10:16:14 -07:00
Logan Darklock
f1973b14c7 Remove MixinBlockPos since we now only log BetterBlockPos 2019-09-01 10:15:41 -07:00
Logan Darklock
73bd2cdcc3 Merge branch 'censoring' into commands 2019-09-01 10:09:12 -07:00
Logan Darklock
9038310150 Rename SettingsUtil.possiblyCensorCoordinate to maybeCensor 2019-09-01 10:06:50 -07:00
Logan Darklock
07fb09b4cc Merge branch 'censoring' into commands 2019-09-01 10:01:46 -07:00
Logan Darklock
ef38051826 Coordinate censoring 2019-09-01 09:50:47 -07:00
Logan Darklock
445037b614 Coordinate censoring 2019-09-01 09:47:27 -07:00
Logan Darklock
44ec969203 yeah 2019-09-01 00:17:42 -07:00
Logan Darklock
444cde1ee9 Improve blockstate filter in BlockOptionalMeta 2019-08-31 23:08:51 -07:00
Logan Darklock
cf12cbbcf4 Don't care about meta in bom if we have none 2019-08-31 20:58:22 -07:00
Logan Darklock
bb2f4da6b6 Fix baritoneHash calculation 2019-08-31 20:53:58 -07:00
Logan Darklock
4bca6cc1a5 Scan ItemStacks correctly 2019-08-31 20:43:03 -07:00
Logan Darklock
544ae24b64 YES I DID IT 2019-08-31 19:08:43 -07:00
Logan Darklock
8fc80a285c Waypoint hashcode + removed one unused line from followcommand 2019-08-31 18:52:24 -07:00
Logan Darklock
6ed86cb3c7 Hopefully speed up BlockOptionalMeta 2019-08-31 10:28:01 -07:00
Logan Darklock
84f45ebb48 Fix file tab completion in production environments 2019-08-31 07:55:24 -07:00
Logan Darklock
90fb17b89f Told Proguard not to touch things it doesn't understand 2019-08-31 07:36:23 -07:00
Logan Darklock
d54e846f91 Proguard likes to fuck up my command framework in the build. This error makes it more clear when that happens 2019-08-31 07:16:02 -07:00
Logan Darklock
ee71819bb2 remove unnecessary import 2019-08-31 06:42:16 -07:00
Logan Darklock
2ee313a795 Don't break Forge world loading 2019-08-31 06:38:36 -07:00
Logan Darklock
b924e8511b fix imports 2019-08-31 02:14:38 -07:00
Logan Darklock
15e9d756b7 Remove unused toArrayBad function... 2019-08-31 01:59:45 -07:00
Logan Darklock
8be879465a Merge branch 'master' of https://github.com/cabaletta/baritone into commands 2019-08-31 01:05:24 -07:00
Logan Darklock
5e0b333cfd fix comment & make final int final 2019-08-31 01:04:22 -07:00
Logan Darklock
efa243386c Make scanChunkInto even faster 2019-08-31 01:00:37 -07:00
Logan Darklock
ae6ee5688c add toArray, scanChunkInto usage coming soon 2019-08-31 00:51:42 -07:00
Logan Darklock
9f3eaac3df increase efficiency of scanChunkInto by ~25% 2019-08-30 22:52:20 -07:00
Logan Darklock
c938983ff5 thisway command + fixed fromDirection for you + fixed double/float argparsers 2019-08-30 22:27:30 -07:00
Logan Darklock
172ce3a054 click 2019-08-30 18:00:34 -07:00
Logan Darklock
69ca48287e prune before checking size 2019-08-30 17:20:20 -07:00
Logan Darklock
a6726f4e96 extend cache on threshold 2019-08-30 17:19:44 -07:00
Logan Darklock
b6c91b5062 speed up cache stuff 2019-08-30 17:13:09 -07:00
Logan Darklock
fe47245b73 Fix searchWorld cache and also speed and stuff 2019-08-30 17:12:05 -07:00
Logan Darklock
d687e1203a BlockOptionalMeta 2019-08-30 15:38:15 -07:00
Leijurv
0280fcb2da Merge pull request #879 from Orinion/fix-waypoint-bug
Check if waypoint name is Tag
2019-08-30 13:39:55 -07:00
Logan Darklock
4354d09c20 some efficiency fixes to filters + qol for leijurv 2019-08-30 12:25:59 -07:00
Logan Darklock
e3c4d06b2b Initial commit of commands 2019-08-30 11:55:25 -07:00
Orinion
6327c8492f fix codestyle 2019-08-30 11:54:04 +02:00
Leijurv
e7412d0d46 Merge pull request #867 from Orinion/master
Add replantCrops setting
2019-08-29 17:46:41 -07:00
Orinion
6a181abdcb Check if waypoint name is Tag
before, saving a waypint with a tag name would not result in an error, but you would not be able to run "goto" on it. see #869
2019-08-30 02:43:59 +02:00
Orinion
65a9b1a78a Make replantCrops override replantNetherWart
When replantCrops is false, baritone will not replant nether wart.
Also fixed spacing.
2019-08-29 10:36:31 +02:00
Leijurv
5ce644718e Merge pull request #871 from babbaj/cla$$
Replace klass with cla$$
2019-08-28 17:51:50 -07:00
Babbaj
a7add6bc13 Replace klass with cla$$ 2019-08-28 20:37:05 -04:00
Orinion
d2a046c8b4 Add replantCrops setting
add replantCrops setting, simmilar to replantNetherWart for the other crops.
2019-08-28 20:15:41 +02:00
Leijurv
33080a4e1c v1.2.9 2019-08-23 15:23:54 -07:00
Leijurv
dae6cc8e20 maintain current behavior 2019-08-23 15:23:36 -07:00
Leijurv
a2159d62e5 quite annoying 2019-08-23 15:23:00 -07:00
Leijurv
a092a0ba94 update badges 2019-08-23 15:22:59 -07:00
Leijurv
33faf5c9b0 Merge pull request #835 from IronException/master
added things to avoid
2019-08-23 15:22:42 -07:00
IronException
d927207b67 added things to avoid
Signs should also be avoided. A lot of history can get lost
2019-08-22 17:44:27 +02:00
Leijurv
a9ba05bf5e Merge branch 'master' into 1.13.2 2019-08-20 14:28:59 -07:00
Leijurv
b9f0da7d27 major unscuff of builder 2019-08-20 11:23:23 -07:00
Leijurv
1c36bf3300 repack on mine cmd 2019-08-17 22:01:53 -07:00
Leijurv
cca137d526 Merge pull request #808 from reb0rt/patch-2
Stop parseGoal from removing the last argument (when it shouldn't)
2019-08-17 21:13:59 -07:00
reb0rt
24da012903 Stop parseGoal from removing the last argument
isNumeric returns false if the input is anything other than a positive integer. This meant that baritone wouldn't properly set goals if they ended in anything other than a positive integer.
2019-08-18 13:04:39 +10:00
Leijurv
7c9b812a5b Merge branch 'master' into 1.13.2 2019-08-17 16:07:26 -07:00
Leijurv
0eb7a5aed6 Merge pull request #805 from Graicc/master
Added amount of block mining to documentation
2019-08-17 09:37:03 -07:00
Graicc
5cbf1eef5f Grammer fix 2019-08-17 12:02:26 -04:00
Graicc
ed4fba330d Added mining certain amount of blocks to USAGE.md 2019-08-17 11:59:30 -04:00
Leijurv
9046eb500b crucial performance optimization 2019-08-16 21:16:41 -07:00
Leijurv
011b7427e2 fine lmao 2019-08-15 23:03:16 -07:00
Leijurv
13caaf6fa7 ok fine optifine 2019-08-15 19:27:46 -07:00
Brady
a98677dbda crucial performance optimization 2019-08-15 03:19:19 -05:00
Leijurv
6c1f0d3711 Merge pull request #764 from Scribblefoxx/master
Just a little fix, you know was coding away and thought, "hey! here is something cool!"
2019-08-10 08:20:50 -10:00
Scribblefoxx
e1e6a08eb2 Update Settings.java 2019-08-11 03:39:29 +10:00
Leijurv
7b21b0401d Merge pull request #712 from IronException/master
dimensional coords extension
2019-08-08 21:47:28 -10:00
Leijurv
4c935fc447 epicer cached bedrock level pathing 2019-08-08 18:09:25 -10:00
Leijurv
3d221dcda4 antiquated and does more harm than good 2019-08-08 18:04:49 -10:00
Friedolin2000
ac6c413fb8 dimensional coords extension 2019-08-08 22:45:18 +02:00
Leijurv
17a07ba85e better render 2019-08-08 09:56:06 -10:00
Leijurv
ca6f7003a5 Merge pull request #752 from cabaletta/raytrace-shaders
Disable lighting on path renderer
2019-08-08 09:55:16 -10:00
Howard Stark
d402ba61cc Disable lighting on path render 2019-08-08 09:36:55 -10:00
Leijurv
081fae98c4 1 year later 2019-08-01 23:47:32 -07:00
Leijurv
014d3b3a99 goal can never be null 2019-08-01 23:47:12 -07:00
Leijurv
19fe29ad1e i am stupid 2019-07-31 22:17:44 -07:00
Leijurv
8bcbd0231e bye 2019-07-31 21:45:57 -07:00
Leijurv
01c0e321b5 what was i THINKING 2019-07-31 20:58:45 -07:00
Leijurv
5f721b544e smh conner, imagine getting the same block position 2x without caching 2019-07-31 20:47:46 -07:00
Leijurv
57d4a79496 Merge pull request #701 from c0nn3r/master
Add parkour ascend
2019-07-30 21:55:37 -07:00
Conner
9541a45451 Resolve comments 2019-07-30 21:37:50 -07:00
Conner
bba4c09195 Add parkour ascend 2019-07-30 21:07:26 -07:00
Leijurv
06c62029c5 not iffy 2019-07-30 20:04:50 -07:00
Leijurv
6f251b64f1 i am very stupid 2019-07-29 17:35:06 -07:00
Leijurv
551b6b88d2 EXTREMELY old comment that is no longer true 2019-07-28 00:19:14 -07:00
Leijurv
07cbc47fb2 extra line 2019-07-27 23:51:23 -07:00
Leijurv
fe6ca97f21 whoops 2019-07-26 15:14:35 -07:00
Leijurv
1b481c6765 aristois badge 2019-07-26 15:14:04 -07:00
Leijurv
1c5e0b4d68 bump impact badge 2019-07-25 23:02:44 -07:00
Leijurv
a8226ba4c8 v1.3.4 2019-07-24 15:43:37 -07:00
Leijurv
bc849daccb v1.2.8 2019-07-24 15:38:14 -07:00
Leijurv
e34b2d1392 Merge branch 'master' into 1.13.2 2019-07-24 15:36:20 -07:00
Leijurv
f5b4de023f update usage stuff 2019-07-24 15:33:39 -07:00
Leijurv
6dc7a7788e install for 1.14.4 2019-07-23 22:30:04 -07:00
Leijurv
de6e96b952 Merge branch 'master' into 1.13.2 2019-07-23 11:58:45 -07:00
Leijurv
0e51a73149 instanceof BlockLiquid checks this 2019-07-23 11:53:21 -07:00
Leijurv
44a092cd94 Merge pull request #622 from babbaj/schematica
fix crash
2019-07-22 23:57:54 -07:00
Babbaj
7000b6cda2 fix crash 2019-07-23 02:56:24 -04:00
Leijurv
7a17f7d253 Merge pull request #607 from babbaj/schematica
build the schematic schematica has open
2019-07-22 23:53:09 -07:00
Babbaj
821e73c1d3 fix usage.md 2019-07-23 02:48:40 -04:00
Babbaj
784bc52d6d add to usage.md 2019-07-23 02:46:53 -04:00
Leijurv
4338e34734 while this is cool, nothing will ever conceivably use it 2019-07-22 23:37:43 -07:00
Babbaj
61147536e5 ok 2019-07-22 16:51:09 -04:00
Leijurv
6b9737eb3f fix double jump on paused overshot sprint ascend 2019-07-21 22:04:15 -07:00
Babbaj
fe54372a53 resolve the issue 2019-07-21 22:33:22 -04:00
Babbaj
21e9c0b7c1 add get functions 2019-07-21 22:17:21 -04:00
Babbaj
8bf977060e dont need the fields 2019-07-21 22:06:36 -04:00
Babbaj
074ec333cf clean up a bit 2019-07-21 21:57:59 -04:00
Babbaj
d505ec4f9f build the schematic schematica has open 2019-07-21 21:05:43 -04:00
Leijurv
9dd6856872 get called out 2019-07-21 14:36:02 -07:00
Leijurv
4d127acb9a reformat 2019-07-20 23:47:51 -07:00
Leijurv
ed4753e968 now that impact locks to specific baritone versions this hack can finally be removed yay 2019-07-19 22:33:08 -07:00
Leijurv
df900c9e64 use origin 2019-07-19 18:55:32 -07:00
Leijurv
93a090c56e Merge pull request #588 from StijnSimons/master
I forgot players and items were entities too
2019-07-19 17:06:48 -07:00
StijnSimons
8b43d93259 i forgot players and items were entities too 2019-07-20 01:37:43 +02:00
Leijurv
053662d0af Merge pull request #554 from StijnSimons/master
FollowEntity and FollowEntities
2019-07-19 16:31:04 -07:00
Brady
af943a8253 Fix issue opening fence gates in some scenarios
If there are 2 fence gates at the player height, and they are approached
diagonally, there is a slight chance that Baritone will be caught in an
infinite loop of opening and closing the upper fence gate, being unable
to interact with the bottom one.
2019-07-18 21:18:02 -05:00
Leijurv
8151444671 privatize this too 2019-07-18 14:15:53 -07:00
Leijurv
f32147d9d5 privatize 2019-07-17 22:41:09 -07:00
Leijurv
515e0364f7 Merge pull request #564 from ZakME/patch-1
PICKUP_DROPPED - Remove 2nd Items.WHEAT
2019-07-16 23:01:09 -07:00
ZakME
09239f8180 PICKUP_DROPPED - Remove 2nd Items.WHEAT
PICKUP_DROPPED:
Remove 2nd Items.WHEAT
Re-order a few items for neatness
2019-07-16 23:50:03 -06:00
Brady
0d9f233e33 Add question template 2019-07-15 18:00:51 -05:00
Brady
e034437c63 Separate templates 2019-07-15 17:55:15 -05:00
Leijurv
72be046f34 Update ISSUE_TEMPLATE.md 2019-07-15 15:26:58 -07:00
StijnSimons
3ba8824eb0 More copy paste 2019-07-15 22:34:52 +02:00
StijnSimons
b51a261bd1 Added entityfollow
Hey look i can cntrl + c v
2019-07-15 22:31:55 +02:00
Leijurv
38602dd141 verify top side of block, fixes #541 2019-07-14 11:13:51 -07:00
Leijurv
cdbec60da0 Merge pull request #531 from StijnSimons/master
Added Spider, PigZombie and Enderman conditions
2019-07-13 09:15:53 -07:00
StijnSimons
2b41012c5b Enderman angry condition 2019-07-13 17:17:10 +02:00
Leijurv
6bb87d0a64 address an absolutely critical gap in documentation 2019-07-12 23:27:02 -07:00
Baddeveloper
b16f9edd2c Added EntitySpider and EntityPigZombie conditions 2019-07-12 19:12:00 +02:00
Leijurv
ce4b1e09ed fix parkour and multithread farm 2019-07-11 14:39:10 -07:00
Leijurv
1a4635df16 v1.3.3 2019-07-11 12:47:44 -07:00
Leijurv
1390af20b6 fix parkour and multithread farm 2019-07-11 12:46:24 -07:00
Leijurv
1427cf57a8 randomlooking 2019-07-11 11:56:44 -07:00
Leijurv
d70243b4c0 leijurv would never do this 2019-07-11 11:08:45 -07:00
Leijurv
8f63dd4ba6 Merge branch 'master' into 1.13.2 2019-07-11 10:51:29 -07:00
Leijurv
01658286af detect allowbreak false 2019-07-11 10:41:24 -07:00
Leijurv
aa90c8b7cd address encapsulation conccerns 2019-07-10 22:18:11 -07:00
Leijurv
eba1011fd6 remove scuff 2019-07-09 23:47:42 -07:00
Brady
96a424c25a Merge pull request #445 from SylveonBottle/patch-1
Speed up production
2019-07-09 14:23:37 -05:00
Leijurv
f4dd100345 fix indexof 2019-07-08 23:16:26 -07:00
Brady
c7e1c917c3 Fix Baritone thinking it can walk through wall-placed skulls
Fixes #485
2019-07-08 19:21:09 -05:00
SylveonBottle
4ff61f96df wow times infinity 2019-06-21 03:59:10 -05:00
Leijurv
125facfbb6 Merge branch 'master' into 1.13.2 2019-06-10 11:50:14 -07:00
Leijurv
16b74ff53c v1.3.2 2019-05-16 14:57:26 -07:00
Leijurv
9297e98ac3 Merge branch 'master' into 1.13.2 2019-05-16 14:55:37 -07:00
Leijurv
b521d7bee1 fix dummy merge typo 2019-05-02 11:42:49 -07:00
Leijurv
4e96c5e5ee Merge branch 'master' into 1.13.2 2019-05-01 23:12:19 -07:00
Leijurv
ec819220b7 Merge branch 'master' into 1.13.2 2019-05-01 12:15:31 -07:00
Brady
3d3a5f420e Fix unsafe creation of potentially invalid ResourceLocation 2019-04-16 20:15:51 -05:00
Leijurv
9c9c9d4387 fix region pruning 2019-04-14 10:06:37 -07:00
Leijurv
82d09a536d v1.3.1 2019-04-13 19:21:44 -07:00
Leijurv
6e49adea33 i WUV impact 2019-04-13 19:10:13 -07:00
Leijurv
f85afdbc70 Merge branch 'master' into 1.13.2 2019-04-12 21:57:01 -07:00
Leijurv
563028a5b3 fix invalid player move packet, and a bunch of things in world scanner 2019-04-09 19:30:48 -07:00
Leijurv
d5c317b88b Merge branch 'master' into 1.13.2 2019-04-09 18:17:53 -07:00
Leijurv
c59ec9da10 blank space 2019-03-23 22:17:40 -08:00
Leijurv
3a675836da Merge pull request #370 from babbaj/patch-1
use runAutoTest
2019-03-23 13:03:19 -07:00
babbaj
7e0fc81246 use runAutoTest 2019-03-23 15:55:16 -04:00
Leijurv
f970f932c7 great 2019-03-23 10:52:03 -07:00
Leijurv
52d2741f52 and lets try making it fail delibrately 2019-03-23 10:31:36 -07:00
Leijurv
7bc6765cac rart 2019-03-23 10:13:14 -07:00
Leijurv
85b2aea6e9 where is this writing??? 2019-03-23 09:52:49 -07:00
Leijurv
c6ba5481d9 one final attempt 2019-03-22 22:33:40 -07:00
Leijurv
81f47d5632 forgot file name lollll 2019-03-22 22:19:13 -07:00
Leijurv
9b1440ed2c that needs to be allowed 2019-03-22 22:07:12 -07:00
Leijurv
2a8dcee028 write to a file to indicate success 2019-03-22 22:05:27 -07:00
Leijurv
277ba3643c Merge branch 'master' into 1.13.2 2019-03-22 21:24:43 -07:00
Leijurv
e5fbaf60f3 shutdownminecraftapplet 2019-03-22 21:04:35 -07:00
Leijurv
0deb854e1b v1.3.0 2019-03-21 16:40:18 -07:00
Leijurv
8268e3ec1b Merge branch 'master' into 1.13.2 2019-03-21 15:51:36 -07:00
Leijurv
af91da6a28 Merge branch 'master' into 1.13.2 2019-03-19 18:12:26 -07:00
Leijurv
9a15a65ad5 not needed anymore 2019-03-19 13:59:56 -07:00
Leijurv
0cbe9f81c8 Merge branch 'master' into 1.13.2 2019-03-15 16:58:23 -07:00
Leijurv
42afd2dd54 maybe proper exit code 2019-03-15 16:49:36 -07:00
Leijurv
315929f31c hey so what if we didnt do that 2019-03-15 16:39:59 -07:00
Leijurv
358aa80280 docker time 2019-03-15 16:22:51 -07:00
Leijurv
1dd9e11994 documentation resigned 2019-03-15 16:19:07 -07:00
Leijurv
5a8f02c944 unscuff everything 2019-03-15 16:11:14 -07:00
Leijurv
f248a5b677 make runClient work 2019-03-15 15:32:51 -07:00
Leijurv
e4a49c5529 fix launchtesting not found on runClient 2019-03-15 14:00:11 -07:00
Leijurv
449b44ba50 line 2019-03-14 16:32:14 -07:00
Leijurv
a00eec402e i love retina wtf 2019-03-14 16:32:04 -07:00
Leijurv
717779f742 air is stupid 2019-03-14 16:06:32 -07:00
Leijurv
6f843bd24d Merge branch 'master' into 1.13.2 2019-03-13 20:09:08 -07:00
Leijurv
d79fbea433 scuffed air 2019-03-13 18:08:15 -07:00
Leijurv
4d22c10ddb unscuff water, thanks wwe 2019-03-12 23:08:06 -07:00
Leijurv
1ea92a6092 😎 2019-03-12 22:49:23 -07:00
Leijurv
66eba84d06 consistent spacing 2019-03-12 18:54:36 -07:00
Leijurv
92e39b5d1d its over its done 2019-03-12 18:45:54 -07:00
Leijurv
0ddc47f473 i am rarted 2019-03-12 18:21:29 -07:00
Leijurv
ddfeca6947 unproject click cursed 2019-03-12 18:00:30 -07:00
Leijurv
6bd2e90cfd crash when pathing near shulker boxes 2019-03-12 17:18:58 -07:00
Leijurv
82505ddb01 online mode via env 2019-03-12 17:18:52 -07:00
Leijurv
2790d1d308 Merge branch 'master' into 1.13.2 2019-03-12 16:19:06 -07:00
Leijurv
11e503a022 many fixes 2019-03-12 16:17:43 -07:00
Leijurv
6fe49380ba pwned 2019-03-12 15:42:25 -07:00
Leijurv
1f2e267e3d fix a bunch of scuff 2019-03-12 15:41:58 -07:00
Leijurv
4cf6783622 fix the tests 2019-03-12 09:38:05 -07:00
Brady
82d77a7bac Update MixinGradle to 0.6.2
Includes fix ensuring that the SRGs are generated prior to Mixin annotation processing
2019-03-12 01:43:03 -05:00
Brady
841a927033 Merge remote-tracking branch 'origin/master' into 1.13.2 2019-03-12 01:09:11 -05:00
Brady
5a16561954 Working 1.13.2 development environment
Including a couple bugfixes to bad 1.13.2 code!!!
2019-03-12 01:05:39 -05:00
Brady
e2cc51908b Notch builds 2019-03-08 23:18:00 -06:00
Brady
1390e04435 Add versions in parenthesis for todos to fix stuff 2019-03-08 15:14:52 -06:00
Brady
84d961cbab Fix usages of Setting#get() 2019-03-08 15:12:55 -06:00
Brady
87b9d3915c Fix compiler errors
unproject needs to be resolved
2019-03-08 15:03:58 -06:00
Brady
c38d17563d Resolve merge conflicts
oh my god I should've updated my local branch before doing this
2019-03-08 14:44:49 -06:00
Brady
0c2af85ac0 Update to 1.13.2
Still need to setup method of launching, and Mixin support for ModLauncher
2019-03-08 14:30:43 -06:00
252 changed files with 12389 additions and 2366 deletions

View File

@@ -1 +0,0 @@
<!-- No UwU's or OwO's allowed -->

25
.github/ISSUE_TEMPLATE/bug.md vendored Normal file
View File

@@ -0,0 +1,25 @@
---
name: Bug report
about: Please file a separate report for each issue
title: Please add a brief but descriptive title
labels: bug
assignees: ''
---
## Some information
Operating system:
Java version:
Minecraft version:
Baritone version:
Forge mods (if used):
## Exception, error or logs
You can find your logs in `%appdata%/.minecraft/logs/` (Windows) or `/Library/Application\ Support/minecraft/logs` (Mac).
## How to reproduce
Add your steps to reproduce the issue/bug experienced here.
## Final checklist
- [ ] I have included the version of Minecraft I'm running, baritone's version and forge mods (if used).
- [ ] I have included logs, exceptions and / or steps to reproduce the issue.
- [ ] I have not used any OwO's or UwU's in this issue.

13
.github/ISSUE_TEMPLATE/question.md vendored Normal file
View File

@@ -0,0 +1,13 @@
---
name: Question
about: Please file a separate report for each question
title: Please add a brief but descriptive title
labels: question
assignees: ''
---
## What do you need help with?
With as much detail as possible, describe your question and what you may need help with.
## Final checklist
- [ ] I have not used any OwO's or UwU's in this issue.

19
.github/ISSUE_TEMPLATE/suggestion.md vendored Normal file
View File

@@ -0,0 +1,19 @@
---
name: Suggestion
about: Please file a separate report for each suggestion
title: Please add a brief but descriptive title
labels: enhancement
assignees: ''
---
## Describe your suggestion
With as much detail as possible, describe what your suggestion would do for Baritone.
## Settings
If applicable, what settings/customizability should be offered to tweak the functionality of your suggestion.
## Context
Describe how your suggestion would improve Baritone, or the reason behind it being added.
## Final checklist
- [ ] I have not used any OwO's or UwU's in this issue.

4
.gitignore vendored
View File

@@ -11,9 +11,13 @@ build/
classes/
*.class
/out
# IntelliJ Files
.idea/
*.iml
*.ipr
*.iws
/logs/
# Copyright Files

View File

@@ -10,7 +10,7 @@ install:
script:
- docker run --rm cabaletta/baritone ./gradlew javadoc
- docker run --name baritone cabaletta/baritone /bin/sh -c "set -e; /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -screen 0 128x128x24 -ac +extension GLX +render; DISPLAY=:99 BARITONE_AUTO_TEST=true ./gradlew runClient"
- docker run --name baritone cabaletta/baritone /bin/sh -c "/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -screen 0 128x128x24 -ac +extension GLX +render; DISPLAY=:99 BARITONE_AUTO_TEST=true ./gradlew runAutoTest; cat /code/autotest/success"
- docker cp baritone:/code/dist dist
- ls dist
- cat dist/checksums.txt

View File

@@ -14,10 +14,10 @@ appearance, race, religion, or sexual identity and orientation.
Examples of behavior that contributes to creating a positive environment
include:
* No Anime
* No Anime (including uwu's or owo's)
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Giving and gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
@@ -29,7 +29,7 @@ Examples of unacceptable behavior by participants include:
* ~~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
address, without explicit permission or consent
* Other conduct which could reasonably be considered inappropriate in a
professional setting

View File

@@ -1,15 +1,16 @@
# 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)
[![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%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)
[![GitHub All Releases](https://img.shields.io/github/downloads/cabaletta/baritone/total.svg)](https://github.com/cabaletta/baritone/releases)
[![Minecraft](https://img.shields.io/badge/MC-1.12.2-green.svg)](https://github.com/cabaletta/baritone/tree/master/)
[![HitCount](http://hits.dwyl.com/cabaletta/baritone.svg)](http://hits.dwyl.com/cabaletta/baritone/)
[![GitHub All Releases](https://img.shields.io/github/downloads/cabaletta/baritone/total.svg)](https://github.com/cabaletta/baritone/releases/)
[![Minecraft](https://img.shields.io/badge/MC-1.12.2-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/master/)
[![Minecraft](https://img.shields.io/badge/MC-1.13.2-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.13.2/)
[![Minecraft](https://img.shields.io/badge/MC-1.14.4-brightgreen.svg)](https://github.com/cabaletta/baritone/tree/1.14.4/)
[![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)
[![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/)
[![GitHub issues-closed](https://img.shields.io/github/issues-closed/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/issues?q=is%3Aissue+is%3Aclosed)
[![Pull Requests](https://img.shields.io/github/issues-pr/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/pulls/)
@@ -18,8 +19,9 @@
![Lines of Code](https://tokei.rs/b1/github/cabaletta/baritone?category=code)
[![GitHub contributors](https://img.shields.io/github/contributors/cabaletta/baritone.svg)](https://github.com/cabaletta/baritone/graphs/contributors/)
[![GitHub commits](https://img.shields.io/github/commits-since/cabaletta/baritone/v1.0.0.svg)](https://github.com/cabaletta/baritone/commit/)
[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.6%20/%20v1.3.2-brightgreen.svg)](https://impactdevelopment.github.io/)
[![Impact integration](https://img.shields.io/badge/Impact%20integration-v1.2.8%20/%20v1.3.4%20/%20v1.4.1-brightgreen.svg)](https://impactclient.net/)
[![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20%22integration%22-scuffed-yellow.svg)](https://github.com/fr1kin/ForgeHax/)
[![Aristois add-on integration](https://img.shields.io/badge/Aristois%20add--on%20integration-v1.3.4%20/%20v1.4.1-green.svg)](https://gitlab.com/emc-mods-indrit/baritone_api)
[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/)
[![Future integration](https://img.shields.io/badge/Future%20integration-Soon™%3F%3F%3F-red.svg)](https://futureclient.net/)
[![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](http://forthebadge.com/)
@@ -27,14 +29,16 @@
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.
Baritone is the pathfinding system used in [Impact](https://impactclient.net/) 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.
The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the forge jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it.
The easiest way to install Baritone is to install [Impact](https://impactclient.net/), which comes with Baritone. The second easiest way (for 1.12.2 only) is to install the v1.2.* forge api jar from [releases](https://github.com/cabaletta/baritone/releases). Otherwise, see [Installation & setup](SETUP.md). Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it.
For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1). Or [with optifine](https://github.com/cabaletta/baritone/issues/797).
This project is an updated version of [MineBot](https://github.com/leijurv/MineBot/),
the original version of the bot for Minecraft 1.8.9, rebuilt for 1.12.2 and 1.13.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 11 months =D 🦀
Have committed at least once a day from Aug 1 2018 to Aug 1 2019.
1Leijurv3DWTrGAfmmiTphjhXLvQiHg7K2
@@ -46,7 +50,7 @@ Here are some links to help to get started:
- [Installation & setup](SETUP.md)
- [API Javadocs](https://baritone.leijurv.com)
- [API Javadocs](https://baritone.leijurv.com/)
- [Settings](https://baritone.leijurv.com/baritone/api/Settings.html#field.detail)
@@ -75,7 +79,7 @@ That's what it's for, sure! (As long as usage is in compliance with the LGPL 3.0
## 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,6 +1,8 @@
# Installation
The easiest way to install Baritone is to install [Impact](https://impactdevelopment.github.io/), which comes with Baritone.
The easiest way to install Baritone is to install [Impact](https://impactclient.net/), which comes with Baritone.
For 1.14.4, [click here](https://www.dropbox.com/s/rkml3hjokd3qv0m/1.14.4-Baritone.zip?dl=1).
Once Baritone is installed, look [here](USAGE.md) for instructions on how to use it.
@@ -9,6 +11,8 @@ These releases are not always completely up to date with latest features, and ar
Link to the releases page: [Releases](https://github.com/cabaletta/baritone/releases)
v1.2.* is for 1.12.2, v1.3.* is for 1.13.2
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).
@@ -99,4 +103,4 @@ $ gradlew build
![Image](https://i.imgur.com/PE6r9iN.png)
- Double click on **build** to run it
- Double click on **build** to run it

View File

@@ -18,16 +18,18 @@ To toggle a boolean setting, just say its name in chat (for example saying `allo
Some common examples:
- `thisway 1000` then `path` to go in the direction you're facing for a thousand blocks
- `goal x y z` or `goal x z` or `goal y`, then `path` to go to a certain coordinate
- `goal x y z` or `goal x z` or `goal y`, then `path` to set a goal to a certain coordinate then path to it
- `goto x y z` or `goto x z` or `goto y` to go to a certain coordinate (in a single step, starts going immediately)
- `goal` to set the goal to your player's feet
- `goal clear` to clear the goal
- `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.)
- `mine diamond_ore iron_ore` to mine diamond ore or iron 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.) An amount of blocks can also be specified, for example, `mine diamond_ore 64`.
- `click` to click your destination on the screen. Right click path to on top of the block, left click to path into it (either at foot level or eye level), and left click and drag to clear all blocks from an area.
- `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).
- `follow playerName` to follow a player. `followplayers` to follow any players in range (combine with Kill Aura for a fun time). `followentities` to follow any entities. `followentity pig` to follow entities of a specific type.
- `save waypointName` to save a waypoint. `goto waypointName` to go to it.
- `build` to build a schematic. `build blah` will load `schematics/blah.schematic` and build it with the origin being your player feet. `build blah x y z` to set the origin. Any of those can be relative to your player (`~ 69 ~-420` would build at x=player x, y=69, z=player z-420).
- `schematica` to build the schematic that is currently open in schematica
- `tunnel` to dig just straight ahead and make a tunnel
- `farm` to automatically harvest, replant, or bone meal crops
- `axis` to go to an axis or diagonal axis at y=120 (`axisHeight` is a configurable setting, defaults to 120).
@@ -37,6 +39,11 @@ Some common examples:
- `damn` daniel
New commands:
- `sel` to manage selections
- some others
For the rest of the commands, you can take a look at the code [here](https://github.com/cabaletta/baritone/blob/master/src/api/java/baritone/api/utils/ExampleBaritoneControl.java).
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>.

View File

@@ -16,33 +16,33 @@
*/
group 'baritone'
version '1.2.7'
version '1.3.5'
buildscript {
repositories {
jcenter()
maven {
name = 'forge'
url = 'http://files.minecraftforge.net/maven'
}
maven {
name = 'SpongePowered'
url = 'http://repo.spongepowered.org/maven'
name = 'impactdevelopment-repo'
url = 'https://impactdevelopment.github.io/maven/'
}
jcenter()
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT'
classpath group: 'com.github.ImpactDevelopment', name: 'ForgeGradle', version: '3.0.115'
classpath group: 'com.github.ImpactDevelopment', name: 'MixinGradle', version: '0.6.2'
}
}
import baritone.gradle.task.CreateDistTask
import baritone.gradle.task.ProguardTask
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'java'
apply plugin: 'net.minecraftforge.gradle.tweaker-client'
apply plugin: 'net.minecraftforge.gradle'
apply plugin: 'org.spongepowered.mixin'
sourceCompatibility = targetCompatibility = '1.8'
@@ -52,19 +52,75 @@ compileJava {
}
sourceSets {
api {
compileClasspath += main.compileClasspath
}
main {
compileClasspath += api.output
}
test {
compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output
runtimeClasspath += main.compileClasspath + main.runtimeClasspath + main.output
}
launch {
compileClasspath += main.compileClasspath + main.runtimeClasspath + main.output
runtimeClasspath += main.compileClasspath + main.runtimeClasspath + main.output
}
schematica_api {
compileClasspath += main.compileClasspath
}
main {
compileClasspath += schematica_api.output
}
}
minecraft {
version = '1.12.2'
mappings = 'stable_39'
tweakClass = 'baritone.launch.BaritoneTweaker'
runDir = 'run'
task sourceJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.api.allSource
}
// The sources jar should use SRG names not MCP to ensure compatibility with all mappings
makeObfSourceJar = true
minecraft {
mappings channel: 'snapshot', version: '20190307-1.13.1'
reobfMappings 'notch'
runs {
client {
workingDirectory project.file('run')
source sourceSets.launch
main 'baritone.launch.LaunchTesting'
environment 'assetIndex', '{asset_index}'
environment 'assetDirectory', downloadAssets.output
environment 'nativesDirectory', extractNatives.output
environment 'tweakClass', 'baritone.launch.BaritoneTweaker'
if (Os.isFamily(Os.FAMILY_MAC)) {
jvmArgs "-XstartOnFirstThread"
}
}
autoTest {
workingDirectory project.file('autotest')
source sourceSets.launch
main 'baritone.launch.LaunchTesting'
environment 'assetIndex', '{asset_index}'
environment 'assetDirectory', downloadAssets.output
environment 'nativesDirectory', extractNatives.output
environment 'tweakClass', 'baritone.launch.BaritoneTweaker'
environment 'BARITONE_AUTO_TEST', 'true'
if (Os.isFamily(Os.FAMILY_MAC)) {
jvmArgs "-XstartOnFirstThread"
}
}
}
}
repositories {
@@ -82,6 +138,12 @@ repositories {
}
dependencies {
minecraft 'com.github.ImpactDevelopment:Vanilla:1.13.2'
runtime launchCompile('net.minecraft:launchwrapper:1.12') {
exclude module: 'lwjgl'
}
runtime launchCompile('org.ow2.asm:asm-debug-all:5.2')
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
@@ -91,6 +153,7 @@ dependencies {
exclude module: 'commons-io'
exclude module: 'log4j-core'
}
testImplementation 'junit:junit:4.12'
}

View File

@@ -40,17 +40,13 @@ class BaritoneGradleTask extends DefaultTask {
PROGUARD_STANDALONE_CONFIG = "standalone.pro",
PROGUARD_EXPORT_PATH = "proguard_out.jar",
TEMP_LIBRARY_DIR = "tempLibraries/",
ARTIFACT_STANDARD = "%s-%s.jar",
ARTIFACT_UNOPTIMIZED = "%s-unoptimized-%s.jar",
ARTIFACT_API = "%s-api-%s.jar",
ARTIFACT_STANDALONE = "%s-standalone-%s.jar",
ARTIFACT_FORGE_API = "%s-api-forge-%s.jar",
ARTIFACT_FORGE_STANDALONE = "%s-standalone-forge-%s.jar";
ARTIFACT_STANDALONE = "%s-standalone-%s.jar";
protected String artifactName, artifactVersion;
protected Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, artifactForgeApiPath, artifactForgeStandalonePath, proguardOut;
protected Path artifactPath, artifactUnoptimizedPath, artifactApiPath, artifactStandalonePath, proguardOut;
protected void verifyArtifacts() throws IllegalStateException {
this.artifactName = getProject().getName();
@@ -60,8 +56,6 @@ class BaritoneGradleTask extends DefaultTask {
this.artifactUnoptimizedPath = this.getBuildFile(formatVersion(ARTIFACT_UNOPTIMIZED));
this.artifactApiPath = this.getBuildFile(formatVersion(ARTIFACT_API));
this.artifactStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_STANDALONE));
this.artifactForgeApiPath = this.getBuildFile(formatVersion(ARTIFACT_FORGE_API));
this.artifactForgeStandalonePath = this.getBuildFile(formatVersion(ARTIFACT_FORGE_STANDALONE));
this.proguardOut = this.getTemporaryFile(PROGUARD_EXPORT_PATH);

View File

@@ -45,8 +45,6 @@ public class CreateDistTask extends BaritoneGradleTask {
Path api = getRelativeFile("dist/" + formatVersion(ARTIFACT_API));
Path standalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_STANDALONE));
Path unoptimized = getRelativeFile("dist/" + formatVersion(ARTIFACT_UNOPTIMIZED));
Path forgeApi = getRelativeFile("dist/" + formatVersion(ARTIFACT_FORGE_API));
Path forgeStandalone = getRelativeFile("dist/" + formatVersion(ARTIFACT_FORGE_STANDALONE));
// NIO will not automatically create directories
Path dir = getRelativeFile("dist/");
@@ -58,11 +56,9 @@ public class CreateDistTask extends BaritoneGradleTask {
Files.copy(this.artifactApiPath, api, REPLACE_EXISTING);
Files.copy(this.artifactStandalonePath, standalone, REPLACE_EXISTING);
Files.copy(this.artifactUnoptimizedPath, unoptimized, REPLACE_EXISTING);
Files.copy(this.artifactForgeApiPath, forgeApi, REPLACE_EXISTING);
Files.copy(this.artifactForgeStandalonePath, forgeStandalone, REPLACE_EXISTING);
// Calculate all checksums and format them like "shasum"
List<String> shasum = Stream.of(api, forgeApi, standalone, forgeStandalone, unoptimized)
List<String> shasum = Stream.of(api, standalone, unoptimized)
.map(path -> sha1(path) + " " + path.getFileName().toString())
.collect(Collectors.toList());

View File

@@ -18,26 +18,18 @@
package baritone.gradle.task;
import baritone.gradle.util.Determinizer;
import baritone.gradle.util.MappingType;
import baritone.gradle.util.ReobfWrapper;
import org.apache.commons.io.IOUtils;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.internal.plugins.DefaultConvention;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.TaskAction;
import org.gradle.internal.Pair;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@@ -49,18 +41,12 @@ import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
*/
public class ProguardTask extends BaritoneGradleTask {
private static final Pattern TEMP_LIBRARY_PATTERN = Pattern.compile("-libraryjars 'tempLibraries\\/([a-zA-Z0-9/_\\-\\.]+)\\.jar'");
@Input
private String url;
@Input
private String extract;
private List<String> requiredLibraries;
private File mixin;
@TaskAction
protected void exec() throws Exception {
super.verifyArtifacts();
@@ -70,7 +56,6 @@ public class ProguardTask extends BaritoneGradleTask {
downloadProguard();
extractProguard();
generateConfigs();
acquireDependencies();
proguardApi();
proguardStandalone();
cleanup();
@@ -81,7 +66,7 @@ public class ProguardTask extends BaritoneGradleTask {
Files.delete(this.artifactUnoptimizedPath);
}
Determinizer.determinize(this.artifactPath.toString(), this.artifactUnoptimizedPath.toString(), Optional.empty());
Determinizer.determinize(this.artifactPath.toString(), this.artifactUnoptimizedPath.toString());
}
private void downloadProguard() throws Exception {
@@ -114,6 +99,19 @@ public class ProguardTask extends BaritoneGradleTask {
String out = IOUtils.toString(p.getInputStream(), "UTF-8").split("\n")[0].split("Opened ")[1].replace("]", "");
template.add(2, "-libraryjars '" + out + "'");
// Discover all of the libraries that we will need to acquire from gradle
acquireDependencies().forEach(f -> {
if (f.toString().endsWith("-recomp.jar")) {
// remove MCP mapped jar
return;
}
if (f.toString().endsWith("client-extra.jar")) {
// go from the extra to the original downloaded client
f = new File(f.getParentFile(), "client.jar");
}
template.add(2, "-libraryjars '" + f + "'");
});
// API config doesn't require any changes from the changes that we made to the template
Files.write(getTemporaryFile(PROGUARD_API_CONFIG), template);
@@ -121,165 +119,20 @@ public class ProguardTask extends BaritoneGradleTask {
List<String> standalone = new ArrayList<>(template);
standalone.removeIf(s -> s.contains("# this is the keep api"));
Files.write(getTemporaryFile(PROGUARD_STANDALONE_CONFIG), standalone);
// Discover all of the libraries that we will need to acquire from gradle
this.requiredLibraries = new ArrayList<>();
template.forEach(line -> {
if (!line.startsWith("#")) {
Matcher m = TEMP_LIBRARY_PATTERN.matcher(line);
if (m.find()) {
this.requiredLibraries.add(m.group(1));
}
}
});
}
private void acquireDependencies() throws Exception {
// Create a map of all of the dependencies that we are able to access in this project
// Likely a better way to do this, I just pair the dependency with the first valid configuration
Map<String, Pair<Configuration, Dependency>> dependencyLookupMap = new HashMap<>();
getProject().getConfigurations().stream().filter(Configuration::isCanBeResolved).forEach(config ->
config.getAllDependencies().forEach(dependency ->
dependencyLookupMap.putIfAbsent(dependency.getName() + "-" + dependency.getVersion(), Pair.of(config, dependency))));
// Create the directory if it doesn't already exist
Path tempLibraries = getTemporaryFile(TEMP_LIBRARY_DIR);
if (!Files.exists(tempLibraries)) {
Files.createDirectory(tempLibraries);
}
// Iterate the required libraries to copy them to tempLibraries
for (String lib : this.requiredLibraries) {
// copy from the forgegradle cache
if (lib.equals("minecraft")) {
Path cachedJar = getMinecraftJar();
Path inTempDir = getTemporaryFile("tempLibraries/minecraft.jar");
// TODO: maybe try not to copy every time
Files.copy(cachedJar, inTempDir, REPLACE_EXISTING);
continue;
}
// Find a configuration/dependency pair that matches the desired library
Pair<Configuration, Dependency> pair = null;
for (Map.Entry<String, Pair<Configuration, Dependency>> entry : dependencyLookupMap.entrySet()) {
if (entry.getKey().startsWith(lib)) {
pair = entry.getValue();
}
}
// The pair must be non-null
Objects.requireNonNull(pair);
// Find the library jar file, and copy it to tempLibraries
for (File file : pair.getLeft().files(pair.getRight())) {
if (file.getName().startsWith(lib)) {
if (lib.contains("mixin")) {
mixin = file;
}
Files.copy(file.toPath(), getTemporaryFile("tempLibraries/" + lib + ".jar"), REPLACE_EXISTING);
}
}
}
if (mixin == null) {
throw new IllegalStateException("Unable to find mixin jar");
}
}
// a bunch of epic stuff to get the path to the cached jar
private Path getMinecraftJar() throws Exception {
MappingType mappingType;
try {
mappingType = getMappingType();
} catch (Exception e) {
System.err.println("Failed to get mapping type, assuming NOTCH.");
mappingType = MappingType.NOTCH;
}
String suffix;
switch (mappingType) {
case NOTCH:
suffix = "";
break;
case SEARGE:
suffix = "-srgBin";
break;
case CUSTOM:
throw new IllegalStateException("Custom mappings not supported!");
default:
throw new IllegalStateException("Unknown mapping type: " + mappingType);
}
DefaultConvention convention = (DefaultConvention) this.getProject().getConvention();
Object extension = convention.getAsMap().get("minecraft");
Objects.requireNonNull(extension);
// for some reason cant use Class.forName
Class<?> class_baseExtension = extension.getClass().getSuperclass().getSuperclass().getSuperclass(); // <-- cursed
Field f_replacer = class_baseExtension.getDeclaredField("replacer");
f_replacer.setAccessible(true);
Object replacer = f_replacer.get(extension);
Class<?> class_replacementProvider = replacer.getClass();
Field replacement_replaceMap = class_replacementProvider.getDeclaredField("replaceMap");
replacement_replaceMap.setAccessible(true);
Map<String, Object> replacements = (Map) replacement_replaceMap.get(replacer);
String cacheDir = replacements.get("CACHE_DIR").toString() + "/net/minecraft";
String mcVersion = replacements.get("MC_VERSION").toString();
String mcpInsert = replacements.get("MAPPING_CHANNEL").toString() + "/" + replacements.get("MAPPING_VERSION").toString();
String fullJarName = "minecraft-" + mcVersion + suffix + ".jar";
String baseDir = String.format("%s/minecraft/%s/", cacheDir, mcVersion);
String jarPath;
if (mappingType == MappingType.SEARGE) {
jarPath = String.format("%s/%s/%s", baseDir, mcpInsert, fullJarName);
} else {
jarPath = baseDir + fullJarName;
}
jarPath = jarPath
.replace("/", File.separator)
.replace("\\", File.separator); // hecking regex
return new File(jarPath).toPath();
}
// throws IllegalStateException if mapping type is ambiguous or it fails to find it
private MappingType getMappingType() {
// if it fails to find this then its probably a forgegradle version problem
Set<Object> reobf = (NamedDomainObjectContainer<Object>) this.getProject().getExtensions().getByName("reobf");
List<MappingType> mappingTypes = getUsedMappingTypes(reobf);
long mappingTypesUsed = mappingTypes.size();
if (mappingTypesUsed == 0) {
throw new IllegalStateException("Failed to find mapping type (no jar task?)");
}
if (mappingTypesUsed > 1) {
throw new IllegalStateException("Ambiguous mapping type (multiple jars with different mapping types?)");
}
return mappingTypes.get(0);
}
private List<MappingType> getUsedMappingTypes(Set<Object> reobf) {
return reobf.stream()
.map(ReobfWrapper::new)
.map(ReobfWrapper::getMappingType)
.distinct()
.collect(Collectors.toList());
private Stream<File> acquireDependencies() {
return getProject().getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().findByName("launch").getRuntimeClasspath().getFiles().stream().filter(File::isFile);
}
private void proguardApi() throws Exception {
runProguard(getTemporaryFile(PROGUARD_API_CONFIG));
Determinizer.determinize(this.proguardOut.toString(), this.artifactApiPath.toString(), Optional.empty());
Determinizer.determinize(this.proguardOut.toString(), this.artifactForgeApiPath.toString(), Optional.of(mixin));
Determinizer.determinize(this.proguardOut.toString(), this.artifactApiPath.toString());
}
private void proguardStandalone() throws Exception {
runProguard(getTemporaryFile(PROGUARD_STANDALONE_CONFIG));
Determinizer.determinize(this.proguardOut.toString(), this.artifactStandalonePath.toString(), Optional.empty());
Determinizer.determinize(this.proguardOut.toString(), this.artifactForgeStandalonePath.toString(), Optional.of(mixin));
Determinizer.determinize(this.proguardOut.toString(), this.artifactStandalonePath.toString());
}
private void cleanup() {

View File

@@ -22,7 +22,10 @@ import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.*;
import java.util.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
@@ -36,7 +39,7 @@ import java.util.stream.Collectors;
*/
public class Determinizer {
public static void determinize(String inputPath, String outputPath, Optional<File> toInclude) throws IOException {
public static void determinize(String inputPath, String outputPath) throws IOException {
System.out.println("Running Determinizer");
System.out.println(" Input path: " + inputPath);
System.out.println(" Output path: " + outputPath);
@@ -63,30 +66,10 @@ public class Determinizer {
if (entry.getName().endsWith(".refmap.json")) {
JsonObject object = new JsonParser().parse(new InputStreamReader(jarFile.getInputStream(entry))).getAsJsonObject();
jos.write(writeSorted(object).getBytes());
} else if (entry.getName().equals("META-INF/MANIFEST.MF") && toInclude.isPresent()) { // only replace for forge jar
ByteArrayOutputStream cancer = new ByteArrayOutputStream();
copy(jarFile.getInputStream(entry), cancer);
String manifest = new String(cancer.toByteArray());
if (!manifest.contains("baritone.launch.BaritoneTweaker")) {
throw new IllegalStateException("unable to replace");
}
manifest = manifest.replace("baritone.launch.BaritoneTweaker", "org.spongepowered.asm.launch.MixinTweaker");
jos.write(manifest.getBytes());
} else {
copy(jarFile.getInputStream(entry), jos);
}
}
if (toInclude.isPresent()) {
try (JarFile mixin = new JarFile(toInclude.get())) {
for (JarEntry entry : mixin.stream().sorted(Comparator.comparing(JarEntry::getName)).collect(Collectors.toList())) {
if (entry.getName().startsWith("META-INF") && !entry.getName().startsWith("META-INF/services")) {
continue;
}
jos.putNextEntry(entry);
copy(mixin.getInputStream(entry), jos);
}
}
}
jos.finish();
}
}

View File

@@ -1,63 +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.gradle.util;
import java.lang.reflect.Field;
import java.util.Objects;
/**
* All credits go to AsmLibGradle and its contributors.
*
* @see <a href="https://github.com/pozzed/AsmLibGradle/blob/8f917dbc3939eab7a3d9daf54d9d285fdf34f4b2/src/main/java/net/futureclient/asmlib/forgegradle/ReobfWrapper.java">Original Source</a>
*/
public class ReobfWrapper {
private final Object instance;
private final Class<?> type;
public ReobfWrapper(Object instance) {
this.instance = instance;
Objects.requireNonNull(instance);
this.type = instance.getClass();
}
public String getName() {
try {
Field nameField = type.getDeclaredField("name");
nameField.setAccessible(true);
return (String) nameField.get(this.instance);
} catch (ReflectiveOperationException ex) {
throw new IllegalStateException(ex);
}
}
public MappingType getMappingType() {
try {
Field enumField = type.getDeclaredField("mappingType");
enumField.setAccessible(true);
Enum<?> aEnum = (Enum<?>) enumField.get(this.instance);
MappingType mappingType = MappingType.values()[aEnum.ordinal()];
if (!aEnum.name().equals(mappingType.name())) {
throw new IllegalStateException("ForgeGradle ReobfMappingType is not equivalent to MappingType (version error?)");
}
return mappingType;
} catch (ReflectiveOperationException ex) {
throw new IllegalStateException(ex);
}
}
}

54
scripts/proguard.pro vendored
View File

@@ -14,6 +14,8 @@
# lwjgl is weird
-dontwarn org.lwjgl.**
# also lwjgl lol
-dontwarn module-info
-keep class baritone.api.** { *; } # this is the keep api
@@ -31,54 +33,10 @@
# need to keep mixin names
-keep class baritone.launch.** { *; }
# copy all necessary libraries into tempLibraries to build
# The correct jar will be copied from the forgegradle cache based on the mapping type being compiled with
-libraryjars 'tempLibraries/minecraft.jar'
-libraryjars 'tempLibraries/SimpleTweaker-1.2.jar'
-libraryjars 'tempLibraries/authlib-1.5.25.jar'
-libraryjars 'tempLibraries/codecjorbis-20101023.jar'
-libraryjars 'tempLibraries/codecwav-20101023.jar'
-libraryjars 'tempLibraries/commons-codec-1.10.jar'
-libraryjars 'tempLibraries/commons-compress-1.8.1.jar'
-libraryjars 'tempLibraries/commons-io-2.5.jar'
-libraryjars 'tempLibraries/commons-lang3-3.5.jar'
-libraryjars 'tempLibraries/commons-logging-1.1.3.jar'
-libraryjars 'tempLibraries/fastutil-7.1.0.jar'
-libraryjars 'tempLibraries/gson-2.8.0.jar'
-libraryjars 'tempLibraries/guava-21.0.jar'
-libraryjars 'tempLibraries/httpclient-4.3.3.jar'
-libraryjars 'tempLibraries/httpcore-4.3.2.jar'
-libraryjars 'tempLibraries/icu4j-core-mojang-51.2.jar'
-libraryjars 'tempLibraries/jinput-2.0.5.jar'
-libraryjars 'tempLibraries/jna-4.4.0.jar'
-libraryjars 'tempLibraries/jopt-simple-5.0.3.jar'
-libraryjars 'tempLibraries/jsr305-3.0.1.jar'
-libraryjars 'tempLibraries/jutils-1.0.0.jar'
-libraryjars 'tempLibraries/libraryjavasound-20101123.jar'
-libraryjars 'tempLibraries/librarylwjglopenal-20100824.jar'
-libraryjars 'tempLibraries/log4j-api-2.8.1.jar'
-libraryjars 'tempLibraries/log4j-core-2.8.1.jar'
# startsWith is used to check the library, and mac/linux differ in which version they use
# this is FINE
-libraryjars 'tempLibraries/lwjgl-.jar'
-libraryjars 'tempLibraries/lwjgl_util-.jar'
-libraryjars 'tempLibraries/netty-all-4.1.9.Final.jar'
-libraryjars 'tempLibraries/oshi-core-1.1.jar'
-libraryjars 'tempLibraries/patchy-1.1.jar'
-libraryjars 'tempLibraries/platform-3.4.0.jar'
-libraryjars 'tempLibraries/realms-1.10.22.jar'
-libraryjars 'tempLibraries/soundsystem-20120107.jar'
-libraryjars 'tempLibraries/text2speech-1.10.3.jar'
-libraryjars 'tempLibraries/mixin-0.7.11-SNAPSHOT.jar'
-libraryjars 'tempLibraries/launchwrapper-1.11.jar' # TODO why does only 1.11.jar exist?
#try to keep usage of schematica in separate classes
-keep class baritone.utils.schematic.schematica.**
#proguard doesnt like it when it cant find our fake schematica classes
-dontwarn baritone.utils.schematic.schematica.**
# Keep - Applications. Keep all application classes, along with their 'main'

View File

@@ -34,12 +34,12 @@ public final class BaritoneAPI {
private static final Settings settings;
static {
settings = new Settings();
SettingsUtil.readAndApply(settings);
ServiceLoader<IBaritoneProvider> baritoneLoader = ServiceLoader.load(IBaritoneProvider.class);
Iterator<IBaritoneProvider> instances = baritoneLoader.iterator();
provider = instances.next();
settings = new Settings();
SettingsUtil.readAndApply(settings);
}
public static IBaritoneProvider getProvider() {

View File

@@ -23,8 +23,10 @@ import baritone.api.cache.IWorldProvider;
import baritone.api.event.listener.IEventBus;
import baritone.api.pathing.calc.IPathingControlManager;
import baritone.api.process.*;
import baritone.api.selection.ISelectionManager;
import baritone.api.utils.IInputOverrideHandler;
import baritone.api.utils.IPlayerContext;
import baritone.api.command.manager.ICommandManager;
/**
* @author Brady
@@ -32,15 +34,6 @@ import baritone.api.utils.IPlayerContext;
*/
public interface IBaritone {
/**
* 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.
*/
void init();
/**
* @return The {@link IPathingBehavior} instance
* @see IPathingBehavior
@@ -128,5 +121,20 @@ public interface IBaritone {
*/
IEventBus getGameEventHandler();
/**
* @return The {@link ISelectionManager} instance
* @see ISelectionManager
*/
ISelectionManager getSelectionManager();
/**
* @return The {@link ICommandManager} instance
* @see ICommandManager
*/
ICommandManager getCommandManager();
/**
* Open click
*/
void openClick();
}

View File

@@ -18,12 +18,15 @@
package baritone.api;
import baritone.api.cache.IWorldScanner;
import baritone.api.command.ICommand;
import baritone.api.command.ICommandSystem;
import net.minecraft.client.entity.EntityPlayerSP;
import java.util.List;
import java.util.Objects;
/**
* Provides the present {@link IBaritone} instances
* Provides the present {@link IBaritone} instances, as well as non-baritone instance related APIs.
*
* @author leijurv
*/
@@ -57,7 +60,7 @@ public interface IBaritoneProvider {
*/
default IBaritone getBaritoneForPlayer(EntityPlayerSP player) {
for (IBaritone baritone : getAllBaritones()) {
if (player.equals(baritone.getPlayerContext().player())) {
if (Objects.equals(player, baritone.getPlayerContext().player())) {
return baritone;
}
}
@@ -71,4 +74,12 @@ public interface IBaritoneProvider {
* @return The {@link IWorldScanner} instance.
*/
IWorldScanner getWorldScanner();
/**
* Returns the {@link ICommandSystem} instance. This is not bound to a specific {@link IBaritone}
* instance because {@link ICommandSystem} itself controls global behavior for {@link ICommand}s.
*
* @return The {@link ICommandSystem} instance.
*/
ICommandSystem getCommandSystem();
}

View File

@@ -124,6 +124,13 @@ public final class Settings {
*/
public final Setting<Boolean> allowJumpAt256 = new Setting<>(false);
/**
* This should be monetized it's so good
* <p>
* Defaults to true, but only actually takes effect if allowParkour is also true
*/
public final Setting<Boolean> allowParkourAscend = new Setting<>(true);
/**
* Allow descending diagonally
* <p>
@@ -133,6 +140,13 @@ public final class Settings {
*/
public final Setting<Boolean> allowDiagonalDescend = new Setting<>(false);
/**
* Allow diagonal ascending
* <p>
* Actually pretty safe, much safer than diagonal descend tbh
*/
public final Setting<Boolean> allowDiagonalAscend = new Setting<>(false);
/**
* Allow mining the block directly beneath its feet
* <p>
@@ -144,10 +158,10 @@ public final class Settings {
* Blocks that Baritone is allowed to place (as throwaway, for sneak bridging, pillaring, etc.)
*/
public final Setting<List<Item>> acceptableThrowawayItems = new Setting<>(new ArrayList<>(Arrays.asList(
Item.getItemFromBlock(Blocks.DIRT),
Item.getItemFromBlock(Blocks.COBBLESTONE),
Item.getItemFromBlock(Blocks.NETHERRACK),
Item.getItemFromBlock(Blocks.STONE)
Blocks.DIRT.asItem(),
Blocks.COBBLESTONE.asItem(),
Blocks.NETHERRACK.asItem(),
Blocks.STONE.asItem()
)));
/**
@@ -163,9 +177,10 @@ public final class Settings {
public final Setting<List<Block>> blocksToAvoidBreaking = new Setting<>(new ArrayList<>(Arrays.asList( // TODO can this be a HashSet or ImmutableSet?
Blocks.CRAFTING_TABLE,
Blocks.FURNACE,
Blocks.LIT_FURNACE,
Blocks.CHEST,
Blocks.TRAPPED_CHEST
Blocks.TRAPPED_CHEST,
Blocks.SIGN,
Blocks.WALL_SIGN
)));
/**
@@ -179,7 +194,7 @@ public final class Settings {
* Enables some more advanced vine features. They're honestly just gimmicks and won't ever be needed in real
* pathing scenarios. And they can cause Baritone to get trapped indefinitely in a strange scenario.
* <p>
* Never turn this on lol
* Almost never turn this on lol
*/
public final Setting<Boolean> allowVines = new Setting<>(false);
@@ -232,6 +247,16 @@ public final class Settings {
*/
public final Setting<Integer> rightClickSpeed = new Setting<>(4);
/**
* How many degrees to randomize the yaw every tick. Set to 0 to disable
*/
public final Setting<Double> randomLooking113 = new Setting<>(2d);
/**
* How many degrees to randomize the pitch and yaw every tick. Set to 0 to disable
*/
public final Setting<Double> randomLooking = new Setting<>(0.01d);
/**
* This is the big A* setting.
* As long as your cost heuristic is an *underestimate*, it's guaranteed to find you the best path.
@@ -474,15 +499,20 @@ public final class Settings {
public final Setting<Boolean> chatControl = new Setting<>(true);
/**
* A second override over chatControl to force it on
* Some clients like Impact try to force chatControl to off, so here's a second setting to do it anyway
*/
public final Setting<Boolean> removePrefix = new Setting<>(false);
public final Setting<Boolean> chatControlAnyway = new Setting<>(false);
/**
* Render the path
*/
public final Setting<Boolean> renderPath = new Setting<>(true);
/**
* Render the path as a line instead of a frickin thingy
*/
public final Setting<Boolean> renderPathAsLine = new Setting<>(false);
/**
* Render the goal
*/
@@ -583,10 +613,41 @@ public final class Settings {
public final Setting<Float> cachedChunksOpacity = new Setting<>(0.5f);
/**
* Whether or not to use the "#" command prefix
* Whether or not to allow you to run Baritone commands with the prefix
*/
public final Setting<Boolean> prefixControl = new Setting<>(true);
/**
* The command prefix for chat control
*/
public final Setting<String> prefix = new Setting<>("#");
/**
* Use a short Baritone prefix [B] instead of [Baritone] when logging to chat
*/
public final Setting<Boolean> shortBaritonePrefix = new Setting<>(false);
/**
* Echo commands to chat when they are run
*/
public final Setting<Boolean> echoCommands = new Setting<>(true);
/**
* Censor coordinates in goals and block positions
*/
public final Setting<Boolean> censorCoordinates = new Setting<>(false);
/**
* Censor arguments to ran commands, to hide, for example, coordinates to #goal
*/
public final Setting<Boolean> censorRanCommands = new Setting<>(false);
/**
* Always prefer silk touch tools over regular tools. This will not sacrifice speed, but it will always prefer silk
* touch tools over other tools of the same speed. This includes always choosing ANY silk touch tool over your hand.
*/
public final Setting<Boolean> preferSilkTouch = new Setting<>(false);
/**
* Don't stop walking forward when you need to break blocks in your way
*/
@@ -648,7 +709,12 @@ public final class Settings {
public final Setting<Integer> exploreMaintainY = new Setting<>(64);
/**
* Replant nether wart while farming
* Replant normal Crops while farming and leave cactus and sugarcane to regrow
*/
public final Setting<Boolean> replantCrops = new Setting<>(true);
/**
* Replant nether wart while farming. This setting only has an effect when replantCrops is also enabled
*/
public final Setting<Boolean> replantNetherWart = new Setting<>(false);
@@ -690,11 +756,65 @@ public final class Settings {
*/
public final Setting<Boolean> goalBreakFromAbove = new Setting<>(false);
/**
* Build in map art mode, which makes baritone only care about the top block in each column
*/
public final Setting<Boolean> mapArtMode = new Setting<>(false);
/**
* Override builder's behavior to not attempt to correct blocks that are currently water
*/
public final Setting<Boolean> okIfWater = new Setting<>(false);
/**
* The set of incorrect blocks can never grow beyond this size
*/
public final Setting<Integer> incorrectSize = new Setting<>(100);
/**
* Multiply the cost of breaking a block that's correct in the builder's schematic by this coefficient
*/
public final Setting<Double> breakCorrectBlockPenaltyMultiplier = new Setting<>(10d);
/**
* When this setting is true, build a schematic with the highest X coordinate being the origin, instead of the lowest
*/
public final Setting<Boolean> schematicOrientationX = new Setting<>(false);
/**
* When this setting is true, build a schematic with the highest Y coordinate being the origin, instead of the lowest
*/
public final Setting<Boolean> schematicOrientationY = new Setting<>(false);
/**
* When this setting is true, build a schematic with the highest Z coordinate being the origin, instead of the lowest
*/
public final Setting<Boolean> schematicOrientationZ = new Setting<>(false);
/**
* Distance to scan every tick for updates. Expanding this beyond player reach distance (i.e. setting it to 6 or above)
* is only necessary in very large schematics where rescanning the whole thing is costly.
*/
public final Setting<Integer> builderTickScanRadius = new Setting<>(5);
/**
* While mining, should it also consider dropped items of the correct type as a pathing destination (as well as ore blocks)?
*/
public final Setting<Boolean> mineScanDroppedItems = new Setting<>(true);
/**
* While mining, wait this number of milliseconds after mining an ore to see if it will drop an item
* instead of immediately going onto the next one
* <p>
* Thanks Louca
*/
public final Setting<Long> mineDropLoiterDurationMSThanksLouca = new Setting<>(250L);
/**
* Trim incorrect positions too far away, helps performance but hurts reliability in very large schematics
*/
public final Setting<Boolean> distanceTrim = new Setting<>(true);
/**
* Cancel the current path if the goal has changed, and the path originally ended in the goal but doesn't anymore.
* <p>
@@ -808,7 +928,7 @@ public final class Settings {
* via {@link Consumer#andThen(Consumer)} or it can completely be overriden via setting
* {@link Setting#value};
*/
public final Setting<Consumer<ITextComponent>> logger = new Setting<>(Minecraft.getMinecraft().ingameGUI.getChatGUI()::printChatMessage);
public final Setting<Consumer<ITextComponent>> logger = new Setting<>(Minecraft.getInstance().ingameGUI.getChatGUI()::printChatMessage);
/**
* The size of the box that is rendered when the current goal is a GoalYLevel
@@ -855,6 +975,51 @@ public final class Settings {
*/
public final Setting<Color> colorGoalBox = new Setting<>(Color.GREEN);
/**
* The color of the goal box when it's inverted
*/
public final Setting<Color> colorInvertedGoalBox = new Setting<>(Color.RED);
/**
* The color of all selections
*/
public final Setting<Color> colorSelection = new Setting<>(Color.CYAN);
/**
* The color of the selection pos 1
*/
public final Setting<Color> colorSelectionPos1 = new Setting<>(Color.BLACK);
/**
* The color of the selection pos 2
*/
public final Setting<Color> colorSelectionPos2 = new Setting<>(Color.ORANGE);
/**
* The opacity of the selection. 0 is completely transparent, 1 is completely opaque
*/
public final Setting<Float> selectionOpacity = new Setting<>(.5f);
/**
* Line width of the goal when rendered, in pixels
*/
public final Setting<Float> selectionLineWidth = new Setting<>(2F);
/**
* Render selections
*/
public final Setting<Boolean> renderSelection = new Setting<>(true);
/**
* Ignore depth when rendering selections
*/
public final Setting<Boolean> renderSelectionIgnoreDepth = new Setting<>(true);
/**
* Render selection corners
*/
public final Setting<Boolean> renderSelectionCorners = new Setting<>(true);
/**
* A map of lowercase setting field names to their respective setting
@@ -869,6 +1034,7 @@ public final class Settings {
public final Map<Setting<?>, Type> settingTypes;
public final class Setting<T> {
public T value;
public final T defaultValue;
private String name;
@@ -951,10 +1117,10 @@ public final class Settings {
}
@SuppressWarnings("unchecked")
public <T> List<Setting<T>> getAllValuesByType(Class<T> klass) {
public <T> List<Setting<T>> getAllValuesByType(Class<T> cla$$) {
List<Setting<T>> result = new ArrayList<>();
for (Setting<?> setting : allSettings) {
if (setting.getValueClass().equals(klass)) {
if (setting.getValueClass().equals(cla$$)) {
result.add((Setting<T>) setting);
}
}

View File

@@ -64,9 +64,17 @@ public interface IPathingBehavior extends IBehavior {
Goal getGoal();
/**
* @return Whether or not a path is currently being executed.
* @return Whether or not a path is currently being executed. This will be false if there's currently a pause.
* @see #hasPath()
*/
default boolean isPathing() {
boolean isPathing();
/**
* @return If there is a current path. Note that the path is not necessarily being executed, for example when there
* is a pause in effect.
* @see #isPathing()
*/
default boolean hasPath() {
return getCurrent() != null;
}

View File

@@ -17,12 +17,9 @@
package baritone.api.cache;
import net.minecraft.util.math.BlockPos;
import org.apache.commons.lang3.ArrayUtils;
import baritone.api.utils.BetterBlockPos;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.*;
/**
* A marker for a position in the world.
@@ -60,7 +57,7 @@ public interface IWaypoint {
*
* @return The block position of this waypoint
*/
BlockPos getLocation();
BetterBlockPos getLocation();
enum Tag {
@@ -92,20 +89,48 @@ public interface IWaypoint {
/**
* The names for the tag, anything that the tag can be referred to as.
*/
private final String[] names;
public final String[] names;
Tag(String... names) {
this.names = names;
}
/**
* Finds a tag from one of the names that could be used to identify said tag.
*
* @param name The name of the tag
* @return The tag, if one is found, otherwise, {@code null}
* @return A name that can be passed to {@link #getByName(String)} to retrieve this tag
*/
public static Tag fromString(String name) {
return TAG_LIST.stream().filter(tag -> ArrayUtils.contains(tag.names, name.toLowerCase())).findFirst().orElse(null);
public String getName() {
return names[0];
}
/**
* Gets a tag by one of its names.
*
* @param name The name to search for.
* @return The tag, if found, or null.
*/
public static Tag getByName(String name) {
for (Tag action : Tag.values()) {
for (String alias : action.names) {
if (alias.equalsIgnoreCase(name)) {
return action;
}
}
}
return null;
}
/**
* @return All tag names.
*/
public static String[] getAllNames() {
Set<String> names = new HashSet<>();
for (Tag tag : Tag.values()) {
names.addAll(Arrays.asList(tag.names));
}
return names.toArray(new String[0]);
}
}
}

View File

@@ -17,6 +17,7 @@
package baritone.api.cache;
import baritone.api.utils.BlockOptionalMetaLookup;
import baritone.api.utils.IPlayerContext;
import net.minecraft.block.Block;
import net.minecraft.util.math.BlockPos;
@@ -33,28 +34,53 @@ public interface IWorldScanner {
/**
* Scans the world, up to the specified max chunk radius, for the specified blocks.
*
* @param ctx The {@link IPlayerContext} containing player and world info that the
* scan is based upon
* @param blocks The blocks to scan for
* @param ctx The {@link IPlayerContext} containing player and world info that the scan is based upon
* @param filter The blocks to scan for
* @param max The maximum number of blocks to scan before cutoff
* @param yLevelThreshold If a block is found within this Y level, the current result will be
* returned, if the value is negative, then this condition doesn't apply.
* @param yLevelThreshold If a block is found within this Y level, the current result will be returned, if the value
* is negative, then this condition doesn't apply.
* @param maxSearchRadius The maximum chunk search radius
* @return The matching block positions
*/
List<BlockPos> scanChunkRadius(IPlayerContext ctx, List<Block> blocks, int max, int yLevelThreshold, int maxSearchRadius);
List<BlockPos> scanChunkRadius(IPlayerContext ctx, BlockOptionalMetaLookup filter, int max, int yLevelThreshold, int maxSearchRadius);
default List<BlockPos> scanChunkRadius(IPlayerContext ctx, List<Block> filter, int max, int yLevelThreshold, int maxSearchRadius) {
return scanChunkRadius(ctx, new BlockOptionalMetaLookup(filter.toArray(new Block[0])), max, yLevelThreshold, maxSearchRadius);
}
/**
* Scans a single chunk for the specified blocks.
*
* @param ctx The {@link IPlayerContext} containing player and world info that the
* scan is based upon
* @param ctx The {@link IPlayerContext} containing player and world info that the scan is based upon
* @param filter The blocks to scan for
* @param pos The position of the target chunk
* @param max The maximum number of blocks to scan before cutoff
* @param yLevelThreshold If a block is found within this Y level, the current result will be returned, if the value
* is negative, then this condition doesn't apply.
* @return The matching block positions
*/
List<BlockPos> scanChunk(IPlayerContext ctx, BlockOptionalMetaLookup filter, ChunkPos pos, int max, int yLevelThreshold);
/**
* Scans a single chunk for the specified blocks.
*
* @param ctx The {@link IPlayerContext} containing player and world info that the scan is based upon
* @param blocks The blocks to scan for
* @param pos The position of the target chunk
* @param max The maximum number of blocks to scan before cutoff
* @param yLevelThreshold If a block is found within this Y level, the current result will be
* returned, if the value is negative, then this condition doesn't apply.
* @param yLevelThreshold If a block is found within this Y level, the current result will be returned, if the value
* is negative, then this condition doesn't apply.
* @return The matching block positions
*/
List<BlockPos> scanChunk(IPlayerContext ctx, List<Block> blocks, ChunkPos pos, int max, int yLevelThreshold);
default List<BlockPos> scanChunk(IPlayerContext ctx, List<Block> blocks, ChunkPos pos, int max, int yLevelThreshold) {
return scanChunk(ctx, new BlockOptionalMetaLookup(blocks), pos, max, yLevelThreshold);
}
/**
* Repacks 40 chunks around the player.
*
* @param ctx The player context for that player.
* @return The number of chunks queued for repacking.
*/
int repack(IPlayerContext ctx);
}

View File

@@ -17,7 +17,7 @@
package baritone.api.cache;
import net.minecraft.util.math.BlockPos;
import baritone.api.utils.BetterBlockPos;
import java.util.Date;
@@ -31,9 +31,9 @@ public class Waypoint implements IWaypoint {
private final String name;
private final Tag tag;
private final long creationTimestamp;
private final BlockPos location;
private final BetterBlockPos location;
public Waypoint(String name, Tag tag, BlockPos location) {
public Waypoint(String name, Tag tag, BetterBlockPos location) {
this(name, tag, location, System.currentTimeMillis());
}
@@ -46,7 +46,7 @@ public class Waypoint implements IWaypoint {
* @param location The waypoint location
* @param creationTimestamp When the waypoint was created
*/
public Waypoint(String name, Tag tag, BlockPos location, long creationTimestamp) {
public Waypoint(String name, Tag tag, BetterBlockPos location, long creationTimestamp) {
this.name = name;
this.tag = tag;
this.location = location;
@@ -55,7 +55,7 @@ public class Waypoint implements IWaypoint {
@Override
public int hashCode() {
return name.hashCode() + tag.hashCode() + location.hashCode(); //lol
return name.hashCode() ^ tag.hashCode() ^ location.hashCode() ^ Long.hashCode(creationTimestamp);
}
@Override
@@ -74,13 +74,18 @@ public class Waypoint implements IWaypoint {
}
@Override
public BlockPos getLocation() {
public BetterBlockPos getLocation() {
return this.location;
}
@Override
public String toString() {
return name + " " + location.toString() + " " + new Date(creationTimestamp).toString();
return String.format(
"%s %s %s",
name,
BetterBlockPos.from(location).toString(),
new Date(creationTimestamp).toString()
);
}
@Override

View File

@@ -0,0 +1,68 @@
/*
* 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.command;
import baritone.api.IBaritone;
import baritone.api.utils.IPlayerContext;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A default implementation of {@link ICommand} which provides easy access to the
* command's bound {@link IBaritone} instance, {@link IPlayerContext} and an easy
* way to provide multiple valid command execution names through the default constructor.
* <p>
* So basically, you should use it because it provides a small amount of boilerplate,
* but you're not forced to use it.
*
* @see ICommand
*
* @author LoganDark
*/
public abstract class Command implements ICommand {
protected IBaritone baritone;
protected IPlayerContext ctx;
/**
* The names of this command. This is what you put after the command prefix.
*/
protected final List<String> names;
/**
* Creates a new Baritone control command.
*
* @param names The names of this command. This is what you put after the command prefix.
*/
protected Command(IBaritone baritone, String... names) {
this.names = Collections.unmodifiableList(Stream.of(names)
.map(s -> s.toLowerCase(Locale.US))
.collect(Collectors.toList()));
this.baritone = baritone;
this.ctx = baritone.getPlayerContext();
}
@Override
public final List<String> getNames() {
return this.names;
}
}

View File

@@ -0,0 +1,42 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.command;
import baritone.api.Settings;
import java.util.UUID;
/**
* @author Brady
* @since 9/26/2019
*/
public interface IBaritoneChatControl {
/**
* In certain cases chat components need to execute commands for you. For example, the paginator automatically runs
* commands when you click the forward and back arrows to show you the previous/next page.
* <p>
* If the prefix is changed in the meantime, then the command will go to chat. That's no good. So here's a permanent
* prefix that forces a command to run, regardless of the current prefix, chat/prefix control being enabled, etc.
* <p>
* If used right (by both developers and users), it should be impossible to expose a command accidentally to the
* server. As a rule of thumb, if you have a clickable chat component, always use this prefix. If you're suggesting
* a command (a component that puts text into your text box, or something else), use {@link Settings#prefix}.
*/
String FORCE_COMMAND_PREFIX = String.format("<<%s>>", UUID.randomUUID().toString());
}

View File

@@ -0,0 +1,67 @@
/*
* 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.command;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import baritone.api.utils.Helper;
import java.util.List;
import java.util.stream.Stream;
/**
* The base for a command.
*
* @author Brady
* @since 10/7/2019
*/
public interface ICommand extends Helper {
/**
* Called when this command is executed.
*/
void execute(String label, IArgConsumer args) throws CommandException;
/**
* Called when the command needs to tab complete. Return a Stream representing the entries to put in the completions
* list.
*/
Stream<String> tabComplete(String label, IArgConsumer args) throws CommandException;
/**
* @return A <b>single-line</b> string containing a short description of this command's purpose.
*/
String getShortDesc();
/**
* @return A list of lines that will be printed by the help command when the user wishes to view them.
*/
List<String> getLongDesc();
/**
* @return A list of the names that can be accepted to have arguments passed to this command
*/
List<String> getNames();
/**
* @return {@code true} if this command should be hidden from the help menu
*/
default boolean hiddenFromHelp() {
return false;
}
}

View File

@@ -15,15 +15,15 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.gradle.util;
package baritone.api.command;
import baritone.api.command.argparser.IArgParserManager;
/**
* All credits go to AsmLibGradle and its contributors.
*
* @see <a href="https://github.com/pozzed/AsmLibGradle/blob/8f917dbc3939eab7a3d9daf54d9d285fdf34f4b2/src/main/java/net/futureclient/asmlib/forgegradle/MappingType.java">Original Source</a>
* @author Brady
* @since 10/4/2019
*/
public enum MappingType {
SEARGE,
NOTCH,
CUSTOM // forgegradle
public interface ICommandSystem {
IArgParserManager getParserManager();
}

View File

@@ -0,0 +1,60 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.command.argparser;
import baritone.api.command.argument.ICommandArgument;
public interface IArgParser<T> {
/**
* @return the class of this parser.
*/
Class<T> getTarget();
/**
* A stateless argument parser is just that. It takes a {@link ICommandArgument} and outputs its type.
*/
interface Stateless<T> extends IArgParser<T> {
/**
* @param arg The argument to parse.
* @return What it was parsed into.
* @throws RuntimeException if you want the parsing to fail. The exception will be caught and turned into an
* appropriate error.
*/
T parseArg(ICommandArgument arg) throws Exception;
}
/**
* A stated argument parser is similar to a stateless one. It also takes a {@link ICommandArgument}, but it also
* takes a second argument that can be any type, referred to as the state.
*/
interface Stated<T, S> extends IArgParser<T> {
Class<S> getStateType();
/**
* @param arg The argument to parse.
* @param state Can be anything.
* @return What it was parsed into.
* @throws RuntimeException if you want the parsing to fail. The exception will be caught and turned into an
* appropriate error.
*/
T parseArg(ICommandArgument arg, S state) throws Exception;
}
}

View File

@@ -0,0 +1,69 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.command.argparser;
import baritone.api.command.argument.ICommandArgument;
import baritone.api.command.exception.CommandInvalidTypeException;
import baritone.api.command.registry.Registry;
/**
* Used to retrieve {@link IArgParser} instances from the registry, by their target class.
* It can be assumed that a {@link IArgParser} exists for {@link Integer}, {@link Long},
* {@link Float}, {@link Double} and {@link Boolean}.
*
* @author Brady
* @since 10/4/2019
*/
public interface IArgParserManager {
/**
* @param type The type trying to be parsed
* @return A parser that can parse arguments into this class, if found.
*/
<T> IArgParser.Stateless<T> getParserStateless(Class<T> type);
/**
* @param type The type trying to be parsed
* @return A parser that can parse arguments into this class, if found.
*/
<T, S> IArgParser.Stated<T, S> getParserStated(Class<T> type, Class<S> stateKlass);
/**
* Attempt to parse the specified argument with a stateless {@link IArgParser} that outputs the specified class.
*
* @param type The type to try and parse the argument into.
* @param arg The argument to parse.
* @return An instance of the specified class.
* @throws CommandInvalidTypeException If the parsing failed
*/
<T> T parseStateless(Class<T> type, ICommandArgument arg) throws CommandInvalidTypeException;
/**
* Attempt to parse the specified argument with a stated {@link IArgParser} that outputs the specified class.
*
* @param type The type to try and parse the argument into.
* @param arg The argument to parse.
* @param state The state to pass to the {@link IArgParser.Stated}.
* @return An instance of the specified class.
* @throws CommandInvalidTypeException If the parsing failed
* @see IArgParser.Stated
*/
<T, S> T parseStated(Class<T> type, Class<S> stateKlass, ICommandArgument arg, S state) throws CommandInvalidTypeException;
Registry<IArgParser> getRegistry();
}

View File

@@ -0,0 +1,594 @@
/*
* 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.command.argument;
import baritone.api.command.ICommand;
import baritone.api.command.exception.CommandTooManyArgumentsException;
import baritone.api.utils.Helper;
import baritone.api.command.argparser.IArgParser;
import baritone.api.command.datatypes.IDatatype;
import baritone.api.command.datatypes.IDatatypeFor;
import baritone.api.command.datatypes.IDatatypePost;
import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidTypeException;
import baritone.api.command.exception.CommandNotEnoughArgumentsException;
import net.minecraft.util.EnumFacing;
import java.util.Deque;
import java.util.LinkedList;
import java.util.stream.Stream;
/**
* The {@link IArgConsumer} is how {@link ICommand}s read the arguments passed to them. This class has many benefits:
*
* <ul>
* <li>Mutability. The whole concept of the {@link IArgConsumer}} is to let you gradually consume arguments in any way
* you'd like. You can change your consumption based on earlier arguments, for subcommands for example.</li>
* <li>You don't need to keep track of your consumption. The {@link IArgConsumer}} keeps track of the arguments you
* consume so that it can throw detailed exceptions whenever something is out of the ordinary. Additionally, if you
* need to retrieve an argument after you've already consumed it - look no further than {@link #consumed()}!</li>
* <li>Easy retrieval of many different types. If you need to retrieve an instance of an int or float for example,
* look no further than {@link #getAs(Class)}. If you need a more powerful way of retrieving data, try out the many
* {@code getDatatype...} methods.</li>
* <li>It's very easy to throw detailed exceptions. The {@link IArgConsumer}} has many different methods that can
* enforce the number of arguments, the type of arguments, and more, throwing different types of
* {@link CommandException}s if something seems off. You're recommended to do all validation and store all needed
* data in variables BEFORE logging any data to chat via {@link Helper#logDirect(String)}, so that the error
* handlers can do their job and log the error to chat.</li>
* </ul>
*/
public interface IArgConsumer {
LinkedList<ICommandArgument> getArgs();
Deque<ICommandArgument> getConsumed();
/**
* @param num The number of arguments to check for
* @return {@code true} if there are <i>at least</i> {@code num} arguments left in this {@link IArgConsumer}}
* @see #hasAny()
* @see #hasAtMost(int)
* @see #hasExactly(int)
*/
boolean has(int num);
/**
* @return {@code true} if there is <i>at least</i> 1 argument left in this {@link IArgConsumer}}
* @see #has(int)
* @see #hasAtMostOne()
* @see #hasExactlyOne()
*/
boolean hasAny();
/**
* @param num The number of arguments to check for
* @return {@code true} if there are <i>at most</i> {@code num} arguments left in this {@link IArgConsumer}}
* @see #has(int)
* @see #hasAtMost(int)
* @see #hasExactly(int)
*/
boolean hasAtMost(int num);
/**
* @return {@code true} if there is <i>at most</i> 1 argument left in this {@link IArgConsumer}}
* @see #hasAny()
* @see #hasAtMostOne()
* @see #hasExactlyOne()
*/
boolean hasAtMostOne();
/**
* @param num The number of arguments to check for
* @return {@code true} if there are <i>exactly</i> {@code num} arguments left in this {@link IArgConsumer}}
* @see #has(int)
* @see #hasAtMost(int)
*/
boolean hasExactly(int num);
/**
* @return {@code true} if there is <i>exactly</i> 1 argument left in this {@link IArgConsumer}}
* @see #hasAny()
* @see #hasAtMostOne()
*/
boolean hasExactlyOne();
/**
* @param index The index to peek
* @return The argument at index {@code index} in this {@link IArgConsumer}}, with 0 being the next one. This does not
* mutate the {@link IArgConsumer}}
* @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left
* @see #peek()
* @see #peekString(int)
* @see #peekAs(Class, int)
* @see #get()
*/
ICommandArgument peek(int index) throws CommandNotEnoughArgumentsException;
/**
* @return The next argument in this {@link IArgConsumer}}. This does not mutate the {@link IArgConsumer}}
* @throws CommandNotEnoughArgumentsException If there is less than one argument left
* @see #peek(int)
* @see #peekString()
* @see #peekAs(Class)
* @see #get()
*/
ICommandArgument peek() throws CommandNotEnoughArgumentsException;
/**
* @param index The index to peek
* @param type The type to check for
* @return If an ArgParser.Stateless for the specified {@code type} would succeed in parsing the next
* argument
* @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left
* @see #peek()
* @see #getAs(Class)
*/
boolean is(Class<?> type, int index) throws CommandNotEnoughArgumentsException;
/**
* @param type The type to check for
* @return If an ArgParser.Stateless for the specified {@code type} would succeed in parsing the next
* argument
* @throws CommandNotEnoughArgumentsException If there is less than one argument left
* @see #peek()
* @see #getAs(Class)
*/
boolean is(Class<?> type) throws CommandNotEnoughArgumentsException;
/**
* @param index The index to peek
* @return The value of the argument at index {@code index} in this {@link IArgConsumer}}, with 0 being the next one
* This does not mutate the {@link IArgConsumer}}
* @throws CommandNotEnoughArgumentsException If there is less than {@code index + 1} arguments left
* @see #peek()
* @see #peekString()
*/
String peekString(int index) throws CommandNotEnoughArgumentsException;
/**
* @return The value of the next argument in this {@link IArgConsumer}}. This does not mutate the {@link IArgConsumer}}
* @throws CommandNotEnoughArgumentsException If there is less than one argument left
* @see #peekString(int)
* @see #getString()
*/
String peekString() throws CommandNotEnoughArgumentsException;
/**
* @param index The index to peek
* @param enumClass The class to search
* @return From the specified enum class, an enum constant of that class. The enum constant's name will match the
* next argument's value
* @throws java.util.NoSuchElementException If the constant couldn't be found
* @see #peekEnumOrNull(Class)
* @see #getEnum(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E peekEnum(Class<E> enumClass, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* @param enumClass The class to search
* @return From the specified enum class, an enum constant of that class. The enum constant's name will match the
* next argument's value
* @throws CommandInvalidTypeException If the constant couldn't be found
* @see #peekEnumOrNull(Class)
* @see #getEnum(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E peekEnum(Class<E> enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* @param index The index to peek
* @param enumClass The class to search
* @return From the specified enum class, an enum constant of that class. The enum constant's name will match the
* next argument's value. If no constant could be found, null
* @see #peekEnum(Class)
* @see #getEnumOrNull(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E peekEnumOrNull(Class<E> enumClass, int index) throws CommandNotEnoughArgumentsException;
/**
* @param enumClass The class to search
* @return From the specified enum class, an enum constant of that class. The enum constant's name will match the
* next argument's value. If no constant could be found, null
* @see #peekEnum(Class)
* @see #getEnumOrNull(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E peekEnumOrNull(Class<E> enumClass) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the argument at the specified index into the specified
* class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @param index The index to peek
* @return An instance of the specified type
* @throws CommandInvalidTypeException If the parsing failed
* @see IArgParser
* @see #peekAs(Class)
* @see #peekAsOrDefault(Class, Object, int)
* @see #peekAsOrNull(Class, int)
*/
<T> T peekAs(Class<T> type, int index) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @return An instance of the specified type
* @throws CommandInvalidTypeException If the parsing failed
* @see IArgParser
* @see #peekAs(Class, int)
* @see #peekAsOrDefault(Class, Object)
* @see #peekAsOrNull(Class)
*/
<T> T peekAs(Class<T> type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the argument at the specified index into the specified
* class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @param def The value to return if the argument can't be parsed
* @param index The index to peek
* @return An instance of the specified type, or {@code def} if it couldn't be parsed
* @see IArgParser
* @see #peekAsOrDefault(Class, Object)
* @see #peekAs(Class, int)
* @see #peekAsOrNull(Class, int)
*/
<T> T peekAsOrDefault(Class<T> type, T def, int index) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @param def The value to return if the argument can't be parsed
* @return An instance of the specified type, or {@code def} if it couldn't be parsed
* @see IArgParser
* @see #peekAsOrDefault(Class, Object, int)
* @see #peekAs(Class)
* @see #peekAsOrNull(Class)
*/
<T> T peekAsOrDefault(Class<T> type, T def) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the argument at the specified index into the specified
* class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @param index The index to peek
* @return An instance of the specified type, or {@code null} if it couldn't be parsed
* @see IArgParser
* @see #peekAsOrNull(Class)
* @see #peekAs(Class, int)
* @see #peekAsOrDefault(Class, Object, int)
*/
<T> T peekAsOrNull(Class<T> type, int index) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @return An instance of the specified type, or {@code null} if it couldn't be parsed
* @see IArgParser
* @see #peekAsOrNull(Class, int)
* @see #peekAs(Class)
* @see #peekAsOrDefault(Class, Object)
*/
<T> T peekAsOrNull(Class<T> type) throws CommandNotEnoughArgumentsException;
<T> T peekDatatype(IDatatypeFor<T> datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T, O> T peekDatatype(IDatatypePost<T, O> datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T, O> T peekDatatype(IDatatypePost<T, O> datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T> T peekDatatypeOrNull(IDatatypeFor<T> datatype);
<T, O> T peekDatatypeOrNull(IDatatypePost<T, O> datatype);
<T, O, D extends IDatatypePost<T, O>> T peekDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T, O, D extends IDatatypePost<T, O>> T peekDatatypePostOrDefault(D datatype, O original, T def);
<T, O, D extends IDatatypePost<T, O>> T peekDatatypePostOrNull(D datatype, O original);
/**
* Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
* <p>
* Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method.
*
* @param datatype The datatype to get
* @return The datatype instance
* @see IDatatype
* @see IDatatypeFor
*/
<T, D extends IDatatypeFor<T>> T peekDatatypeFor(Class<D> datatype);
/**
* Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
* <p>
* Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method.
*
* @param datatype The datatype to get
* @param def The default value
* @return The datatype instance, or {@code def} if it throws an exception
* @see IDatatype
* @see IDatatypeFor
*/
<T, D extends IDatatypeFor<T>> T peekDatatypeForOrDefault(Class<D> datatype, T def);
/**
* Attempts to get the specified {@link IDatatypeFor} from this ArgConsumer
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
* <p>
* Since this is a peek operation, this ArgConsumer will not be mutated by any call to this method.
*
* @param datatype The datatype to get
* @return The datatype instance, or {@code null} if it throws an exception
* @see IDatatype
* @see IDatatypeFor
*/
<T, D extends IDatatypeFor<T>> T peekDatatypeForOrNull(Class<D> datatype);
/**
* Gets the next argument and returns it. This consumes the first argument so that subsequent calls will return
* later arguments
*
* @return The next argument
* @throws CommandNotEnoughArgumentsException If there's less than one argument left
*/
ICommandArgument get() throws CommandNotEnoughArgumentsException;
/**
* Gets the value of the next argument and returns it. This consumes the first argument so that subsequent calls
* will return later arguments
*
* @return The value of the next argument
* @throws CommandNotEnoughArgumentsException If there's less than one argument left
*/
String getString() throws CommandNotEnoughArgumentsException;
/**
* Gets an enum value from the enum class with the same name as the next argument's value
* <p>
* For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return
* {@link EnumFacing#UP}
*
* @param enumClass The enum class to search
* @return An enum constant of that class with the same name as the next argument's value
* @throws CommandInvalidTypeException If the constant couldn't be found
* @see #peekEnum(Class)
* @see #getEnumOrNull(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E getEnum(Class<E> enumClass) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* Gets an enum value from the enum class with the same name as the next argument's value
* <p>
* For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return
* {@link EnumFacing#UP}
*
* @param enumClass The enum class to search
* @param def The default value
* @return An enum constant of that class with the same name as the next argument's value, or {@code def} if it
* couldn't be found
* @see #getEnum(Class)
* @see #getEnumOrNull(Class)
* @see #peekEnumOrNull(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E getEnumOrDefault(Class<E> enumClass, E def) throws CommandNotEnoughArgumentsException;
/**
* Gets an enum value from the enum class with the same name as the next argument's value
* <p>
* For example if you getEnum as an {@link EnumFacing}, and the next argument's value is "up", this will return
* {@link EnumFacing#UP}
*
* @param enumClass The enum class to search
* @return An enum constant of that class with the same name as the next argument's value, or {@code null} if it
* couldn't be found
* @see #getEnum(Class)
* @see #getEnumOrDefault(Class, Enum)
* @see #peekEnumOrNull(Class)
* @see ICommandArgument#getEnum(Class)
*/
<E extends Enum<?>> E getEnumOrNull(Class<E> enumClass) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @return An instance of the specified type
* @throws CommandInvalidTypeException If the parsing failed
* @see IArgParser
* @see #get()
* @see #getAsOrDefault(Class, Object)
* @see #getAsOrNull(Class)
* @see #peekAs(Class)
* @see #peekAsOrDefault(Class, Object, int)
* @see #peekAsOrNull(Class, int)
*/
<T> T getAs(Class<T> type) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @param def The default value
* @return An instance of the specified type, or {@code def} if it couldn't be parsed
* @see IArgParser
* @see #get()
* @see #getAs(Class)
* @see #getAsOrNull(Class)
* @see #peekAs(Class)
* @see #peekAsOrDefault(Class, Object, int)
* @see #peekAsOrNull(Class, int)
*/
<T> T getAsOrDefault(Class<T> type, T def) throws CommandNotEnoughArgumentsException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse the next argument into the specified class
* <p>
* A critical difference between {@link IDatatype}s and {@link IArgParser}s is how many arguments they can take.
* While {@link IArgParser}s always operate on a single argument's value, {@link IDatatype}s get access to the entire
* {@link IArgConsumer}}.
*
* @param type The type to peek as
* @return An instance of the specified type, or {@code null} if it couldn't be parsed
* @see IArgParser
* @see #get()
* @see #getAs(Class)
* @see #getAsOrDefault(Class, Object)
* @see #peekAs(Class)
* @see #peekAsOrDefault(Class, Object, int)
* @see #peekAsOrNull(Class, int)
*/
<T> T getAsOrNull(Class<T> type) throws CommandNotEnoughArgumentsException;
<T, O, D extends IDatatypePost<T, O>> T getDatatypePost(D datatype, O original) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T, O, D extends IDatatypePost<T, O>> T getDatatypePostOrDefault(D datatype, O original, T _default);
<T, O, D extends IDatatypePost<T, O>> T getDatatypePostOrNull(D datatype, O original);
<T, D extends IDatatypeFor<T>> T getDatatypeFor(D datatype) throws CommandInvalidTypeException, CommandNotEnoughArgumentsException;
<T, D extends IDatatypeFor<T>> T getDatatypeForOrDefault(D datatype, T def);
<T, D extends IDatatypeFor<T>> T getDatatypeForOrNull(D datatype);
<T extends IDatatype> Stream<String> tabCompleteDatatype(T datatype);
/**
* Returns the "raw rest" of the string. For example, from a string <code>arg1 arg2&nbsp;&nbsp;arg3</code>, split
* into three {@link ICommandArgument}s {@code "arg1"}, {@code "arg2"}, and {@code "arg3"}:
*
* <ul>
* <li>{@code rawRest()} would return <code>arg1 arg2&nbsp;&nbsp;arg3</code></li>
* <li>After calling {@link #get()}, {@code rawRest()} would return <code>arg2&nbsp;&nbsp;arg3</code> (note the
* double space - it is preserved!)</li>
* <li>After calling {@link #get()} again, {@code rawRest()} would return {@code "arg3"}</li>
* <li>After calling {@link #get()} one last time, {@code rawRest()} would return {@code ""}</li>
* </ul>
*
* @return The "raw rest" of the string.
*/
String rawRest();
/**
* @param min The minimum amount of arguments to require.
* @throws CommandNotEnoughArgumentsException If there are less than {@code min} arguments left.
* @see #requireMax(int)
* @see #requireExactly(int)
*/
void requireMin(int min) throws CommandNotEnoughArgumentsException;
/**
* @param max The maximum amount of arguments allowed.
* @throws CommandTooManyArgumentsException If there are more than {@code max} arguments left.
* @see #requireMin(int)
* @see #requireExactly(int)
*/
void requireMax(int max) throws CommandTooManyArgumentsException;
/**
* @param args The exact amount of arguments to require.
* @throws CommandNotEnoughArgumentsException If there are less than {@code args} arguments left.
* @throws CommandTooManyArgumentsException If there are more than {@code args} arguments left.
* @see #requireMin(int)
* @see #requireMax(int)
*/
void requireExactly(int args) throws CommandException;
/**
* @return If this {@link IArgConsumer}} has consumed at least one argument.
* @see #consumed()
* @see #consumedString()
*/
boolean hasConsumed();
/**
* @return The last argument this {@link IArgConsumer}} has consumed, or an "unknown" argument, indicated by a
* comamnd argument index that has a value of {@code -1}, if no arguments have been consumed yet.
* @see #consumedString()
* @see #hasConsumed()
*/
ICommandArgument consumed();
/**
* @return The value of thelast argument this {@link IArgConsumer}} has consumed, or an empty string if no arguments
* have been consumed yet
* @see #consumed()
* @see #hasConsumed()
*/
String consumedString();
/**
* @return A copy of this {@link IArgConsumer}}. It has the same arguments (both consumed and not), but does not
* affect or mutate this instance. Useful for the various {@code peek} functions
*/
IArgConsumer copy();
}

View File

@@ -0,0 +1,101 @@
/*
* 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.command.argument;
import baritone.api.command.argparser.IArgParser;
import baritone.api.command.exception.CommandInvalidTypeException;
import net.minecraft.util.EnumFacing;
/**
* A {@link ICommandArgument} is an immutable object representing one command argument. It contains data on the index of
* that argument, its value, and the rest of the string that argument was found in
* <p>
* You're recommended to use {@link IArgConsumer}}s to handle these.
*
* @author Brady
* @since 10/2/2019
*/
public interface ICommandArgument {
/**
* @return The index of this command argument in the list of command arguments generated
*/
int getIndex();
/**
* @return The raw value of just this argument
*/
String getValue();
/**
* @return The raw value of the remaining arguments after this one was captured
*/
String getRawRest();
/**
* Gets an enum value from the enum class with the same name as this argument's value
* <p>
* For example if you getEnum as an {@link EnumFacing}, and this argument's value is "up", it will return {@link
* EnumFacing#UP}
*
* @param enumClass The enum class to search
* @return An enum constant of that class with the same name as this argument's value
* @throws CommandInvalidTypeException If the constant couldn't be found
* @see IArgConsumer#peekEnum(Class)
* @see IArgConsumer#peekEnum(Class, int)
* @see IArgConsumer#peekEnumOrNull(Class)
* @see IArgConsumer#peekEnumOrNull(Class, int)
* @see IArgConsumer#getEnum(Class)
* @see IArgConsumer#getEnumOrNull(Class)
*/
<E extends Enum<?>> E getEnum(Class<E> enumClass) throws CommandInvalidTypeException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse this argument into the specified class
*
* @param type The class to parse this argument into
* @return An instance of the specified type
* @throws CommandInvalidTypeException If the parsing failed
*/
<T> T getAs(Class<T> type) throws CommandInvalidTypeException;
/**
* Tries to use a <b>stateless</b> {@link IArgParser} to parse this argument into the specified class
*
* @param type The class to parse this argument into
* @return If the parser succeeded
*/
<T> boolean is(Class<T> type);
/**
* Tries to use a <b>stated</b> {@link IArgParser} to parse this argument into the specified class
*
* @param type The class to parse this argument into
* @return An instance of the specified type
* @throws CommandInvalidTypeException If the parsing failed
*/
<T, S> T getAs(Class<T> type, Class<S> stateType, S state) throws CommandInvalidTypeException;
/**
* Tries to use a <b>stated</b> {@link IArgParser} to parse this argument into the specified class
*
* @param type The class to parse this argument into
* @return If the parser succeeded
*/
<T, S> boolean is(Class<T> type, Class<S> stateType, S state);
}

View File

@@ -0,0 +1,54 @@
/*
* 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.command.datatypes;
import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.command.exception.CommandException;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import java.util.stream.Stream;
public enum BlockById implements IDatatypeFor<Block> {
INSTANCE;
@Override
public Block get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
Block block;
if ((block = IRegistry.BLOCK.get(id)) == Blocks.AIR) {
throw new IllegalArgumentException("no block found by that id");
}
return block;
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper()
.append(
IRegistry.BLOCK.keySet()
.stream()
.map(Object::toString)
)
.filterPrefixNamespaced(ctx.getConsumer().getString())
.sortAlphabetically()
.stream();
}
}

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.command.datatypes;
import baritone.api.command.exception.CommandException;
import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.entity.EntityType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import java.util.stream.Stream;
public enum EntityClassById implements IDatatypeFor<EntityType> {
INSTANCE;
@Override
public EntityType get(IDatatypeContext ctx) throws CommandException {
ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
EntityType entity;
if ((entity = IRegistry.ENTITY_TYPE.get(id)) == null) {
throw new IllegalArgumentException("no entity found by that id");
}
return entity;
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper()
.append(IRegistry.ENTITY_TYPE.stream().map(Object::toString))
.filterPrefixNamespaced(ctx.getConsumer().getString())
.sortAlphabetically()
.stream();
}
}

View File

@@ -0,0 +1,37 @@
/*
* 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.command.datatypes;
import baritone.api.utils.BlockOptionalMeta;
import baritone.api.command.exception.CommandException;
import java.util.stream.Stream;
public enum ForBlockOptionalMeta implements IDatatypeFor<BlockOptionalMeta> {
INSTANCE;
@Override
public BlockOptionalMeta get(IDatatypeContext ctx) throws CommandException {
return new BlockOptionalMeta(ctx.getConsumer().getString());
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) {
return ctx.getConsumer().tabCompleteDatatype(BlockById.INSTANCE);
}
}

View File

@@ -0,0 +1,43 @@
/*
* 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.command.datatypes;
import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.command.exception.CommandException;
import net.minecraft.util.EnumFacing;
import java.util.Locale;
import java.util.stream.Stream;
public enum ForEnumFacing implements IDatatypeFor<EnumFacing> {
INSTANCE;
@Override
public EnumFacing get(IDatatypeContext ctx) throws CommandException {
return EnumFacing.valueOf(ctx.getConsumer().getString().toUpperCase(Locale.US));
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper()
.append(Stream.of(EnumFacing.values())
.map(EnumFacing::getName).map(String::toLowerCase))
.filterPrefix(ctx.getConsumer().getString())
.stream();
}
}

View File

@@ -0,0 +1,81 @@
/*
* 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.command.datatypes;
import baritone.api.IBaritone;
import baritone.api.cache.IWaypoint;
import baritone.api.cache.IWaypointCollection;
import baritone.api.command.helpers.TabCompleteHelper;
import baritone.api.command.exception.CommandException;
import java.util.Comparator;
import java.util.stream.Stream;
public enum ForWaypoints implements IDatatypeFor<IWaypoint[]> {
INSTANCE;
@Override
public IWaypoint[] get(IDatatypeContext ctx) throws CommandException {
final String input = ctx.getConsumer().getString();
final IWaypoint.Tag tag = IWaypoint.Tag.getByName(input);
// If the input doesn't resolve to a valid tag, resolve by name
return tag == null
? getWaypointsByName(ctx.getBaritone(), input)
: getWaypointsByTag(ctx.getBaritone(), tag);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper()
.append(getWaypointNames(ctx.getBaritone()))
.sortAlphabetically()
.prepend(IWaypoint.Tag.getAllNames())
.filterPrefix(ctx.getConsumer().getString())
.stream();
}
public static IWaypointCollection waypoints(IBaritone baritone) {
return baritone.getWorldProvider().getCurrentWorld().getWaypoints();
}
public static IWaypoint[] getWaypoints(IBaritone baritone) {
return waypoints(baritone).getAllWaypoints().stream()
.sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed())
.toArray(IWaypoint[]::new);
}
public static String[] getWaypointNames(IBaritone baritone) {
return Stream.of(getWaypoints(baritone))
.map(IWaypoint::getName)
.filter(name -> !name.isEmpty())
.toArray(String[]::new);
}
public static IWaypoint[] getWaypointsByTag(IBaritone baritone, IWaypoint.Tag tag) {
return waypoints(baritone).getByTag(tag).stream()
.sorted(Comparator.comparingLong(IWaypoint::getCreationTimestamp).reversed())
.toArray(IWaypoint[]::new);
}
public static IWaypoint[] getWaypointsByName(IBaritone baritone, String name) {
return Stream.of(getWaypoints(baritone))
.filter(waypoint -> waypoint.getName().equalsIgnoreCase(name))
.toArray(IWaypoint[]::new);
}
}

View File

@@ -0,0 +1,56 @@
/*
* 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.command.datatypes;
import baritone.api.command.argparser.IArgParser;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import java.util.stream.Stream;
/**
* An {@link IDatatype} is similar to an {@link IArgParser} in the sense that it is capable of consuming an argument
* to transform it into a usable form as the code desires.
* <p>
* A fundamental difference is that an {@link IDatatype} is capable of consuming multiple arguments. For example,
* {@link RelativeBlockPos} is an {@link IDatatypePost} which requires at least 3 {@link RelativeCoordinate} arguments
* to be specified.
* <p>
* Another difference is that an {@link IDatatype} can be tab-completed, providing comprehensive auto completion
* that can substitute based on existing input or provide possibilities for the next piece of input.
*
* @see IDatatypeContext
* @see IDatatypeFor
* @see IDatatypePost
*/
public interface IDatatype {
/**
* Attempts to complete missing or partial input provided through the {@link IArgConsumer}} provided by
* {@link IDatatypeContext#getConsumer()} in order to aide the user in executing commands.
* <p>
* One benefit over datatypes over {@link IArgParser}s is that instead of each command trying to guess what values
* the datatype will accept, or simply not tab completing at all, datatypes that support tab completion can provide
* accurate information using the same methods used to parse arguments in the first place.
*
* @param ctx The argument consumer to tab complete
* @return A stream representing the strings that can be tab completed. DO NOT INCLUDE SPACES IN ANY STRINGS.
* @see IArgConsumer#tabCompleteDatatype(IDatatype)
*/
Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException;
}

View File

@@ -0,0 +1,47 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.command.datatypes;
import baritone.api.IBaritone;
import baritone.api.command.argument.IArgConsumer;
/**
* Provides an {@link IDatatype} with contextual information so
* that it can perform the desired operation on the target level.
*
* @see IDatatype
*
* @author Brady
* @since 9/26/2019
*/
public interface IDatatypeContext {
/**
* Provides the {@link IBaritone} instance that is associated with the action relating to datatype handling.
*
* @return The context {@link IBaritone} instance.
*/
IBaritone getBaritone();
/**
* Provides the {@link IArgConsumer}} to fetch input information from.
*
* @return The context {@link IArgConsumer}}.
*/
IArgConsumer getConsumer();
}

View File

@@ -0,0 +1,44 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.command.datatypes;
import baritone.api.command.exception.CommandException;
import java.util.function.Supplier;
/**
* An {@link IDatatype} which acts as a {@link Supplier}, in essence. The only difference
* is that it requires an {@link IDatatypeContext} to be provided due to the expectation that
* implementations of {@link IDatatype} are singletons.
*/
public interface IDatatypeFor<T> extends IDatatype {
/**
* Consumes the desired amount of arguments from the specified {@link IDatatypeContext}, and
* then returns the parsed value. This method will more than likely return a {@link IllegalArgumentException}
* if the expected input does not conform to a parseable value. As far as a {@link CommandException} being
* thrown is concerned, see the note below for specifics.
*
* @see IDatatypeContext
*
* @param ctx The context
* @return The parsed data-type
* @throws CommandException If there was an issue parsing using another type or arguments could not be polled.
*/
T get(IDatatypeContext ctx) throws CommandException;
}

View File

@@ -0,0 +1,41 @@
/*
* 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.command.datatypes;
import baritone.api.command.exception.CommandException;
import java.util.function.Function;
/**
* An {@link IDatatype} which acts as a {@link Function}, in essence. The only difference
* is that it requires an {@link IDatatypeContext} to be provided due to the expectation that
* implementations of {@link IDatatype} are singletons.
*/
public interface IDatatypePost<T, O> extends IDatatype {
/**
* Takes the expected input and transforms it based on the value held by {@code original}. If {@code original}
* is null, it is expected that the implementation of this method has a case to handle it, such that a
* {@link NullPointerException} will never be thrown as a result.
*
* @param ctx The datatype context
* @param original The transformable value
* @return The transformed value
*/
T apply(IDatatypeContext ctx, O original) throws CommandException;
}

View File

@@ -0,0 +1,29 @@
/*
* 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.command.datatypes;
import baritone.api.command.exception.CommandException;
/**
* @author Brady
* @since 9/26/2019
*/
public interface IDatatypePostFunction<T, O> {
T apply(O original) throws CommandException;
}

View File

@@ -0,0 +1,56 @@
/*
* 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.command.datatypes;
import baritone.api.IBaritone;
import baritone.api.command.exception.CommandException;
import baritone.api.command.helpers.TabCompleteHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.text.ITextComponent;
import java.util.List;
import java.util.stream.Stream;
/**
* An {@link IDatatype} used to resolve nearby players, those within
* render distance of the target {@link IBaritone} instance.
*/
public enum NearbyPlayer implements IDatatypeFor<EntityPlayer> {
INSTANCE;
@Override
public EntityPlayer get(IDatatypeContext ctx) throws CommandException {
final String username = ctx.getConsumer().getString();
return getPlayers(ctx).stream()
.filter(s -> s.getName().getString().equalsIgnoreCase(username))
.findFirst().orElse(null);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
return new TabCompleteHelper()
.append(getPlayers(ctx).stream().map(EntityPlayer::getName).map(ITextComponent::getString))
.filterPrefix(ctx.getConsumer().getString())
.sortAlphabetically()
.stream();
}
private static List<EntityPlayer> getPlayers(IDatatypeContext ctx) {
return ctx.getBaritone().getPlayerContext().world().playerEntities;
}
}

View File

@@ -0,0 +1,57 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.utils.BetterBlockPos;
import baritone.api.command.exception.CommandException;
import java.util.stream.Stream;
public enum RelativeBlockPos implements IDatatypePost<BetterBlockPos, BetterBlockPos> {
INSTANCE;
@Override
public BetterBlockPos apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException {
if (origin == null) {
origin = BetterBlockPos.ORIGIN;
}
final IArgConsumer consumer = ctx.getConsumer();
return new BetterBlockPos(
consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x),
consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y),
consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.z)
);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
final IArgConsumer consumer = ctx.getConsumer();
if (consumer.hasAny() && !consumer.has(4)) {
while (consumer.has(2)) {
if (consumer.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) == null) {
break;
}
consumer.get();
}
return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE);
}
return Stream.empty();
}
}

View File

@@ -0,0 +1,64 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public enum RelativeCoordinate implements IDatatypePost<Double, Double> {
INSTANCE;
private static Pattern PATTERN = Pattern.compile("^(~?)([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)([k-k]?)|)$");
@Override
public Double apply(IDatatypeContext ctx, Double origin) throws CommandException {
if (origin == null) {
origin = 0.0D;
}
Matcher matcher = PATTERN.matcher(ctx.getConsumer().getString());
if (!matcher.matches()) {
throw new IllegalArgumentException("pattern doesn't match");
}
boolean isRelative = !matcher.group(1).isEmpty();
double offset = matcher.group(2).isEmpty() ? 0 : Double.parseDouble(matcher.group(2).replaceAll("k", ""));
if (matcher.group(2).contains("k")) {
offset *= 1000;
}
if (isRelative) {
return origin + offset;
}
return offset;
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
final IArgConsumer consumer = ctx.getConsumer();
if (!consumer.has(2) && consumer.getString().matches("^(~|$)")) {
return Stream.of("~");
}
return Stream.empty();
}
}

View File

@@ -0,0 +1,103 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.exception.CommandException;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.FileSystems;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Stream;
import static baritone.api.utils.Helper.HELPER;
public enum RelativeFile implements IDatatypePost<File, File> {
INSTANCE;
@Override
public File apply(IDatatypeContext ctx, File original) throws CommandException {
if (original == null) {
original = new File("./");
}
Path path;
try {
path = FileSystems.getDefault().getPath(ctx.getConsumer().getString());
} catch (InvalidPathException e) {
throw new IllegalArgumentException("invalid path");
}
return getCanonicalFileUnchecked(original.toPath().resolve(path).toFile());
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) {
return Stream.empty();
}
/**
* Seriously
*
* @param file File
* @return Canonical file of file
* @author LoganDark
*/
private static File getCanonicalFileUnchecked(File file) {
try {
return file.getCanonicalFile();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static Stream<String> tabComplete(IArgConsumer consumer, File base0) throws CommandException {
// I will not make the caller deal with this, seriously
// Tab complete code is beautiful and I'm not going to bloat it with dumb ass checked exception bullshit -LoganDark
// lol owned -Brady
File base = getCanonicalFileUnchecked(base0);
String currentPathStringThing = consumer.getString();
Path currentPath = FileSystems.getDefault().getPath(currentPathStringThing);
Path basePath = currentPath.isAbsolute() ? currentPath.getRoot() : base.toPath();
boolean useParent = !currentPathStringThing.isEmpty() && !currentPathStringThing.endsWith(File.separator);
File currentFile = currentPath.isAbsolute() ? currentPath.toFile() : new File(base, currentPathStringThing);
return Stream.of(Objects.requireNonNull(getCanonicalFileUnchecked(
useParent
? currentFile.getParentFile()
: currentFile
).listFiles()))
.map(f -> (currentPath.isAbsolute() ? f : basePath.relativize(f.toPath()).toString()) +
(f.isDirectory() ? File.separator : ""))
.filter(s -> s.toLowerCase(Locale.US).startsWith(currentPathStringThing.toLowerCase(Locale.US)))
.filter(s -> !s.contains(" "));
}
public static File gameDir() {
File gameDir = HELPER.mc.gameDir.getAbsoluteFile();
if (gameDir.getName().equals(".")) {
return gameDir.getParentFile();
}
return gameDir;
}
}

View File

@@ -0,0 +1,79 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.pathing.goals.GoalXZ;
import baritone.api.pathing.goals.GoalYLevel;
import baritone.api.utils.BetterBlockPos;
import baritone.api.command.exception.CommandException;
import net.minecraft.util.math.MathHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public enum RelativeGoal implements IDatatypePost<Goal, BetterBlockPos> {
INSTANCE;
@Override
public Goal apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException {
if (origin == null) {
origin = BetterBlockPos.ORIGIN;
}
final IArgConsumer consumer = ctx.getConsumer();
List<IDatatypePostFunction<Double, Double>> coords = new ArrayList<>();
final IArgConsumer copy = consumer.copy(); // This is a hack and should be fixed in the future probably
for (int i = 0; i < 3; i++) {
if (copy.peekDatatypeOrNull(RelativeCoordinate.INSTANCE) != null) {
coords.add(o -> consumer.getDatatypePost(RelativeCoordinate.INSTANCE, o));
copy.get(); // Consume so we actually decrement the remaining arguments
}
}
switch (coords.size()) {
case 0:
return new GoalBlock(origin);
case 1:
return new GoalYLevel(
MathHelper.floor(coords.get(0).apply((double) origin.y))
);
case 2:
return new GoalXZ(
MathHelper.floor(coords.get(0).apply((double) origin.x)),
MathHelper.floor(coords.get(1).apply((double) origin.z))
);
case 3:
return new GoalBlock(
MathHelper.floor(coords.get(0).apply((double) origin.x)),
MathHelper.floor(coords.get(1).apply((double) origin.y)),
MathHelper.floor(coords.get(2).apply((double) origin.z))
);
default:
throw new IllegalStateException("Unexpected coords size: " + coords.size());
}
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) {
return ctx.getConsumer().tabCompleteDatatype(RelativeCoordinate.INSTANCE);
}
}

View File

@@ -0,0 +1,53 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.utils.BetterBlockPos;
import baritone.api.command.exception.CommandException;
import net.minecraft.util.math.MathHelper;
import java.util.stream.Stream;
public enum RelativeGoalBlock implements IDatatypePost<GoalBlock, BetterBlockPos> {
INSTANCE;
@Override
public GoalBlock apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException {
if (origin == null) {
origin = BetterBlockPos.ORIGIN;
}
final IArgConsumer consumer = ctx.getConsumer();
return new GoalBlock(
MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x)),
MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y)),
MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.z))
);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) {
final IArgConsumer consumer = ctx.getConsumer();
if (consumer.hasAtMost(3)) {
return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE);
}
return Stream.empty();
}
}

View File

@@ -0,0 +1,52 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.pathing.goals.GoalXZ;
import baritone.api.utils.BetterBlockPos;
import baritone.api.command.exception.CommandException;
import net.minecraft.util.math.MathHelper;
import java.util.stream.Stream;
public enum RelativeGoalXZ implements IDatatypePost<GoalXZ, BetterBlockPos> {
INSTANCE;
@Override
public GoalXZ apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException {
if (origin == null) {
origin = BetterBlockPos.ORIGIN;
}
final IArgConsumer consumer = ctx.getConsumer();
return new GoalXZ(
MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.x)),
MathHelper.floor(consumer.getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y))
);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) {
final IArgConsumer consumer = ctx.getConsumer();
if (consumer.hasAtMost(2)) {
return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE);
}
return Stream.empty();
}
}

View File

@@ -0,0 +1,50 @@
/*
* 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.command.datatypes;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.pathing.goals.GoalYLevel;
import baritone.api.utils.BetterBlockPos;
import baritone.api.command.exception.CommandException;
import net.minecraft.util.math.MathHelper;
import java.util.stream.Stream;
public enum RelativeGoalYLevel implements IDatatypePost<GoalYLevel, BetterBlockPos> {
INSTANCE;
@Override
public GoalYLevel apply(IDatatypeContext ctx, BetterBlockPos origin) throws CommandException {
if (origin == null) {
origin = BetterBlockPos.ORIGIN;
}
return new GoalYLevel(
MathHelper.floor(ctx.getConsumer().getDatatypePost(RelativeCoordinate.INSTANCE, (double) origin.y))
);
}
@Override
public Stream<String> tabComplete(IDatatypeContext ctx) {
final IArgConsumer consumer = ctx.getConsumer();
if (consumer.hasAtMost(1)) {
return consumer.tabCompleteDatatype(RelativeCoordinate.INSTANCE);
}
return Stream.empty();
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.command.exception;
public abstract class CommandErrorMessageException extends CommandException {
protected CommandErrorMessageException(String reason) {
super(reason);
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.command.exception;
public abstract class CommandException extends Exception implements ICommandException {
protected CommandException(String reason) {
super(reason);
}
}

View File

@@ -0,0 +1,34 @@
/*
* 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.command.exception;
import baritone.api.command.argument.ICommandArgument;
public abstract class CommandInvalidArgumentException extends CommandErrorMessageException {
public final ICommandArgument arg;
protected CommandInvalidArgumentException(ICommandArgument arg, String reason) {
super(String.format(
"Error at argument #%s: %s",
arg.getIndex() == -1 ? "<unknown>" : Integer.toString(arg.getIndex() + 1),
reason
));
this.arg = arg;
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.command.exception;
public class CommandInvalidStateException extends CommandErrorMessageException {
public CommandInvalidStateException(String reason) {
super(reason);
}
}

View File

@@ -0,0 +1,39 @@
/*
* 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.command.exception;
import baritone.api.command.argument.ICommandArgument;
public class CommandInvalidTypeException extends CommandInvalidArgumentException {
public CommandInvalidTypeException(ICommandArgument arg, String expected) {
super(arg, String.format("Expected %s", expected));
}
public CommandInvalidTypeException(ICommandArgument arg, String expected, Throwable cause) {
super(arg, String.format("Expected %s.\nMore details: %s", expected, cause.getMessage()));
}
public CommandInvalidTypeException(ICommandArgument arg, String expected, String got) {
super(arg, String.format("Expected %s, but got %s instead", expected, got));
}
public CommandInvalidTypeException(ICommandArgument arg, String expected, String got, Throwable cause) {
super(arg, String.format("Expected %s, but got %s instead.\nMore details: %s", expected, got, cause.getMessage()));
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.command.exception;
public class CommandNoParserForTypeException extends CommandUnhandledException {
public CommandNoParserForTypeException(Class<?> klass) {
super(String.format("Could not find a handler for type %s", klass.getSimpleName()));
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.command.exception;
public class CommandNotEnoughArgumentsException extends CommandErrorMessageException {
public CommandNotEnoughArgumentsException(int minArgs) {
super(String.format("Not enough arguments (expected at least %d)", minArgs));
}
}

View File

@@ -0,0 +1,40 @@
/*
* 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.command.exception;
import baritone.api.command.ICommand;
import baritone.api.command.argument.ICommandArgument;
import java.util.List;
import static baritone.api.utils.Helper.HELPER;
public class CommandNotFoundException extends CommandException {
public final String command;
public CommandNotFoundException(String command) {
super(String.format("Command not found: %s", command));
this.command = command;
}
@Override
public void handle(ICommand command, List<ICommandArgument> args) {
HELPER.logDirect(getMessage());
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.command.exception;
public class CommandTooManyArgumentsException extends CommandErrorMessageException {
public CommandTooManyArgumentsException(int maxArgs) {
super(String.format("Too many arguments (expected at most %d)", maxArgs));
}
}

View File

@@ -0,0 +1,46 @@
/*
* 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.command.exception;
import baritone.api.command.ICommand;
import baritone.api.command.argument.ICommandArgument;
import net.minecraft.util.text.TextFormatting;
import java.util.List;
import static baritone.api.utils.Helper.HELPER;
public class CommandUnhandledException extends RuntimeException implements ICommandException {
public CommandUnhandledException(String message) {
super(message);
}
public CommandUnhandledException(Throwable cause) {
super(cause);
}
@Override
public void handle(ICommand command, List<ICommandArgument> args) {
HELPER.logDirect("An unhandled exception occurred." +
"The error is in your game's log, please report this at https://github.com/cabaletta/baritone/issues",
TextFormatting.RED);
this.printStackTrace();
}
}

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.api.command.exception;
import baritone.api.command.ICommand;
import baritone.api.command.argument.ICommandArgument;
import net.minecraft.util.text.TextFormatting;
import java.util.List;
import static baritone.api.utils.Helper.HELPER;
/**
* The base for a Baritone Command Exception, checked or unchecked. Provides a
* {@link #handle(ICommand, List)} method that is used to provide useful output
* to the user for diagnosing issues that may have occurred during execution.
* <p>
* Anything implementing this interface should be assignable to {@link Exception}.
*
* @author Brady
* @since 9/20/2019
*/
public interface ICommandException {
/**
* @see Exception#getMessage()
* @return The exception details
*/
String getMessage();
/**
* Called when this exception is thrown, to handle the exception.
*
* @param command The command that threw it.
* @param args The arguments the command was called with.
*/
default void handle(ICommand command, List<ICommandArgument> args) {
HELPER.logDirect(this.getMessage(), TextFormatting.RED);
}
}

View File

@@ -0,0 +1,184 @@
/*
* 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.command.helpers;
import baritone.api.utils.Helper;
import baritone.api.command.exception.CommandException;
import baritone.api.command.exception.CommandInvalidTypeException;
import baritone.api.command.argument.IArgConsumer;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.util.text.event.HoverEvent;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class Paginator<E> implements Helper {
public final List<E> entries;
public int pageSize = 8;
public int page = 1;
public Paginator(List<E> entries) {
this.entries = entries;
}
public Paginator(E... entries) {
this.entries = Arrays.asList(entries);
}
public Paginator<E> setPageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
public int getMaxPage() {
return (entries.size() - 1) / pageSize + 1;
}
public boolean validPage(int page) {
return page > 0 && page <= getMaxPage();
}
public Paginator<E> skipPages(int pages) {
page += pages;
return this;
}
public void display(Function<E, ITextComponent> transform, String commandPrefix) {
int offset = (page - 1) * pageSize;
for (int i = offset; i < offset + pageSize; i++) {
if (i < entries.size()) {
logDirect(transform.apply(entries.get(i)));
} else {
logDirect("--", TextFormatting.DARK_GRAY);
}
}
boolean hasPrevPage = commandPrefix != null && validPage(page - 1);
boolean hasNextPage = commandPrefix != null && validPage(page + 1);
ITextComponent prevPageComponent = new TextComponentString("<<");
if (hasPrevPage) {
prevPageComponent.getStyle()
.setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format("%s %d", commandPrefix, page - 1)
))
.setHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
new TextComponentString("Click to view previous page")
));
} else {
prevPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
}
ITextComponent nextPageComponent = new TextComponentString(">>");
if (hasNextPage) {
nextPageComponent.getStyle()
.setClickEvent(new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
String.format("%s %d", commandPrefix, page + 1)
))
.setHoverEvent(new HoverEvent(
HoverEvent.Action.SHOW_TEXT,
new TextComponentString("Click to view next page")
));
} else {
nextPageComponent.getStyle().setColor(TextFormatting.DARK_GRAY);
}
ITextComponent pagerComponent = new TextComponentString("");
pagerComponent.getStyle().setColor(TextFormatting.GRAY);
pagerComponent.appendSibling(prevPageComponent);
pagerComponent.appendText(" | ");
pagerComponent.appendSibling(nextPageComponent);
pagerComponent.appendText(String.format(" %d/%d", page, getMaxPage()));
logDirect(pagerComponent);
}
public void display(Function<E, ITextComponent> transform) {
display(transform, null);
}
public static <T> void paginate(IArgConsumer consumer, Paginator<T> pagi, Runnable pre, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
int page = 1;
consumer.requireMax(1);
if (consumer.hasAny()) {
page = consumer.getAs(Integer.class);
if (!pagi.validPage(page)) {
throw new CommandInvalidTypeException(
consumer.consumed(),
String.format(
"a valid page (1-%d)",
pagi.getMaxPage()
),
consumer.consumed().getValue()
);
}
}
pagi.skipPages(page - pagi.page);
if (pre != null) {
pre.run();
}
pagi.display(transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, List<T> elems, Runnable pre, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
paginate(consumer, new Paginator<>(elems), pre, transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, T[] elems, Runnable pre, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
paginate(consumer, Arrays.asList(elems), pre, transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, Paginator<T> pagi, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
paginate(consumer, pagi, null, transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, List<T> elems, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
paginate(consumer, new Paginator<>(elems), null, transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, T[] elems, Function<T, ITextComponent> transform, String commandPrefix) throws CommandException {
paginate(consumer, Arrays.asList(elems), null, transform, commandPrefix);
}
public static <T> void paginate(IArgConsumer consumer, Paginator<T> pagi, Runnable pre, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, pagi, pre, transform, null);
}
public static <T> void paginate(IArgConsumer consumer, List<T> elems, Runnable pre, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, new Paginator<>(elems), pre, transform, null);
}
public static <T> void paginate(IArgConsumer consumer, T[] elems, Runnable pre, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, Arrays.asList(elems), pre, transform, null);
}
public static <T> void paginate(IArgConsumer consumer, Paginator<T> pagi, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, pagi, null, transform, null);
}
public static <T> void paginate(IArgConsumer consumer, List<T> elems, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, new Paginator<>(elems), null, transform, null);
}
public static <T> void paginate(IArgConsumer consumer, T[] elems, Function<T, ITextComponent> transform) throws CommandException {
paginate(consumer, Arrays.asList(elems), null, transform, null);
}
}

View File

@@ -0,0 +1,288 @@
/*
* 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.command.helpers;
import baritone.api.BaritoneAPI;
import baritone.api.Settings;
import baritone.api.event.events.TabCompleteEvent;
import baritone.api.utils.SettingsUtil;
import baritone.api.command.argument.IArgConsumer;
import baritone.api.command.manager.ICommandManager;
import net.minecraft.util.ResourceLocation;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* The {@link TabCompleteHelper} is a <b>single-use</b> object that helps you handle tab completion. It includes helper
* methods for appending and prepending streams, sorting, filtering by prefix, and so on.
* <p>
* The recommended way to use this class is:
* <ul>
* <li>Create a new instance with the empty constructor</li>
* <li>Use {@code append}, {@code prepend} or {@code add<something>} methods to add completions</li>
* <li>Sort using {@link #sort(Comparator)} or {@link #sortAlphabetically()} and then filter by prefix using
* {@link #filterPrefix(String)}</li>
* <li>Get the stream using {@link #stream()}</li>
* <li>Pass it up to whatever's calling your tab complete function (i.e.
* {@link ICommandManager#tabComplete(String)} or {@link IArgConsumer}#tabCompleteDatatype(IDatatype)})</li>
* </ul>
* <p>
* For advanced users: if you're intercepting {@link TabCompleteEvent}s directly, use {@link #build()} instead for an
* array.
*/
public class TabCompleteHelper {
private Stream<String> stream;
public TabCompleteHelper(String[] base) {
stream = Stream.of(base);
}
public TabCompleteHelper(List<String> base) {
stream = base.stream();
}
public TabCompleteHelper() {
stream = Stream.empty();
}
/**
* Appends the specified stream to this {@link TabCompleteHelper} and returns it for chaining
*
* @param source The stream to append
* @return This {@link TabCompleteHelper} after having appended the stream
* @see #append(String...)
* @see #append(Class)
*/
public TabCompleteHelper append(Stream<String> source) {
stream = Stream.concat(stream, source);
return this;
}
/**
* Appends the specified strings to this {@link TabCompleteHelper} and returns it for chaining
*
* @param source The stream to append
* @return This {@link TabCompleteHelper} after having appended the strings
* @see #append(Stream)
* @see #append(Class)
*/
public TabCompleteHelper append(String... source) {
return append(Stream.of(source));
}
/**
* Appends all values of the specified enum to this {@link TabCompleteHelper} and returns it for chaining
*
* @param num The enum to append the values of
* @return This {@link TabCompleteHelper} after having appended the values
* @see #append(Stream)
* @see #append(String...)
*/
public TabCompleteHelper append(Class<? extends Enum<?>> num) {
return append(
Stream.of(num.getEnumConstants())
.map(Enum::name)
.map(String::toLowerCase)
);
}
/**
* Prepends the specified stream to this {@link TabCompleteHelper} and returns it for chaining
*
* @param source The stream to prepend
* @return This {@link TabCompleteHelper} after having prepended the stream
* @see #prepend(String...)
* @see #prepend(Class)
*/
public TabCompleteHelper prepend(Stream<String> source) {
stream = Stream.concat(source, stream);
return this;
}
/**
* Prepends the specified strings to this {@link TabCompleteHelper} and returns it for chaining
*
* @param source The stream to prepend
* @return This {@link TabCompleteHelper} after having prepended the strings
* @see #prepend(Stream)
* @see #prepend(Class)
*/
public TabCompleteHelper prepend(String... source) {
return prepend(Stream.of(source));
}
/**
* Prepends all values of the specified enum to this {@link TabCompleteHelper} and returns it for chaining
*
* @param num The enum to prepend the values of
* @return This {@link TabCompleteHelper} after having prepended the values
* @see #prepend(Stream)
* @see #prepend(String...)
*/
public TabCompleteHelper prepend(Class<? extends Enum<?>> num) {
return prepend(
Stream.of(num.getEnumConstants())
.map(Enum::name)
.map(String::toLowerCase)
);
}
/**
* Apply the specified {@code transform} to every element <b>currently</b> in this {@link TabCompleteHelper} and
* return this object for chaining
*
* @param transform The transform to apply
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper map(Function<String, String> transform) {
stream = stream.map(transform);
return this;
}
/**
* Apply the specified {@code filter} to every element <b>currently</b> in this {@link TabCompleteHelper} and return
* this object for chaining
*
* @param filter The filter to apply
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper filter(Predicate<String> filter) {
stream = stream.filter(filter);
return this;
}
/**
* Apply the specified {@code sort} to every element <b>currently</b> in this {@link TabCompleteHelper} and return
* this object for chaining
*
* @param comparator The comparator to use
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper sort(Comparator<String> comparator) {
stream = stream.sorted(comparator);
return this;
}
/**
* Sort every element <b>currently</b> in this {@link TabCompleteHelper} alphabetically and return this object for
* chaining
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper sortAlphabetically() {
return sort(String.CASE_INSENSITIVE_ORDER);
}
/**
* Filter out any element that doesn't start with {@code prefix} and return this object for chaining
*
* @param prefix The prefix to filter for
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper filterPrefix(String prefix) {
return filter(x -> x.toLowerCase(Locale.US).startsWith(prefix.toLowerCase(Locale.US)));
}
/**
* Filter out any element that doesn't start with {@code prefix} and return this object for chaining
* <p>
* Assumes every element in this {@link TabCompleteHelper} is a {@link ResourceLocation}
*
* @param prefix The prefix to filter for
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper filterPrefixNamespaced(String prefix) {
return filterPrefix(new ResourceLocation(prefix).toString());
}
/**
* @return An array containing every element in this {@link TabCompleteHelper}
* @see #stream()
*/
public String[] build() {
return stream.toArray(String[]::new);
}
/**
* @return A stream containing every element in this {@link TabCompleteHelper}
* @see #build()
*/
public Stream<String> stream() {
return stream;
}
/**
* Appends every command in the specified {@link ICommandManager} to this {@link TabCompleteHelper}
*
* @param manager A command manager
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper addCommands(ICommandManager manager) {
return append(manager.getRegistry().descendingStream()
.flatMap(command -> command.getNames().stream())
.distinct()
);
}
/**
* Appends every setting in the {@link Settings} to this {@link TabCompleteHelper}
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper addSettings() {
return append(
BaritoneAPI.getSettings().allSettings.stream()
.map(Settings.Setting::getName)
.filter(s -> !s.equalsIgnoreCase("logger"))
.sorted(String.CASE_INSENSITIVE_ORDER)
);
}
/**
* Appends every modified setting in the {@link Settings} to this {@link TabCompleteHelper}
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper addModifiedSettings() {
return append(
SettingsUtil.modifiedSettings(BaritoneAPI.getSettings()).stream()
.map(Settings.Setting::getName)
.sorted(String.CASE_INSENSITIVE_ORDER)
);
}
/**
* Appends every {@link Boolean} setting in the {@link Settings} to this {@link TabCompleteHelper}
*
* @return This {@link TabCompleteHelper}
*/
public TabCompleteHelper addToggleableSettings() {
return append(
BaritoneAPI.getSettings().getAllValuesByType(Boolean.class).stream()
.map(Settings.Setting::getName)
.sorted(String.CASE_INSENSITIVE_ORDER)
);
}
}

View File

@@ -0,0 +1,52 @@
/*
* 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.command.manager;
import baritone.api.IBaritone;
import baritone.api.command.ICommand;
import baritone.api.command.argument.ICommandArgument;
import baritone.api.command.registry.Registry;
import net.minecraft.util.Tuple;
import java.util.List;
import java.util.stream.Stream;
/**
* @author Brady
* @since 9/21/2019
*/
public interface ICommandManager {
IBaritone getBaritone();
Registry<ICommand> getRegistry();
/**
* @param name The command name to search for.
* @return The command, if found.
*/
ICommand getCommand(String name);
boolean execute(String string);
boolean execute(Tuple<String, List<ICommandArgument>> expanded);
Stream<String> tabComplete(Tuple<String, List<ICommandArgument>> expanded);
Stream<String> tabComplete(String prefix);
}

View File

@@ -0,0 +1,135 @@
/*
* 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.command.registry;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* This registry class allows for registration and unregistration of a certain type. This is mainly designed for use by
* event handlers where newly registered ones are encountered first during iteration and can therefore override older
* ones. In Baritone, this is used for commands and argument parsers so that mods and addons can extend Baritone's
* functionality without resorting to hacks, wrappers, or mixins.
*
* @param <V> The entry type that will be stored in this registry. This can be anything, really - preferably anything
* that works as a HashMap key, as that's what's used to keep track of which entries are registered or not.
*/
public class Registry<V> {
/**
* An internal linked list of all the entries that are currently registered. This is a linked list so that entries
* can be inserted at the beginning, which means that newer entries are encountered first during iteration. This is
* an important property of the registry that makes it more useful than a simple list, and also the reason it does
* not just use a map.
*/
private final Deque<V> _entries = new LinkedList<>();
/**
* A HashSet containing every entry currently registered. Entries are added to this set when something is registered
* and removed from the set when they are unregistered. An entry being present in this set indicates that it is
* currently registered, can be removed, and should not be reregistered until it is removed.
*/
private final Set<V> registered = new HashSet<>();
/**
* The collection of entries that are currently in this registry. This is a collection (and not a list) because,
* internally, entries are stored in a linked list, which is not the same as a normal list.
*/
public final Collection<V> entries = Collections.unmodifiableCollection(_entries);
/**
* @param entry The entry to check.
* @return If this entry is currently registered in this registry.
*/
public boolean registered(V entry) {
return registered.contains(entry);
}
/**
* Ensures that the entry {@code entry} is registered.
*
* @param entry The entry to register.
* @return A boolean indicating whether or not this is a new registration. No matter the value of this boolean, the
* entry is always guaranteed to now be in this registry. This boolean simply indicates if the entry was <i>not</i>
* in the map prior to this method call.
*/
public boolean register(V entry) {
if (!registered(entry)) {
_entries.addFirst(entry);
registered.add(entry);
return true;
}
return false;
}
/**
* Unregisters this entry from this registry. After this method call, the entry is guaranteed to be removed from the
* registry, since each entry only ever appears once.
*
* @param entry The entry to unregister.
*/
public void unregister(V entry) {
if (registered(entry)) {
return;
}
_entries.remove(entry);
registered.remove(entry);
}
/**
* Returns an iterator that iterates over each entry in this registry, with the newest elements iterated over first.
* Internally, as new elements are prepended to the registry rather than appended to the end, this order is the best
* way to search through the registry if you want to discover newer items first.
*/
public Iterator<V> iterator() {
return _entries.iterator();
}
/**
* Returns an iterator that iterates over each entry in this registry, in the order they were added. Internally,
* this iterates through the registry backwards, as new elements are prepended to the registry rather than appended
* to the end. You should only do this when you need to, for example, list elements in order - it is almost always
* fine to simply use {@link Iterable#forEach(Consumer) forEach} on the {@link #entries} collection instead.
*/
public Iterator<V> descendingIterator() {
return _entries.descendingIterator();
}
/**
* Returns a stream that contains each entry in this registry, with the newest elements ordered first. Internally,
* as new elements are prepended to the registry rather than appended to the end, this order is the best way to
* search through the registry if you want to discover newer items first.
*/
public Stream<V> stream() {
return _entries.stream();
}
/**
* Returns a stream that returns each entry in this registry, in the order they were added. Internally, this orders
* the registry backwards, as new elements are prepended to the registry rather than appended to the end. You should
* only use this when you need to, for example, list elements in order - it is almost always fine to simply use the
* regular {@link #stream()} method instead.
*/
public Stream<V> descendingStream() {
return StreamSupport.stream(Spliterators.spliterator(
descendingIterator(),
_entries.size(),
Spliterator.SIZED | Spliterator.SUBSIZED
), false);
}
}

View File

@@ -0,0 +1,35 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events;
import baritone.api.event.events.type.Cancellable;
import baritone.api.event.events.type.Overrideable;
/**
* @author LoganDark
*/
public final class TabCompleteEvent extends Cancellable {
public final String prefix;
public String[] completions;
public TabCompleteEvent(String prefix) {
this.prefix = prefix;
this.completions = null;
}
}

View File

@@ -0,0 +1,53 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.event.events.type;
/**
* @author LoganDark
*/
public class Overrideable<T> {
private T value;
private boolean modified;
public Overrideable(T current) {
value = current;
}
public T get() {
return value;
}
public void set(T newValue) {
value = newValue;
modified = true;
}
public boolean wasModified() {
return modified;
}
@Override
public String toString() {
return String.format(
"Overrideable{modified=%b,value=%s}",
modified,
value.toString()
);
}
}

View File

@@ -39,6 +39,9 @@ public interface AbstractGameEventListener extends IGameEventListener {
@Override
default void onSendChatMessage(ChatEvent event) {}
@Override
default void onPreTabComplete(TabCompleteEvent event) {}
@Override
default void onChunkEvent(ChunkEvent event) {}

View File

@@ -18,12 +18,11 @@
package baritone.api.event.listener;
import baritone.api.event.events.*;
import io.netty.util.concurrent.GenericFutureListener;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.GuiGameOver;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.entity.Entity;
import net.minecraft.network.Packet;
@@ -45,7 +44,7 @@ public interface IGameEventListener {
* Run once per game tick from before and after the player rotation is sent to the server.
*
* @param event The event
* @see EntityPlayerSP#onUpdate()
* @see EntityPlayerSP#tick()
*/
void onPlayerUpdate(PlayerUpdateEvent event);
@@ -57,18 +56,22 @@ public interface IGameEventListener {
*/
void onSendChatMessage(ChatEvent event);
/**
* Runs whenever the client player tries to tab complete in chat.
*
* @param event The event
*/
void onPreTabComplete(TabCompleteEvent event);
/**
* Runs before and after whenever a chunk is either loaded, unloaded, or populated.
*
* @param event The event
* @see WorldClient#doPreChunk(int, int, boolean)
*/
void onChunkEvent(ChunkEvent event);
/**
* Runs once per world render pass. Two passes are made when {@link GameSettings#anaglyph} is on.
* <p>
* <b>Note:</b> {@link GameSettings#anaglyph} has been removed in Minecraft 1.13
* Runs once per world render pass.
*
* @param event The event
*/
@@ -78,7 +81,7 @@ public interface IGameEventListener {
* Runs before and after whenever a new world is loaded
*
* @param event The event
* @see Minecraft#loadWorld(WorldClient, String)
* @see Minecraft#loadWorld(WorldClient, GuiScreen)
*/
void onWorldEvent(WorldEvent event);
@@ -87,7 +90,6 @@ public interface IGameEventListener {
*
* @param event The event
* @see Packet
* @see GenericFutureListener
*/
void onSendPacket(PacketEvent event);
@@ -96,7 +98,6 @@ public interface IGameEventListener {
*
* @param event The event
* @see Packet
* @see GenericFutureListener
*/
void onReceivePacket(PacketEvent event);
@@ -110,10 +111,10 @@ public interface IGameEventListener {
void onPlayerRotationMove(RotationMoveEvent event);
/**
* Called whenever the sprint keybind state is checked in {@link EntityPlayerSP#onLivingUpdate}
* Called whenever the sprint keybind state is checked in {@link EntityPlayerSP#livingTick}
*
* @param event The event
* @see EntityPlayerSP#onLivingUpdate()
* @see EntityPlayerSP#livingTick()
*/
void onPlayerSprintState(SprintStateEvent event);

View File

@@ -17,6 +17,7 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import baritone.api.utils.interfaces.IGoalRenderPos;
import net.minecraft.util.math.BlockPos;
@@ -67,7 +68,12 @@ public class GoalBlock implements Goal, IGoalRenderPos {
@Override
public String toString() {
return "GoalBlock{x=" + x + ",y=" + y + ",z=" + z + "}";
return String.format(
"GoalBlock{x=%s,y=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z)
);
}
/**

View File

@@ -17,6 +17,7 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import baritone.api.utils.interfaces.IGoalRenderPos;
import net.minecraft.util.math.BlockPos;
@@ -61,6 +62,11 @@ public class GoalGetToBlock implements Goal, IGoalRenderPos {
@Override
public String toString() {
return "GoalGetToBlock{x=" + x + ",y=" + y + ",z=" + z + "}";
return String.format(
"GoalGetToBlock{x=%s,y=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z)
);
}
}

View File

@@ -0,0 +1,52 @@
/*
* 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.pathing.goals;
/**
* Invert any goal.
* <p>
* In the old chat control system, #invert just tried to pick a {@link GoalRunAway} that <i>effectively</i> inverted the
* current goal. This goal just reverses the heuristic to act as a TRUE invert. Inverting a Y level? Baritone tries to
* get away from that Y level. Inverting a GoalBlock? Baritone will try to make distance whether it's in the X, Y or Z
* directions. And of course, you can always invert a GoalXZ.
*
* @author LoganDark
*/
public class GoalInverted implements Goal {
public final Goal origin;
public GoalInverted(Goal origin) {
this.origin = origin;
}
@Override
public boolean isInGoal(int x, int y, int z) {
return false;
}
@Override
public double heuristic(int x, int y, int z) {
return -origin.heuristic(x, y, z);
}
@Override
public String toString() {
return String.format("GoalInverted{%s}", origin.toString());
}
}

View File

@@ -17,10 +17,12 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import baritone.api.utils.interfaces.IGoalRenderPos;
import net.minecraft.util.math.BlockPos;
public class GoalNear implements Goal, IGoalRenderPos {
private final int x;
private final int y;
private final int z;
@@ -56,11 +58,12 @@ public class GoalNear implements Goal, IGoalRenderPos {
@Override
public String toString() {
return "GoalNear{" +
"x=" + x +
", y=" + y +
", z=" + z +
", rangeSq=" + rangeSq +
"}";
return String.format(
"GoalNear{x=%s, y=%s, z=%s, rangeSq=%d}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z),
rangeSq
);
}
}

View File

@@ -17,6 +17,7 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import net.minecraft.util.math.BlockPos;
import java.util.Arrays;
@@ -82,7 +83,11 @@ public class GoalRunAway implements Goal {
@Override
public String toString() {
if (maintainY != null) {
return "GoalRunAwayFromMaintainY y=" + maintainY + ", " + Arrays.asList(from);
return String.format(
"GoalRunAwayFromMaintainY y=%s, %s",
SettingsUtil.maybeCensor(maintainY),
Arrays.asList(from)
);
} else {
return "GoalRunAwayFrom" + Arrays.asList(from);
}

View File

@@ -17,6 +17,7 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
@@ -24,6 +25,7 @@ import net.minecraft.util.math.BlockPos;
* Dig a tunnel in a certain direction, but if you have to deviate from the path, go back to where you started
*/
public class GoalStrictDirection implements Goal {
public final int x;
public final int y;
public final int z;
@@ -64,12 +66,13 @@ public class GoalStrictDirection implements Goal {
@Override
public String toString() {
return "GoalStrictDirection{" +
"x=" + x +
", y=" + y +
", z=" + z +
", dx=" + dx +
", dz=" + dz +
"}";
return String.format(
"GoalStrictDirection{x=%s, y=%s, z=%s, dx=%s, dz=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z),
SettingsUtil.maybeCensor(dx),
SettingsUtil.maybeCensor(dz)
);
}
}

View File

@@ -17,6 +17,7 @@
package baritone.api.pathing.goals;
import baritone.api.utils.SettingsUtil;
import baritone.api.utils.interfaces.IGoalRenderPos;
import net.minecraft.util.math.BlockPos;
@@ -73,6 +74,11 @@ public class GoalTwoBlocks implements Goal, IGoalRenderPos {
@Override
public String toString() {
return "GoalTwoBlocks{x=" + x + ",y=" + y + ",z=" + z + "}";
return String.format(
"GoalTwoBlocks{x=%s,y=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z)
);
}
}

View File

@@ -18,6 +18,8 @@
package baritone.api.pathing.goals;
import baritone.api.BaritoneAPI;
import baritone.api.utils.BetterBlockPos;
import baritone.api.utils.SettingsUtil;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
@@ -45,6 +47,11 @@ public class GoalXZ implements Goal {
this.z = z;
}
public GoalXZ(BetterBlockPos pos) {
this.x = pos.x;
this.z = pos.z;
}
@Override
public boolean isInGoal(int x, int y, int z) {
return x == this.x && z == this.z;
@@ -59,7 +66,11 @@ public class GoalXZ implements Goal {
@Override
public String toString() {
return "GoalXZ{x=" + x + ",z=" + z + "}";
return String.format(
"GoalXZ{x=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(z)
);
}
public static double calculate(double xDiff, double zDiff) {
@@ -87,7 +98,7 @@ public class GoalXZ implements Goal {
float theta = (float) Math.toRadians(yaw);
double x = origin.x - MathHelper.sin(theta) * distance;
double z = origin.z + MathHelper.cos(theta) * distance;
return new GoalXZ((int) x, (int) z);
return new GoalXZ(MathHelper.floor(x), MathHelper.floor(z));
}
public int getX() {

View File

@@ -18,6 +18,7 @@
package baritone.api.pathing.goals;
import baritone.api.pathing.movement.ActionCosts;
import baritone.api.utils.SettingsUtil;
/**
* Useful for mining (getting to diamond / iron level)
@@ -59,6 +60,9 @@ public class GoalYLevel implements Goal, ActionCosts {
@Override
public String toString() {
return "GoalYLevel{y=" + level + "}";
return String.format(
"GoalYLevel{y=%s}",
SettingsUtil.maybeCensor(level)
);
}
}

View File

@@ -17,12 +17,14 @@
package baritone.api.process;
import baritone.api.utils.ISchematic;
import baritone.api.schematic.ISchematic;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i;
import java.io.File;
import java.util.List;
/**
* @author Brady
@@ -50,13 +52,24 @@ public interface IBuilderProcess extends IBaritoneProcess {
boolean build(String name, File schematic, Vec3i origin);
default boolean build(String schematicFile, BlockPos origin) {
File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile);
File file = new File(new File(Minecraft.getInstance().gameDir, "schematics"), schematicFile);
return build(schematicFile, file, origin);
}
void buildOpenSchematic();
void pause();
boolean isPaused();
void resume();
void clearArea(BlockPos corner1, BlockPos corner2);
/**
* @return A list of block states that are estimated to be placeable by this builder process. You can use this in
* schematics, for example, to pick a state that the builder process will be happy with, because any variation will
* cause it to give up. This is updated every tick, but only while the builder process is active.
*/
List<IBlockState> getApproxPlaceable();
}

View File

@@ -20,6 +20,7 @@ package baritone.api.process;
import java.nio.file.Path;
public interface IExploreProcess extends IBaritoneProcess {
void explore(int centerX, int centerZ);
void applyJsonFilter(Path path, boolean invert) throws Exception;

View File

@@ -18,5 +18,6 @@
package baritone.api.process;
public interface IFarmProcess extends IBaritoneProcess {
void farm();
}

View File

@@ -17,6 +17,7 @@
package baritone.api.process;
import baritone.api.utils.BlockOptionalMeta;
import net.minecraft.block.Block;
/**
@@ -24,7 +25,11 @@ import net.minecraft.block.Block;
*/
public interface IGetToBlockProcess extends IBaritoneProcess {
void getToBlock(Block block);
void getToBlock(BlockOptionalMeta block);
default void getToBlock(Block block) {
getToBlock(new BlockOptionalMeta(block));
}
boolean blacklistClosest();
}

View File

@@ -17,8 +17,12 @@
package baritone.api.process;
import baritone.api.utils.BlockOptionalMeta;
import baritone.api.utils.BlockOptionalMetaLookup;
import net.minecraft.block.Block;
import java.util.stream.Stream;
/**
* @author Brady
* @since 9/23/2018
@@ -28,9 +32,9 @@ public interface IMineProcess extends IBaritoneProcess {
/**
* Begin to search for and mine the specified blocks until
* the number of specified items to get from the blocks that
* are mined. This is based on the first target block to mine.
* are mined.
*
* @param quantity The number of items to get from blocks mined
* @param quantity The total number of items to get
* @param blocks The blocks to mine
*/
void mineByName(int quantity, String... blocks);
@@ -41,9 +45,18 @@ public interface IMineProcess extends IBaritoneProcess {
* are mined. This is based on the first target block to mine.
*
* @param quantity The number of items to get from blocks mined
* @param blocks The blocks to mine
* @param filter The blocks to mine
*/
void mine(int quantity, Block... blocks);
void mine(int quantity, BlockOptionalMetaLookup filter);
/**
* Begin to search for and mine the specified blocks.
*
* @param filter The blocks to mine
*/
default void mine(BlockOptionalMetaLookup filter) {
mine(0, filter);
}
/**
* Begin to search for and mine the specified blocks.
@@ -54,6 +67,38 @@ public interface IMineProcess extends IBaritoneProcess {
mineByName(0, blocks);
}
/**
* Begin to search for and mine the specified blocks.
*
* @param boms The blocks to mine
*/
default void mine(int quantity, BlockOptionalMeta... boms) {
mine(quantity, new BlockOptionalMetaLookup(boms));
}
/**
* Begin to search for and mine the specified blocks.
*
* @param boms The blocks to mine
*/
default void mine(BlockOptionalMeta... boms) {
mine(0, boms);
}
/**
* Begin to search for and mine the specified blocks.
*
* @param quantity The total number of items to get
* @param blocks The blocks to mine
*/
default void mine(int quantity, Block... blocks) {
mine(quantity, new BlockOptionalMetaLookup(
Stream.of(blocks)
.map(BlockOptionalMeta::new)
.toArray(BlockOptionalMeta[]::new)
));
}
/**
* Begin to search for and mine the specified blocks.
*

View File

@@ -0,0 +1,46 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.schematic;
public abstract class AbstractSchematic implements ISchematic {
protected int x;
protected int y;
protected int z;
public AbstractSchematic(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int widthX() {
return x;
}
@Override
public int heightY() {
return y;
}
@Override
public int lengthZ() {
return z;
}
}

View File

@@ -0,0 +1,74 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.schematic;
import net.minecraft.block.state.IBlockState;
import java.util.ArrayList;
import java.util.List;
public class CompositeSchematic extends AbstractSchematic {
private final List<CompositeSchematicEntry> schematics;
private CompositeSchematicEntry[] schematicArr;
private void recalcArr() {
schematicArr = schematics.toArray(new CompositeSchematicEntry[0]);
for (CompositeSchematicEntry entry : schematicArr) {
this.x = Math.max(x, entry.x + entry.schematic.widthX());
this.y = Math.max(y, entry.y + entry.schematic.heightY());
this.z = Math.max(z, entry.z + entry.schematic.lengthZ());
}
}
public CompositeSchematic(int x, int y, int z) {
super(x, y, z);
schematics = new ArrayList<>();
recalcArr();
}
public void put(ISchematic extra, int x, int y, int z) {
schematics.add(new CompositeSchematicEntry(extra, x, y, z));
recalcArr();
}
private CompositeSchematicEntry getSchematic(int x, int y, int z, IBlockState currentState) {
for (CompositeSchematicEntry entry : schematicArr) {
if (x >= entry.x && y >= entry.y && z >= entry.z &&
entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState)) {
return entry;
}
}
return null;
}
@Override
public boolean inSchematic(int x, int y, int z, IBlockState currentState) {
CompositeSchematicEntry entry = getSchematic(x, y, z, currentState);
return entry != null && entry.schematic.inSchematic(x - entry.x, y - entry.y, z - entry.z, currentState);
}
@Override
public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) {
CompositeSchematicEntry entry = getSchematic(x, y, z, current);
if (entry == null) {
throw new IllegalStateException("couldn't find schematic for this position");
}
return entry.schematic.desiredState(x - entry.x, y - entry.y, z - entry.z, current, approxPlaceable);
}
}

View File

@@ -0,0 +1,33 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.schematic;
public class CompositeSchematicEntry {
public final ISchematic schematic;
public final int x;
public final int y;
public final int z;
public CompositeSchematicEntry(ISchematic schematic, int x, int y, int z) {
this.schematic = schematic;
this.x = x;
this.y = y;
this.z = z;
}
}

View File

@@ -0,0 +1,53 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.schematic;
import baritone.api.utils.BlockOptionalMeta;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import java.util.List;
public class FillSchematic extends AbstractSchematic {
private final BlockOptionalMeta bom;
public FillSchematic(int x, int y, int z, BlockOptionalMeta bom) {
super(x, y, z);
this.bom = bom;
}
public BlockOptionalMeta getBom() {
return bom;
}
@Override
public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) {
if (bom.matches(current)) {
return current;
} else if (current.getBlock() != Blocks.AIR) {
return Blocks.AIR.getDefaultState();
}
for (IBlockState placeable : approxPlaceable) {
if (bom.matches(placeable)) {
return placeable;
}
}
return bom.getAnyBlockState();
}
}

View File

@@ -15,14 +15,16 @@
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.utils;
package baritone.api.schematic;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.EnumFacing;
import java.util.List;
/**
* Basic representation of a schematic. Provides the dimensions and
* the desired statefor a given position relative to the origin.
* Basic representation of a schematic. Provides the dimensions and the desired state for a given position relative to
* the origin.
*
* @author leijurv
*/
@@ -36,12 +38,13 @@ public interface ISchematic {
* 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
* @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
* @param currentState The current state of that block in the world, or null
* @return Whether or not the specified position is within the bounds of this schematic
*/
default boolean inSchematic(int x, int y, int z) {
default boolean inSchematic(int x, int y, int z, IBlockState currentState) {
return x >= 0 && x < widthX() && y >= 0 && y < heightY() && z >= 0 && z < lengthZ();
}
@@ -61,12 +64,14 @@ public interface ISchematic {
/**
* 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
* @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
* @param current The current state of that block in the world, or null
* @param approxPlaceable The list of blockstates estimated to be placeable
* @return The desired block state at the specified position
*/
IBlockState desiredState(int x, int y, int z);
IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable);
/**
* @return The width (X axis length) of this schematic
@@ -82,4 +87,4 @@ public interface ISchematic {
* @return The length (Z axis length) of this schematic
*/
int lengthZ();
}
}

View File

@@ -0,0 +1,44 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.schematic;
import net.minecraft.block.state.IBlockState;
import java.util.List;
public abstract class MaskSchematic extends AbstractSchematic {
private final ISchematic schematic;
public MaskSchematic(ISchematic schematic) {
super(schematic.widthX(), schematic.heightY(), schematic.lengthZ());
this.schematic = schematic;
}
protected abstract boolean partOfMask(int x, int y, int z, IBlockState currentState);
@Override
public boolean inSchematic(int x, int y, int z, IBlockState currentState) {
return schematic.inSchematic(x, y, z, currentState) && partOfMask(x, y, z, currentState);
}
@Override
public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) {
return schematic.desiredState(x, y, z, current, approxPlaceable);
}
}

View File

@@ -0,0 +1,41 @@
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.api.schematic;
import baritone.api.utils.BlockOptionalMetaLookup;
import net.minecraft.block.state.IBlockState;
public class ReplaceSchematic extends MaskSchematic {
private final BlockOptionalMetaLookup filter;
private final Boolean[][][] cache;
public ReplaceSchematic(ISchematic schematic, BlockOptionalMetaLookup filter) {
super(schematic);
this.filter = filter;
this.cache = new Boolean[widthX()][heightY()][lengthZ()];
}
@Override
protected boolean partOfMask(int x, int y, int z, IBlockState currentState) {
if (cache[x][y][z] == null) {
cache[x][y][z] = filter.has(currentState);
}
return cache[x][y][z];
}
}

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.api.schematic;
import net.minecraft.block.state.IBlockState;
public class ShellSchematic extends MaskSchematic {
public ShellSchematic(ISchematic schematic) {
super(schematic);
}
@Override
protected boolean partOfMask(int x, int y, int z, IBlockState currentState) {
return x == 0 || y == 0 || z == 0 || x == widthX() - 1 || y == heightY() - 1 || z == lengthZ() - 1;
}
}

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.api.schematic;
import net.minecraft.block.state.IBlockState;
public class WallsSchematic extends MaskSchematic {
public WallsSchematic(ISchematic schematic) {
super(schematic);
}
@Override
protected boolean partOfMask(int x, int y, int z, IBlockState currentState) {
return x == 0 || z == 0 || x == widthX() - 1 || z == lengthZ() - 1;
}
}

View File

@@ -0,0 +1,91 @@
/*
* 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.selection;
import baritone.api.utils.BetterBlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.Vec3i;
/**
* A selection is an immutable object representing the current selection. The selection is commonly used for certain
* types of build commands, however it can be used for anything.
*/
public interface ISelection {
/**
* @return The first corner of this selection. This is meant to preserve the user's original first corner.
*/
BetterBlockPos pos1();
/**
* @return The second corner of this selection. This is meant to preserve the user's original second corner.
*/
BetterBlockPos pos2();
/**
* @return The {@link BetterBlockPos} with the lowest x, y, and z position in the selection.
*/
BetterBlockPos min();
/**
* @return The opposite corner from the {@link #min()}.
*/
BetterBlockPos max();
/**
* @return The size of this ISelection.
*/
Vec3i size();
/**
* @return An {@link AxisAlignedBB} encompassing all blocks in this selection.
*/
AxisAlignedBB aabb();
/**
* Returns a new {@link ISelection} expanded in the specified direction by the specified number of blocks.
*
* @param direction The direction to expand the selection.
* @param blocks How many blocks to expand it.
* @return A new selection, expanded as specified.
*/
ISelection expand(EnumFacing direction, int blocks);
/**
* Returns a new {@link ISelection} contracted in the specified direction by the specified number of blocks.
* <p>
* Note that, for example, if the direction specified is UP, the bottom of the selection will be shifted up. If it
* is DOWN, the top of the selection will be shifted down.
*
* @param direction The direction to contract the selection.
* @param blocks How many blocks to contract it.
* @return A new selection, contracted as specified.
*/
ISelection contract(EnumFacing direction, int blocks);
/**
* Returns a new {@link ISelection} shifted in the specified direction by the specified number of blocks. This moves
* the whole selection.
*
* @param direction The direction to shift the selection.
* @param blocks How many blocks to shift it.
* @return A new selection, shifted as specified.
*/
ISelection shift(EnumFacing direction, int blocks);
}

View File

@@ -0,0 +1,116 @@
/*
* 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.selection;
import baritone.api.utils.BetterBlockPos;
import net.minecraft.util.EnumFacing;
/**
* The selection manager handles setting Baritone's selections. You can set the selection here, as well as retrieving
* the current selection.
*/
public interface ISelectionManager {
/**
* Adds a new selection. The added selection is returned.
*
* @param selection The new selection to add.
*/
ISelection addSelection(ISelection selection);
/**
* Adds a new {@link ISelection} constructed from the given block positions. The new selection is returned.
*
* @param pos1 One corner of the selection
* @param pos2 The new corner of the selection
*/
ISelection addSelection(BetterBlockPos pos1, BetterBlockPos pos2);
/**
* Removes the selection from the current selections.
*
* @param selection The selection to remove.
* @return The removed selection.
*/
ISelection removeSelection(ISelection selection);
/**
* Removes all selections.
*
* @return The selections that were removed, sorted from oldest to newest..
*/
ISelection[] removeAllSelections();
/**
* @return The current selections, sorted from oldest to newest.
*/
ISelection[] getSelections();
/**
* For anything expecting only one selection, this method is provided. However, to enforce multi-selection support,
* this method will only return a selection if there is ONLY one.
*
* @return The only selection, or null if there isn't only one.
*/
ISelection getOnlySelection();
/**
* This method will always return the last selection. ONLY use this if you want to, for example, modify the most
* recent selection based on user input. ALWAYS use {@link #getOnlySelection()} or, ideally,
* {@link #getSelections()} for retrieving the content of selections.
*
* @return The last selection, or null if it doesn't exist.
*/
ISelection getLastSelection();
/**
* Replaces the specified {@link ISelection} with one expanded in the specified direction by the specified number of
* blocks. Returns the new selection.
*
* @param selection The selection to expand.
* @param direction The direction to expand the selection.
* @param blocks How many blocks to expand it.
* @return The new selection, expanded as specified.
*/
ISelection expand(ISelection selection, EnumFacing direction, int blocks);
/**
* Replaces the specified {@link ISelection} with one contracted in the specified direction by the specified number
* of blocks.
* <p>
* Note that, for example, if the direction specified is UP, the bottom of the selection will be shifted up. If it
* is DOWN, the top of the selection will be shifted down.
*
* @param selection The selection to contract.
* @param direction The direction to contract the selection.
* @param blocks How many blocks to contract it.
* @return The new selection, contracted as specified.
*/
ISelection contract(ISelection selection, EnumFacing direction, int blocks);
/**
* Replaces the specified {@link ISelection} with one shifted in the specified direction by the specified number of
* blocks. This moves the whole selection.
*
* @param selection The selection to shift.
* @param direction The direction to shift the selection.
* @param blocks How many blocks to shift it.
* @return The new selection, shifted as specified.
*/
ISelection shift(ISelection selection, EnumFacing direction, int blocks);
}

View File

@@ -22,6 +22,8 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3i;
import javax.annotation.Nonnull;
/**
* A better BlockPos that has fewer hash collisions (and slightly more performant offsets)
* <p>
@@ -32,6 +34,9 @@ import net.minecraft.util.math.Vec3i;
* @author leijurv
*/
public final class BetterBlockPos extends BlockPos {
public static final BetterBlockPos ORIGIN = new BetterBlockPos(0, 0, 0);
public final int x;
public final int y;
public final int z;
@@ -51,6 +56,20 @@ public final class BetterBlockPos extends BlockPos {
this(pos.getX(), pos.getY(), pos.getZ());
}
/**
* Like constructor but returns null if pos is null, good if you just need to possibly censor coordinates
*
* @param pos The BlockPos, possibly null, to convert
* @return A BetterBlockPos or null if pos was null
*/
public static BetterBlockPos from(BlockPos pos) {
if (pos == null) {
return null;
}
return new BetterBlockPos(pos);
}
@Override
public int hashCode() {
return (int) longHash(x, y, z);
@@ -182,4 +201,15 @@ public final class BetterBlockPos extends BlockPos {
public BetterBlockPos west(int amt) {
return amt == 0 ? this : new BetterBlockPos(x - amt, y, z);
}
@Override
@Nonnull
public String toString() {
return String.format(
"BetterBlockPos{x=%s,y=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z)
);
}
}

View File

@@ -0,0 +1,270 @@
/*
* 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 baritone.api.utils.accessor.IItemStack;
import com.google.common.collect.ImmutableSet;
import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.state.IProperty;
import net.minecraft.state.properties.*;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.function.Consumer;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class BlockOptionalMeta {
private final Block block;
private final Set<IBlockState> blockstates;
private final ImmutableSet<Integer> stateHashes;
private final ImmutableSet<Integer> stackHashes;
private static final Pattern pattern = Pattern.compile("^(.+?)(?::(\\d+))?$");
private static final Map<Object, Object> normalizations;
public BlockOptionalMeta(@Nonnull Block block) {
this.block = block;
this.blockstates = getStates(block);
this.stateHashes = getStateHashes(blockstates);
this.stackHashes = getStackHashes(blockstates);
}
public BlockOptionalMeta(@Nonnull String selector) {
Matcher matcher = pattern.matcher(selector);
if (!matcher.find()) {
throw new IllegalArgumentException("invalid block selector");
}
MatchResult matchResult = matcher.toMatchResult();
ResourceLocation id = new ResourceLocation(matchResult.group(1));
if (!IRegistry.BLOCK.containsKey(id)) {
throw new IllegalArgumentException("Invalid block ID");
}
block = IRegistry.BLOCK.get(id);
blockstates = getStates(block);
stateHashes = getStateHashes(blockstates);
stackHashes = getStackHashes(blockstates);
}
static {
Map<Object, Object> _normalizations = new HashMap<>();
Consumer<Enum> put = instance -> _normalizations.put(instance.getClass(), instance);
put.accept(EnumFacing.NORTH);
put.accept(EnumFacing.Axis.Y);
put.accept(Half.BOTTOM);
put.accept(StairsShape.STRAIGHT);
put.accept(AttachFace.FLOOR);
put.accept(DoubleBlockHalf.UPPER);
put.accept(SlabType.BOTTOM);
put.accept(DoorHingeSide.LEFT);
put.accept(BedPart.HEAD);
put.accept(RailShape.NORTH_SOUTH);
_normalizations.put(BlockBanner.ROTATION, 0);
_normalizations.put(BlockBed.OCCUPIED, false);
_normalizations.put(BlockBrewingStand.HAS_BOTTLE[0], false);
_normalizations.put(BlockBrewingStand.HAS_BOTTLE[1], false);
_normalizations.put(BlockBrewingStand.HAS_BOTTLE[2], false);
_normalizations.put(BlockButton.POWERED, false);
// _normalizations.put(BlockCactus.AGE, 0);
// _normalizations.put(BlockCauldron.LEVEL, 0);
// _normalizations.put(BlockChorusFlower.AGE, 0);
_normalizations.put(BlockChorusPlant.NORTH, false);
_normalizations.put(BlockChorusPlant.EAST, false);
_normalizations.put(BlockChorusPlant.SOUTH, false);
_normalizations.put(BlockChorusPlant.WEST, false);
_normalizations.put(BlockChorusPlant.UP, false);
_normalizations.put(BlockChorusPlant.DOWN, false);
// _normalizations.put(BlockCocoa.AGE, 0);
// _normalizations.put(BlockCrops.AGE, 0);
_normalizations.put(BlockDirtSnowy.SNOWY, false);
_normalizations.put(BlockDoor.OPEN, false);
_normalizations.put(BlockDoor.POWERED, false);
// _normalizations.put(BlockFarmland.MOISTURE, 0);
_normalizations.put(BlockFence.NORTH, false);
_normalizations.put(BlockFence.EAST, false);
_normalizations.put(BlockFence.WEST, false);
_normalizations.put(BlockFence.SOUTH, false);
// _normalizations.put(BlockFenceGate.POWERED, false);
// _normalizations.put(BlockFenceGate.IN_WALL, false);
_normalizations.put(BlockFire.AGE, 0);
_normalizations.put(BlockFire.NORTH, false);
_normalizations.put(BlockFire.EAST, false);
_normalizations.put(BlockFire.SOUTH, false);
_normalizations.put(BlockFire.WEST, false);
_normalizations.put(BlockFire.UP, false);
// _normalizations.put(BlockFrostedIce.AGE, 0);
_normalizations.put(BlockGrass.SNOWY, false);
// _normalizations.put(BlockHopper.ENABLED, true);
// _normalizations.put(BlockLever.POWERED, false);
// _normalizations.put(BlockLiquid.LEVEL, 0);
// _normalizations.put(BlockMycelium.SNOWY, false);
// _normalizations.put(BlockNetherWart.AGE, false);
_normalizations.put(BlockLeaves.DISTANCE, false);
// _normalizations.put(BlockLeaves.DECAYABLE, false);
// _normalizations.put(BlockObserver.POWERED, false);
_normalizations.put(BlockPane.NORTH, false);
_normalizations.put(BlockPane.EAST, false);
_normalizations.put(BlockPane.WEST, false);
_normalizations.put(BlockPane.SOUTH, false);
// _normalizations.put(BlockPistonBase.EXTENDED, false);
// _normalizations.put(BlockPressurePlate.POWERED, false);
// _normalizations.put(BlockPressurePlateWeighted.POWER, false);
// _normalizations.put(BlockRailDetector.POWERED, false);
// _normalizations.put(BlockRailPowered.POWERED, false);
_normalizations.put(BlockRedstoneWire.NORTH, false);
_normalizations.put(BlockRedstoneWire.EAST, false);
_normalizations.put(BlockRedstoneWire.SOUTH, false);
_normalizations.put(BlockRedstoneWire.WEST, false);
// _normalizations.put(BlockReed.AGE, false);
_normalizations.put(BlockSapling.STAGE, 0);
_normalizations.put(BlockStandingSign.ROTATION, 0);
_normalizations.put(BlockStem.AGE, 0);
_normalizations.put(BlockTripWire.NORTH, false);
_normalizations.put(BlockTripWire.EAST, false);
_normalizations.put(BlockTripWire.WEST, false);
_normalizations.put(BlockTripWire.SOUTH, false);
_normalizations.put(BlockVine.NORTH, false);
_normalizations.put(BlockVine.EAST, false);
_normalizations.put(BlockVine.SOUTH, false);
_normalizations.put(BlockVine.WEST, false);
_normalizations.put(BlockVine.UP, false);
_normalizations.put(BlockWall.UP, false);
_normalizations.put(BlockWall.NORTH, false);
_normalizations.put(BlockWall.EAST, false);
_normalizations.put(BlockWall.WEST, false);
_normalizations.put(BlockWall.SOUTH, false);
normalizations = Collections.unmodifiableMap(_normalizations);
}
private static <C extends Comparable<C>, P extends IProperty<C>> P castToIProperty(Object value) {
//noinspection unchecked
return (P) value;
}
private static <C extends Comparable<C>, P extends IProperty<C>> C castToIPropertyValue(P iproperty, Object value) {
//noinspection unchecked
return (C) value;
}
public static IBlockState normalize(IBlockState state) {
IBlockState newState = state;
for (IProperty<?> property : state.getProperties()) {
Class<?> valueClass = property.getValueClass();
if (normalizations.containsKey(property)) {
try {
newState = newState.with(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(property))
);
} catch (IllegalArgumentException ignored) {}
} else if (normalizations.containsKey(state.get(property))) {
try {
newState = newState.with(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(state.get(property)))
);
} catch (IllegalArgumentException ignored) {}
} else if (normalizations.containsKey(valueClass)) {
try {
newState = newState.with(
castToIProperty(property),
castToIPropertyValue(property, normalizations.get(valueClass))
);
} catch (IllegalArgumentException ignored) {}
}
}
return newState;
}
public static int stateMeta(IBlockState state) {
return state.hashCode();
}
private static Set<IBlockState> getStates(@Nonnull Block block) {
return new HashSet<>(block.getStateContainer().getValidStates());
}
private static ImmutableSet<Integer> getStateHashes(Set<IBlockState> blockstates) {
return ImmutableSet.copyOf(
blockstates.stream()
.map(IBlockState::hashCode)
.toArray(Integer[]::new)
);
}
private static ImmutableSet<Integer> getStackHashes(Set<IBlockState> blockstates) {
//noinspection ConstantConditions
return ImmutableSet.copyOf(
blockstates.stream()
.map(state -> new ItemStack(
state.getBlock().getItemDropped(state, null, null, 0).asItem(),
1
))
.map(stack -> ((IItemStack) (Object) stack).getBaritoneHash())
.toArray(Integer[]::new)
);
}
public Block getBlock() {
return block;
}
public boolean matches(@Nonnull Block block) {
return block == this.block;
}
public boolean matches(@Nonnull IBlockState blockstate) {
Block block = blockstate.getBlock();
return block == this.block && stateHashes.contains(blockstate.hashCode());
}
public boolean matches(ItemStack stack) {
//noinspection ConstantConditions
int hash = ((IItemStack) (Object) stack).getBaritoneHash();
hash -= stack.getDamage();
return stackHashes.contains(hash);
}
@Override
public String toString() {
return String.format("BlockOptionalMeta{block=%s}", block);
}
public IBlockState getAnyBlockState() {
if (blockstates.size() > 0) {
return blockstates.iterator().next();
}
return null;
}
}

View File

@@ -0,0 +1,95 @@
/*
* 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.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class BlockOptionalMetaLookup {
private final BlockOptionalMeta[] boms;
public BlockOptionalMetaLookup(BlockOptionalMeta... boms) {
this.boms = boms;
}
public BlockOptionalMetaLookup(Block... blocks) {
this.boms = Stream.of(blocks)
.map(BlockOptionalMeta::new)
.toArray(BlockOptionalMeta[]::new);
}
public BlockOptionalMetaLookup(List<Block> blocks) {
this.boms = blocks.stream()
.map(BlockOptionalMeta::new)
.toArray(BlockOptionalMeta[]::new);
}
public BlockOptionalMetaLookup(String... blocks) {
this.boms = Stream.of(blocks)
.map(BlockOptionalMeta::new)
.toArray(BlockOptionalMeta[]::new);
}
public boolean has(Block block) {
for (BlockOptionalMeta bom : boms) {
if (bom.getBlock() == block) {
return true;
}
}
return false;
}
public boolean has(IBlockState state) {
for (BlockOptionalMeta bom : boms) {
if (bom.matches(state)) {
return true;
}
}
return false;
}
public boolean has(ItemStack stack) {
for (BlockOptionalMeta bom : boms) {
if (bom.matches(stack)) {
return true;
}
}
return false;
}
public List<BlockOptionalMeta> blocks() {
return Arrays.asList(boms);
}
@Override
public String toString() {
return String.format(
"BlockOptionalMetaLookup{%s}",
Arrays.toString(boms)
);
}
}

View File

@@ -19,16 +19,17 @@ package baritone.api.utils;
import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class BlockUtils {
private static transient Map<String, Block> resourceCache = new HashMap<>();
public static String blockToString(Block block) {
ResourceLocation loc = Block.REGISTRY.getNameForObject(block);
ResourceLocation loc = IRegistry.BLOCK.getKey(block);
String name = loc.getPath(); // normally, only write the part after the minecraft:
if (!loc.getNamespace().equals("minecraft")) {
// Baritone is running on top of forge with mods installed, perhaps?
@@ -39,7 +40,11 @@ public class BlockUtils {
public static Block stringToBlockRequired(String name) {
Block block = stringToBlockNullable(name);
Objects.requireNonNull(block);
if (block == null) {
throw new IllegalArgumentException(String.format("Invalid block name %s", name));
}
return block;
}
@@ -52,7 +57,7 @@ public class BlockUtils {
if (resourceCache.containsKey(name)) {
return null; // cached as null
}
block = Block.getBlockFromName(name.contains(":") ? name : "minecraft:" + name);
block = IRegistry.BLOCK.get(ResourceLocation.tryCreate(name.contains(":") ? name : "minecraft:" + name));
Map<String, Block> copy = new HashMap<>(resourceCache); // read only copy is safe, wont throw concurrentmodification
copy.put(name, block);
resourceCache = copy;

View File

@@ -1,712 +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.api.utils;
import baritone.api.BaritoneAPI;
import baritone.api.IBaritone;
import baritone.api.Settings;
import baritone.api.behavior.IPathingBehavior;
import baritone.api.cache.IRememberedInventory;
import baritone.api.cache.IWaypoint;
import baritone.api.cache.Waypoint;
import baritone.api.event.events.ChatEvent;
import baritone.api.event.listener.AbstractGameEventListener;
import baritone.api.pathing.goals.*;
import baritone.api.process.IBaritoneProcess;
import baritone.api.process.ICustomGoalProcess;
import baritone.api.process.IGetToBlockProcess;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ChunkProviderClient;
import net.minecraft.crash.CrashReport;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ReportedException;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.Chunk;
import java.nio.file.Path;
import java.util.*;
public class ExampleBaritoneControl implements Helper, AbstractGameEventListener {
private static final String HELP_MSG =
"baritone - Output settings into chat\n" +
"settings - Same as baritone\n" +
"goal - Create a goal (one number is '<Y>', two is '<X> <Z>', three is '<X> <Y> <Z>, 'clear' to clear)\n" +
"path - Go towards goal\n" +
"repack - (debug) Repacks chunk cache\n" +
"rescan - (debug) Same as repack\n" +
"axis - Paths towards the closest axis or diagonal axis, at y=120\n" +
"cancel - Cancels current path\n" +
"forcecancel - sudo cancel (only use if very glitched, try toggling 'pause' first)\n" +
"gc - Calls System.gc();\n" +
"invert - Runs away from the goal instead of towards it\n" +
"follow - Follows a player 'follow username'\n" +
"reloadall - (debug) Reloads chunk cache\n" +
"saveall - (debug) Saves chunk cache\n" +
"find - (debug) outputs how many blocks of a certain type are within the cache\n" +
"mine - Paths to and mines specified blocks 'mine x_ore y_ore ...'\n" +
"thisway - Creates a goal X blocks where you're facing\n" +
"list - Lists waypoints under a category\n" +
"get - Same as list\n" +
"show - Same as list\n" +
"save - Saves a waypoint (works but don't try to make sense of it)\n" +
"delete - Deletes a waypoint\n" +
"goto - Paths towards specified block or waypoint\n" +
"spawn - Paths towards world spawn or your most recent bed right-click\n" +
"sethome - Sets \"home\"\n" +
"home - Paths towards \"home\" \n" +
"costs - (debug) all movement costs from current location\n" +
"damn - Daniel\n" +
"Go to https://github.com/cabaletta/baritone/blob/master/USAGE.md for more information";
private static final String COMMAND_PREFIX = "#";
public final IBaritone baritone;
public final IPlayerContext ctx;
public ExampleBaritoneControl(IBaritone baritone) {
this.baritone = baritone;
this.ctx = baritone.getPlayerContext();
baritone.getGameEventHandler().registerEventListener(this);
}
@Override
public void onSendChatMessage(ChatEvent event) {
String msg = event.getMessage();
if (BaritoneAPI.getSettings().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 (!BaritoneAPI.getSettings().chatControl.value && !BaritoneAPI.getSettings().removePrefix.value) {
return;
}
if (runCommand(msg)) {
event.cancel();
}
}
public boolean runCommand(String msg0) { // you may think this can be private, but impcat calls it from .b =)
String msg = msg0.toLowerCase(Locale.US).trim(); // don't reassign the argument LOL
IPathingBehavior pathingBehavior = baritone.getPathingBehavior();
ICustomGoalProcess customGoalProcess = baritone.getCustomGoalProcess();
List<Settings.Setting<Boolean>> toggleable = BaritoneAPI.getSettings().getAllValuesByType(Boolean.class);
for (Settings.Setting<Boolean> setting : toggleable) {
if (msg.equalsIgnoreCase(setting.getName())) {
setting.value ^= true;
logDirect("Toggled " + setting.getName() + " to " + setting.value);
SettingsUtil.save(BaritoneAPI.getSettings());
return true;
}
}
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(BaritoneAPI.getSettings())) {
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(BaritoneAPI.getSettings().allSettings.size(), (page + 1) * 10);
logDirect("Settings " + min + " to " + (max - 1) + ":");
for (int i = min; i < max; i++) {
logDirect(BaritoneAPI.getSettings().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 : BaritoneAPI.getSettings().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);
}
return true;
}
if (msg.contains(" ")) {
String settingName = msg.substring(0, msg.indexOf(' '));
String settingValue = msg.substring(msg.indexOf(' ') + 1);
Settings.Setting setting = BaritoneAPI.getSettings().byLowerName.get(settingName);
if (setting != null) {
if (settingValue.equals("reset")) {
logDirect("Resetting setting " + settingName + " to default value.");
setting.reset();
} else {
try {
SettingsUtil.parseAndApply(BaritoneAPI.getSettings(), settingName, settingValue);
} catch (Exception ex) {
logDirect("Unable to parse setting");
return true;
}
}
SettingsUtil.save(BaritoneAPI.getSettings());
logDirect(setting.toString());
return true;
}
}
if (BaritoneAPI.getSettings().byLowerName.containsKey(msg)) {
Settings.Setting<?> setting = BaritoneAPI.getSettings().byLowerName.get(msg);
logDirect(setting.toString());
return true;
}
if (msg.startsWith("goal")) {
String rest = msg.substring(4).trim();
Goal goal;
if (rest.equals("clear") || rest.equals("none")) {
goal = null;
} else {
String[] params = rest.split(" ");
if (params[0].equals("")) {
params = new String[]{};
}
goal = parseGoal(params);
if (goal == null) {
return true;
}
}
customGoalProcess.setGoal(goal);
logDirect("Goal: " + goal);
return true;
}
if (msg.equals("crash")) {
StringBuilder meme = new StringBuilder();
CrashReport rep = new CrashReport("Manually triggered debug crash", new Throwable());
mc.addGraphicsAndWorldToCrashReport(rep);
new ReportedException(rep).printStackTrace();
rep.getSectionsInStringBuilder(meme);
System.out.println(meme);
logDirect(meme.toString());
logDirect("ok");
return true;
}
if (msg.equals("path")) {
if (pathingBehavior.getGoal() == null) {
logDirect("No goal.");
} else if (pathingBehavior.getGoal().isInGoal(ctx.playerFeet())) {
logDirect("Already in goal");
} else if (pathingBehavior.isPathing()) {
logDirect("Currently executing a path. Please cancel it first.");
} else {
customGoalProcess.setGoalAndPath(pathingBehavior.getGoal());
}
return true;
}
/*if (msg.equals("fullpath")) {
if (pathingBehavior.getGoal() == null) {
logDirect("No goal.");
} else {
logDirect("Started segmented calculator");
SegmentedCalculator.calculateSegmentsThreaded(pathingBehavior.pathStart(), pathingBehavior.getGoal(), new CalculationContext(baritone, true), ipath -> {
logDirect("Found a path");
logDirect("Ends at " + ipath.getDest());
logDirect("Length " + ipath.length());
logDirect("Estimated time " + ipath.ticksRemainingFrom(0));
pathingBehavior.secretCursedFunctionDoNotCall(ipath); // it's okay when *I* do it
}, () -> {
logDirect("Path calculation failed, no path");
});
}
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) {
logDirect("No version detected. Either dev environment or broken install.");
} else {
logDirect("You are using Baritone v" + version);
}
return true;
}
if (msg.equals("repack") || msg.equals("rescan")) {
ChunkProviderClient cli = (ChunkProviderClient) ctx.world().getChunkProvider();
int playerChunkX = ctx.playerFeet().getX() >> 4;
int playerChunkZ = ctx.playerFeet().getZ() >> 4;
int count = 0;
for (int x = playerChunkX - 40; x <= playerChunkX + 40; x++) {
for (int z = playerChunkZ - 40; z <= playerChunkZ + 40; z++) {
Chunk chunk = cli.getLoadedChunk(x, z);
if (chunk != null) {
count++;
baritone.getWorldProvider().getCurrentWorld().getCachedWorld().queueForPacking(chunk);
}
}
}
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(Helper.mc.getRenderViewEntity())));
logDirect("Coming");
return true;
}
if (msg.equals("axis") || msg.equals("highway")) {
customGoalProcess.setGoalAndPath(new GoalAxis());
return true;
}
if (msg.equals("cancel") || msg.equals("stop")) {
pathingBehavior.cancelEverything();
logDirect("ok canceled");
return true;
}
if (msg.equals("forcecancel")) {
pathingBehavior.cancelEverything();
pathingBehavior.forceCancel();
logDirect("ok force canceled");
return true;
}
if (msg.equals("gc")) {
System.gc();
logDirect("Called System.gc();");
return true;
}
if (msg.equals("invert")) {
Goal goal = pathingBehavior.getGoal();
BlockPos runAwayFrom;
if (goal instanceof GoalXZ) {
runAwayFrom = new BlockPos(((GoalXZ) goal).getX(), 0, ((GoalXZ) goal).getZ());
} else if (goal instanceof GoalBlock) {
runAwayFrom = ((GoalBlock) goal).getGoalPos();
} else {
logDirect("Goal must be GoalXZ or GoalBlock to invert");
logDirect("Inverting goal of player feet");
runAwayFrom = ctx.playerFeet();
}
customGoalProcess.setGoalAndPath(new GoalRunAway(1, runAwayFrom) {
@Override
public boolean isInGoal(int x, int y, int z) {
return false;
}
});
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 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("resume")) {
baritone.getBuilderProcess().resume();
logDirect("resumed");
return true;
}
if (msg.equals("pause")) {
baritone.getBuilderProcess().pause();
logDirect("paused");
return true;
}
if (msg.equals("reset")) {
for (Settings.Setting setting : BaritoneAPI.getSettings().allSettings) {
setting.reset();
}
SettingsUtil.save(BaritoneAPI.getSettings());
logDirect("Baritone settings reset");
return true;
}
if (msg.equals("tunnel")) {
customGoalProcess.setGoalAndPath(new GoalStrictDirection(ctx.playerFeet(), ctx.player().getHorizontalFacing()));
logDirect("tunneling");
return true;
}
if (msg.equals("render")) {
BetterBlockPos pf = ctx.playerFeet();
Minecraft.getMinecraft().renderGlobal.markBlockRangeForRenderUpdate(pf.x - 500, pf.y - 500, pf.z - 500, pf.x + 500, pf.y + 500, pf.z + 500);
logDirect("okay");
return true;
}
if (msg.equals("farm")) {
baritone.getFarmProcess().farm();
logDirect("farming");
return true;
}
if (msg.equals("chests")) {
for (Map.Entry<BlockPos, IRememberedInventory> entry : baritone.getWorldProvider().getCurrentWorld().getContainerMemory().getRememberedInventories().entrySet()) {
logDirect(entry.getKey() + "");
log(entry.getValue().getContents());
}
return true;
}
if (msg.startsWith("followplayers")) {
baritone.getFollowProcess().follow(EntityPlayer.class::isInstance); // O P P A
logDirect("Following any players");
return true;
}
if (msg.startsWith("follow")) {
String name = msg.substring(6).trim();
Optional<Entity> toFollow = Optional.empty();
if (name.length() == 0) {
toFollow = ctx.getSelectedEntity();
} else {
for (EntityPlayer pl : ctx.world().playerEntities) {
String theirName = pl.getName().trim().toLowerCase();
if (!theirName.equals(ctx.player().getName().trim().toLowerCase()) && (theirName.contains(name) || name.contains(theirName))) { // don't follow ourselves lol
toFollow = Optional.of(pl);
}
}
}
if (!toFollow.isPresent()) {
logDirect("Not found");
return true;
}
Entity effectivelyFinal = toFollow.get();
baritone.getFollowProcess().follow(effectivelyFinal::equals);
logDirect("Following " + toFollow.get());
return true;
}
if (msg.startsWith("explorefilter")) {
// explorefilter blah.json
// means that entries in blah.json are already explored
// explorefilter blah.json invert
// means that entries in blah.json are NOT already explored
String path = msg.substring("explorefilter".length()).trim();
String[] parts = path.split(" ");
Path path1 = Minecraft.getMinecraft().gameDir.toPath().resolve(parts[0]);
boolean invert = parts.length > 1;
try {
baritone.getExploreProcess().applyJsonFilter(path1, invert);
logDirect("Loaded filter. Inverted: " + invert);
if (invert) {
logDirect("Chunks on this list will be treated as possibly unexplored, all others will be treated as certainly explored");
} else {
logDirect("Chunks on this list will be treated as certainly explored, all others will be treated as possibly unexplored");
}
} catch (Exception e) {
e.printStackTrace();
logDirect("Unable to load " + path1);
}
return true;
}
if (msg.equals("reloadall")) {
baritone.getWorldProvider().getCurrentWorld().getCachedWorld().reloadAllFromDisk();
logDirect("ok");
return true;
}
if (msg.equals("saveall")) {
baritone.getWorldProvider().getCurrentWorld().getCachedWorld().save();
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.equals("blacklist")) {
IGetToBlockProcess proc = baritone.getGetToBlockProcess();
if (!proc.isActive()) {
logDirect("GetToBlockProcess is not currently active");
return true;
}
if (proc.blacklistClosest()) {
logDirect("Blacklisted closest instances");
} else {
logDirect("No known locations, unable to blacklist");
}
return true;
}
if (msg.startsWith("find")) {
String blockType = msg.substring(4).trim();
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 = ctx.world().getBlockState(pos).getBlock();
if (!BlockUtils.blockToString(actually).equalsIgnoreCase(blockType)) {
logDebug("Was looking for " + blockType + " but actually found " + actually + " " + BlockUtils.blockToString(actually));
}
}
return true;
}
if (msg.startsWith("mine")) {
String[] blockTypes = msg.substring(4).trim().split(" ");
try {
int quantity = Integer.parseInt(blockTypes[1]);
Block block = BlockUtils.stringToBlockRequired(blockTypes[0]);
baritone.getMineProcess().mine(quantity, block);
logDirect("Will mine " + quantity + " " + blockTypes[0]);
return true;
} catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) {}
for (String s : blockTypes) {
if (BlockUtils.stringToBlockNullable(s) == null) {
logDirect(s + " isn't a valid block name");
return true;
}
}
baritone.getMineProcess().mineByName(0, blockTypes);
logDirect("Started mining blocks of type " + Arrays.toString(blockTypes));
return true;
}
if (msg.equals("click")) {
baritone.openClick();
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);
logDirect("Goal: " + goal);
} catch (NumberFormatException ex) {
logDirect("Error unable to parse '" + msg.substring(7).trim() + "' to a double.");
}
return true;
}
if (msg.startsWith("list") || msg.startsWith("get ") || msg.startsWith("show")) {
String waypointType = msg.substring(4).trim();
if (waypointType.endsWith("s")) {
// for example, "show deaths"
waypointType = waypointType.substring(0, waypointType.length() - 1);
}
IWaypoint.Tag tag = IWaypoint.Tag.fromString(waypointType);
if (tag == null) {
logDirect("Not a valid tag. Tags are: " + Arrays.asList(IWaypoint.Tag.values()).toString().toLowerCase());
return true;
}
Set<IWaypoint> waypoints = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getByTag(tag);
// might as well show them from oldest to newest
List<IWaypoint> sorted = new ArrayList<>(waypoints);
sorted.sort(Comparator.comparingLong(IWaypoint::getCreationTimestamp));
logDirect("Waypoints under tag " + tag + ":");
for (IWaypoint waypoint : sorted) {
logDirect(waypoint.toString());
}
return true;
}
if (msg.startsWith("save")) {
String name = msg.substring(4).trim();
BlockPos pos = ctx.playerFeet();
if (name.contains(" ")) {
logDirect("Name contains a space, assuming it's in the format 'save waypointName X Y Z'");
String[] parts = name.split(" ");
if (parts.length != 4) {
logDirect("Unable to parse, expected four things");
return true;
}
try {
pos = new BlockPos(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3]));
} catch (NumberFormatException ex) {
logDirect("Unable to parse coordinate integers");
return true;
}
name = parts[0];
}
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint(name, IWaypoint.Tag.USER, pos));
logDirect("Saved user defined position " + pos + " under name '" + name + "'. Say 'goto " + name + "' to set goal, say 'list user' to list custom waypoints.");
return true;
}
if (msg.startsWith("delete")) {
String name = msg.substring(6).trim();
IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getTag() == IWaypoint.Tag.USER && w.getName().equalsIgnoreCase(name)).findFirst().orElse(null);
if (waypoint == null) {
logDirect("No user defined position under the name '" + name + "' found.");
return true;
}
baritone.getWorldProvider().getCurrentWorld().getWaypoints().removeWaypoint(waypoint);
logDirect("Deleted user defined position under name '" + name + "'.");
return true;
}
if (msg.startsWith("goto")) {
String waypointType = msg.substring(4).trim();
if (waypointType.endsWith("s") && IWaypoint.Tag.fromString(waypointType.substring(0, waypointType.length() - 1)) != null) {
// for example, "show deaths"
waypointType = waypointType.substring(0, waypointType.length() - 1);
}
IWaypoint.Tag tag = IWaypoint.Tag.fromString(waypointType);
IWaypoint waypoint;
if (tag == null) {
String mining = waypointType;
Block block = BlockUtils.stringToBlockNullable(mining);
//logDirect("Not a valid tag. Tags are: " + Arrays.asList(Waypoint.Tag.values()).toString().toLowerCase());
if (block == null) {
waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getAllWaypoints().stream().filter(w -> w.getName().equalsIgnoreCase(mining)).max(Comparator.comparingLong(IWaypoint::getCreationTimestamp)).orElse(null);
if (waypoint == null) {
Goal goal = parseGoal(waypointType.split(" "));
if (goal != null) {
logDirect("Going to " + goal);
customGoalProcess.setGoalAndPath(goal);
}
return true;
}
} else {
baritone.getGetToBlockProcess().getToBlock(block);
return true;
}
} else {
waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(tag);
if (waypoint == null) {
logDirect("None saved for tag " + tag);
return true;
}
}
Goal goal = waypoint.getTag() == IWaypoint.Tag.BED ? new GoalGetToBlock(waypoint.getLocation()) : new GoalBlock(waypoint.getLocation());
customGoalProcess.setGoalAndPath(goal);
return true;
}
if (msg.equals("spawn") || msg.equals("bed")) {
IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(IWaypoint.Tag.BED);
if (waypoint == null) {
BlockPos spawnPoint = ctx.player().getBedLocation();
// for some reason the default spawnpoint is underground sometimes
Goal goal = new GoalXZ(spawnPoint.getX(), spawnPoint.getZ());
logDirect("spawn not saved, defaulting to world spawn. set goal to " + goal);
customGoalProcess.setGoalAndPath(goal);
} else {
Goal goal = new GoalGetToBlock(waypoint.getLocation());
customGoalProcess.setGoalAndPath(goal);
logDirect("Set goal to most recent bed " + goal);
}
return true;
}
if (msg.equals("sethome")) {
baritone.getWorldProvider().getCurrentWorld().getWaypoints().addWaypoint(new Waypoint("", IWaypoint.Tag.HOME, ctx.playerFeet()));
logDirect("Saved. Say home to set goal.");
return true;
}
if (msg.equals("home")) {
IWaypoint waypoint = baritone.getWorldProvider().getCurrentWorld().getWaypoints().getMostRecentByTag(IWaypoint.Tag.HOME);
if (waypoint == null) {
logDirect("home not saved");
} else {
Goal goal = new GoalBlock(waypoint.getLocation());
customGoalProcess.setGoalAndPath(goal);
logDirect("Going to saved home " + goal);
}
return true;
}
if (msg.equals("damn")) {
logDirect("daniel");
}
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()) {
logDirect(stack.getCount() + "x " + stack.getDisplayName() + "@" + stack.getItemDamage());
}
}
}
private Goal parseGoal(String[] params) {
Goal goal;
try {
BetterBlockPos playerFeet = ctx.playerFeet();
switch (params.length) {
case 0:
goal = new GoalBlock(playerFeet);
break;
case 1:
goal = new GoalYLevel(parseOrDefault(params[0], playerFeet.y));
break;
case 2:
goal = new GoalXZ(parseOrDefault(params[0], playerFeet.x), parseOrDefault(params[1], playerFeet.z));
break;
case 3:
goal = new GoalBlock(new BlockPos(parseOrDefault(params[0], playerFeet.x), parseOrDefault(params[1], playerFeet.y), parseOrDefault(params[2], playerFeet.z)));
break;
default:
logDirect("unable to understand lol");
return null;
}
} catch (NumberFormatException ex) {
logDirect("unable to parse integer " + ex);
return null;
}
return goal;
}
}

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