-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
BuilderProcess.java
1137 lines (1045 loc) · 49.6 KB
/
BuilderProcess.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of Baritone.
*
* Baritone is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Baritone is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Baritone. If not, see <https://www.gnu.org/licenses/>.
*/
package baritone.process;
import baritone.Baritone;
import baritone.api.pathing.goals.Goal;
import baritone.api.pathing.goals.GoalBlock;
import baritone.api.pathing.goals.GoalComposite;
import baritone.api.pathing.goals.GoalGetToBlock;
import baritone.api.process.IBuilderProcess;
import baritone.api.process.PathingCommand;
import baritone.api.process.PathingCommandType;
import baritone.api.schematic.FillSchematic;
import baritone.api.schematic.ISchematic;
import baritone.api.schematic.IStaticSchematic;
import baritone.api.schematic.SubstituteSchematic;
import baritone.api.schematic.format.ISchematicFormat;
import baritone.api.utils.*;
import baritone.api.utils.input.Input;
import baritone.pathing.movement.CalculationContext;
import baritone.pathing.movement.Movement;
import baritone.pathing.movement.MovementHelper;
import baritone.utils.BaritoneProcessHelper;
import baritone.utils.BlockStateInterface;
import baritone.utils.PathingCommandContext;
import baritone.utils.schematic.MapArtSchematic;
import baritone.utils.schematic.SchematicSystem;
import baritone.utils.schematic.SelectionSchematic;
import baritone.utils.schematic.format.defaults.LitematicaSchematic;
import baritone.utils.schematic.litematica.LitematicaHelper;
import baritone.utils.schematic.schematica.SchematicaHelper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import net.minecraft.block.*;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.Tuple;
import net.minecraft.util.math.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static baritone.api.pathing.movement.ActionCosts.COST_INF;
public final class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess {
private HashSet<BetterBlockPos> incorrectPositions;
private LongOpenHashSet observedCompleted; // positions that are completed even if they're out of render distance and we can't make sure right now
private String name;
private ISchematic realSchematic;
private ISchematic schematic;
private Vec3i origin;
private int ticks;
private boolean paused;
private int layer;
private int numRepeats;
private List<IBlockState> approxPlaceable;
public int stopAtHeight = 0;
public BuilderProcess(Baritone baritone) {
super(baritone);
}
@Override
public void build(String name, ISchematic schematic, Vec3i origin) {
this.name = name;
this.schematic = schematic;
this.realSchematic = null;
boolean buildingSelectionSchematic = schematic instanceof SelectionSchematic;
if (!Baritone.settings().buildSubstitutes.value.isEmpty()) {
this.schematic = new SubstituteSchematic(this.schematic, Baritone.settings().buildSubstitutes.value);
}
int x = origin.getX();
int y = origin.getY();
int z = origin.getZ();
if (Baritone.settings().schematicOrientationX.value) {
x += schematic.widthX();
}
if (Baritone.settings().schematicOrientationY.value) {
y += schematic.heightY();
}
if (Baritone.settings().schematicOrientationZ.value) {
z += schematic.lengthZ();
}
this.origin = new Vec3i(x, y, z);
this.paused = false;
this.layer = Baritone.settings().startAtLayer.value;
this.stopAtHeight = schematic.heightY();
if (Baritone.settings().buildOnlySelection.value && buildingSelectionSchematic) { // currently redundant but safer maybe
if (baritone.getSelectionManager().getSelections().length == 0) {
logDirect("Poor little kitten forgot to set a selection while BuildOnlySelection is true");
this.stopAtHeight = 0;
} else if (Baritone.settings().buildInLayers.value) {
OptionalInt minim = Stream.of(baritone.getSelectionManager().getSelections()).mapToInt(sel -> sel.min().y).min();
OptionalInt maxim = Stream.of(baritone.getSelectionManager().getSelections()).mapToInt(sel -> sel.max().y).max();
if (minim.isPresent() && maxim.isPresent()) {
int startAtHeight = Baritone.settings().layerOrder.value ? y + schematic.heightY() - maxim.getAsInt() : minim.getAsInt() - y;
this.stopAtHeight = (Baritone.settings().layerOrder.value ? y + schematic.heightY() - minim.getAsInt() : maxim.getAsInt() - y) + 1;
this.layer = Math.max(this.layer, startAtHeight / Baritone.settings().layerHeight.value); // startAtLayer or startAtHeight, whichever is highest
logDebug(String.format("Schematic starts at y=%s with height %s", y, schematic.heightY()));
logDebug(String.format("Selection starts at y=%s and ends at y=%s", minim.getAsInt(), maxim.getAsInt()));
logDebug(String.format("Considering relevant height %s - %s", startAtHeight, this.stopAtHeight));
}
}
}
this.numRepeats = 0;
this.observedCompleted = new LongOpenHashSet();
this.incorrectPositions = null;
}
public void resume() {
paused = false;
}
public void pause() {
paused = true;
}
@Override
public boolean isPaused() {
return paused;
}
@Override
public boolean build(String name, File schematic, Vec3i origin) {
Optional<ISchematicFormat> format = SchematicSystem.INSTANCE.getByFile(schematic);
if (!format.isPresent()) {
return false;
}
ISchematic parsed;
try {
parsed = format.get().parse(new FileInputStream(schematic));
} catch (Exception e) {
e.printStackTrace();
return false;
}
parsed = applyMapArtAndSelection(origin, (IStaticSchematic) parsed);
build(name, parsed, origin);
return true;
}
private ISchematic applyMapArtAndSelection(Vec3i origin, IStaticSchematic parsed) {
ISchematic schematic = parsed;
if (Baritone.settings().mapArtMode.value) {
schematic = new MapArtSchematic(parsed);
}
if (Baritone.settings().buildOnlySelection.value) {
schematic = new SelectionSchematic(schematic, origin, baritone.getSelectionManager().getSelections());
}
return schematic;
}
@Override
public void buildOpenSchematic() {
if (SchematicaHelper.isSchematicaPresent()) {
Optional<Tuple<IStaticSchematic, BlockPos>> schematic = SchematicaHelper.getOpenSchematic();
if (schematic.isPresent()) {
IStaticSchematic s = schematic.get().getFirst();
BlockPos origin = schematic.get().getSecond();
ISchematic schem = Baritone.settings().mapArtMode.value ? new MapArtSchematic(s) : s;
if (Baritone.settings().buildOnlySelection.value) {
schem = new SelectionSchematic(schem, origin, baritone.getSelectionManager().getSelections());
}
this.build(
schematic.get().getFirst().toString(),
schem,
origin
);
} else {
logDirect("No schematic currently open");
}
} else {
logDirect("Schematica is not present");
}
}
/**
* Builds the with index 'i' given schematic placement.
*
* @param i index reference to the schematic placement list.
*/
@Override
public void buildOpenLitematic(int i) {
if (LitematicaHelper.isLitematicaPresent()) {
//if java.lang.NoSuchMethodError is thrown see comment in SchematicPlacementManager
if (LitematicaHelper.hasLoadedSchematic()) {
String name = LitematicaHelper.getName(i);
try {
LitematicaSchematic schematic1 = new LitematicaSchematic(CompressedStreamTools.readCompressed(Files.newInputStream(LitematicaHelper.getSchematicFile(i).toPath())), false);
Vec3i correctedOrigin = LitematicaHelper.getCorrectedOrigin(schematic1, i);
ISchematic schematic2 = LitematicaHelper.blackMagicFuckery(schematic1, i);
schematic2 = applyMapArtAndSelection(origin, (IStaticSchematic) schematic2);
build(name, schematic2, correctedOrigin);
} catch (IOException e) {
logDirect("Schematic File could not be loaded.");
}
} else {
logDirect("No schematic currently loaded");
}
} else {
logDirect("Litematica is not present");
}
}
public void clearArea(BlockPos corner1, BlockPos corner2) {
BlockPos origin = new BlockPos(Math.min(corner1.getX(), corner2.getX()), Math.min(corner1.getY(), corner2.getY()), Math.min(corner1.getZ(), corner2.getZ()));
int widthX = Math.abs(corner1.getX() - corner2.getX()) + 1;
int heightY = Math.abs(corner1.getY() - corner2.getY()) + 1;
int lengthZ = Math.abs(corner1.getZ() - corner2.getZ()) + 1;
build("clear area", new FillSchematic(widthX, heightY, lengthZ, Blocks.AIR.getDefaultState()), origin);
}
@Override
public List<IBlockState> getApproxPlaceable() {
return new ArrayList<>(approxPlaceable);
}
@Override
public boolean isActive() {
return schematic != null;
}
public IBlockState placeAt(int x, int y, int z, IBlockState current) {
if (!isActive()) {
return null;
}
if (!schematic.inSchematic(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current)) {
return null;
}
IBlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ(), current, this.approxPlaceable);
if (state.getBlock() == Blocks.AIR) {
return null;
}
return state;
}
private Optional<Tuple<BetterBlockPos, Rotation>> toBreakNearPlayer(BuilderCalculationContext bcc) {
BetterBlockPos center = ctx.playerFeet();
BetterBlockPos pathStart = baritone.getPathingBehavior().pathStart();
for (int dx = -5; dx <= 5; dx++) {
for (int dy = Baritone.settings().breakFromAbove.value ? -1 : 0; dy <= 5; dy++) {
for (int dz = -5; dz <= 5; dz++) {
int x = center.x + dx;
int y = center.y + dy;
int z = center.z + dz;
if (dy == -1 && x == pathStart.x && z == pathStart.z) {
continue; // dont mine what we're supported by, but not directly standing on
}
IBlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z));
if (desired == null) {
continue; // irrelevant
}
IBlockState curr = bcc.bsi.get0(x, y, z);
if (curr.getBlock() != Blocks.AIR && !(curr.getBlock() instanceof BlockLiquid) && !valid(curr, desired, false)) {
BetterBlockPos pos = new BetterBlockPos(x, y, z);
Optional<Rotation> rot = RotationUtils.reachable(ctx, pos, ctx.playerController().getBlockReachDistance());
if (rot.isPresent()) {
return Optional.of(new Tuple<>(pos, rot.get()));
}
}
}
}
}
return Optional.empty();
}
public static class Placement {
private final int hotbarSelection;
private final BlockPos placeAgainst;
private final EnumFacing side;
private final Rotation rot;
public Placement(int hotbarSelection, BlockPos placeAgainst, EnumFacing side, Rotation rot) {
this.hotbarSelection = hotbarSelection;
this.placeAgainst = placeAgainst;
this.side = side;
this.rot = rot;
}
}
private Optional<Placement> searchForPlaceables(BuilderCalculationContext bcc, List<IBlockState> desirableOnHotbar) {
BetterBlockPos center = ctx.playerFeet();
for (int dx = -5; dx <= 5; dx++) {
for (int dy = -5; dy <= 1; dy++) {
for (int dz = -5; dz <= 5; dz++) {
int x = center.x + dx;
int y = center.y + dy;
int z = center.z + dz;
IBlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z));
if (desired == null) {
continue; // irrelevant
}
IBlockState curr = bcc.bsi.get0(x, y, z);
if (MovementHelper.isReplaceable(x, y, z, curr, bcc.bsi) && !valid(curr, desired, false)) {
if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() == Blocks.AIR) {
continue;
}
desirableOnHotbar.add(desired);
Optional<Placement> opt = possibleToPlace(desired, x, y, z, bcc.bsi);
if (opt.isPresent()) {
return opt;
}
}
}
}
}
return Optional.empty();
}
private Optional<Placement> possibleToPlace(IBlockState toPlace, int x, int y, int z, BlockStateInterface bsi) {
for (EnumFacing against : EnumFacing.values()) {
BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against);
IBlockState placeAgainstState = bsi.get0(placeAgainstPos);
if (MovementHelper.isReplaceable(placeAgainstPos.x, placeAgainstPos.y, placeAgainstPos.z, placeAgainstState, bsi)) {
continue;
}
if (!ctx.world().mayPlace(toPlace.getBlock(), new BetterBlockPos(x, y, z), false, against, null)) {
continue;
}
AxisAlignedBB aabb = placeAgainstState.getBoundingBox(ctx.world(), placeAgainstPos);
for (Vec3d placementMultiplier : aabbSideMultipliers(against)) {
double placeX = placeAgainstPos.x + aabb.minX * placementMultiplier.x + aabb.maxX * (1 - placementMultiplier.x);
double placeY = placeAgainstPos.y + aabb.minY * placementMultiplier.y + aabb.maxY * (1 - placementMultiplier.y);
double placeZ = placeAgainstPos.z + aabb.minZ * placementMultiplier.z + aabb.maxZ * (1 - placementMultiplier.z);
Rotation rot = RotationUtils.calcRotationFromVec3d(RayTraceUtils.inferSneakingEyePosition(ctx.player()), new Vec3d(placeX, placeY, placeZ), ctx.playerRotations());
Rotation actualRot = baritone.getLookBehavior().getAimProcessor().peekRotation(rot);
RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), actualRot, ctx.playerController().getBlockReachDistance(), true);
if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK && result.getBlockPos().equals(placeAgainstPos) && result.sideHit == against.getOpposite()) {
OptionalInt hotbar = hasAnyItemThatWouldPlace(toPlace, result, actualRot);
if (hotbar.isPresent()) {
return Optional.of(new Placement(hotbar.getAsInt(), placeAgainstPos, against.getOpposite(), rot));
}
}
}
}
return Optional.empty();
}
private OptionalInt hasAnyItemThatWouldPlace(IBlockState desired, RayTraceResult result, Rotation rot) {
for (int i = 0; i < 9; i++) {
ItemStack stack = ctx.player().inventory.mainInventory.get(i);
if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) {
continue;
}
float originalYaw = ctx.player().rotationYaw;
float originalPitch = ctx.player().rotationPitch;
// the state depends on the facing of the player sometimes
ctx.player().rotationYaw = rot.getYaw();
ctx.player().rotationPitch = rot.getPitch();
IBlockState wouldBePlaced = ((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(
ctx.world(),
result.getBlockPos().offset(result.sideHit),
result.sideHit,
(float) result.hitVec.x - result.getBlockPos().getX(), // as in PlayerControllerMP
(float) result.hitVec.y - result.getBlockPos().getY(),
(float) result.hitVec.z - result.getBlockPos().getZ(),
stack.getItem().getMetadata(stack.getMetadata()),
ctx.player()
);
ctx.player().rotationYaw = originalYaw;
ctx.player().rotationPitch = originalPitch;
if (valid(wouldBePlaced, desired, true)) {
return OptionalInt.of(i);
}
}
return OptionalInt.empty();
}
private static Vec3d[] aabbSideMultipliers(EnumFacing side) {
switch (side) {
case UP:
return new Vec3d[]{new Vec3d(0.5, 1, 0.5), new Vec3d(0.1, 1, 0.5), new Vec3d(0.9, 1, 0.5), new Vec3d(0.5, 1, 0.1), new Vec3d(0.5, 1, 0.9)};
case DOWN:
return new Vec3d[]{new Vec3d(0.5, 0, 0.5), new Vec3d(0.1, 0, 0.5), new Vec3d(0.9, 0, 0.5), new Vec3d(0.5, 0, 0.1), new Vec3d(0.5, 0, 0.9)};
case NORTH:
case SOUTH:
case EAST:
case WEST:
double x = side.getXOffset() == 0 ? 0.5 : (1 + side.getXOffset()) / 2D;
double z = side.getZOffset() == 0 ? 0.5 : (1 + side.getZOffset()) / 2D;
return new Vec3d[]{new Vec3d(x, 0.25, z), new Vec3d(x, 0.75, z)};
default: // null
throw new IllegalStateException();
}
}
@Override
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
return onTick(calcFailed, isSafeToCancel, 0);
}
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel, int recursions) {
if (recursions > 1000) { // onTick calls itself, don't crash
return new PathingCommand(null, PathingCommandType.SET_GOAL_AND_PATH);
}
approxPlaceable = approxPlaceable(36);
if (baritone.getInputOverrideHandler().isInputForcedDown(Input.CLICK_LEFT)) {
ticks = 5;
} else {
ticks--;
}
baritone.getInputOverrideHandler().clearAllKeys();
if (paused) {
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
}
if (Baritone.settings().buildInLayers.value) {
if (realSchematic == null) {
realSchematic = schematic;
}
ISchematic realSchematic = this.realSchematic; // wrap this properly, dont just have the inner class refer to the builderprocess.this
int minYInclusive;
int maxYInclusive;
// layer = 0 should be nothing
// layer = realSchematic.heightY() should be everything
if (Baritone.settings().layerOrder.value) { // top to bottom
maxYInclusive = realSchematic.heightY() - 1;
minYInclusive = realSchematic.heightY() - layer * Baritone.settings().layerHeight.value;
} else {
maxYInclusive = layer * Baritone.settings().layerHeight.value - 1;
minYInclusive = 0;
}
schematic = new ISchematic() {
@Override
public IBlockState desiredState(int x, int y, int z, IBlockState current, List<IBlockState> approxPlaceable) {
return realSchematic.desiredState(x, y, z, current, BuilderProcess.this.approxPlaceable);
}
@Override
public boolean inSchematic(int x, int y, int z, IBlockState currentState) {
return ISchematic.super.inSchematic(x, y, z, currentState) && y >= minYInclusive && y <= maxYInclusive && realSchematic.inSchematic(x, y, z, currentState);
}
@Override
public void reset() {
realSchematic.reset();
}
@Override
public int widthX() {
return realSchematic.widthX();
}
@Override
public int heightY() {
return realSchematic.heightY();
}
@Override
public int lengthZ() {
return realSchematic.lengthZ();
}
};
}
BuilderCalculationContext bcc = new BuilderCalculationContext();
if (!recalc(bcc)) {
if (Baritone.settings().buildInLayers.value && layer * Baritone.settings().layerHeight.value < stopAtHeight) {
logDirect("Starting layer " + layer);
layer++;
return onTick(calcFailed, isSafeToCancel, recursions + 1);
}
Vec3i repeat = Baritone.settings().buildRepeat.value;
int max = Baritone.settings().buildRepeatCount.value;
numRepeats++;
if (repeat.equals(new Vec3i(0, 0, 0)) || (max != -1 && numRepeats >= max)) {
logDirect("Done building");
if (Baritone.settings().notificationOnBuildFinished.value) {
logNotification("Done building", false);
}
onLostControl();
return null;
}
// build repeat time
layer = 0;
origin = new BlockPos(origin).add(repeat);
if (!Baritone.settings().buildRepeatSneaky.value) {
schematic.reset();
}
logDirect("Repeating build in vector " + repeat + ", new origin is " + origin);
return onTick(calcFailed, isSafeToCancel, recursions + 1);
}
if (Baritone.settings().distanceTrim.value) {
trim();
}
Optional<Tuple<BetterBlockPos, Rotation>> toBreak = toBreakNearPlayer(bcc);
if (toBreak.isPresent() && isSafeToCancel && ctx.player().onGround) {
// we'd like to pause to break this block
// only change look direction if it's safe (don't want to fuck up an in progress parkour for example
Rotation rot = toBreak.get().getSecond();
BetterBlockPos pos = toBreak.get().getFirst();
baritone.getLookBehavior().updateTarget(rot, true);
MovementHelper.switchToBestToolFor(ctx, bcc.get(pos));
if (ctx.player().isSneaking()) {
// really horrible bug where a block is visible for breaking while sneaking but not otherwise
// so you can't see it, it goes to place something else, sneaks, then the next tick it tries to break
// and is unable since it's unsneaked in the intermediary tick
baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true);
}
if (ctx.isLookingAt(pos) || ctx.playerRotations().isReallyCloseTo(rot)) {
baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true);
}
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
}
List<IBlockState> desirableOnHotbar = new ArrayList<>();
Optional<Placement> toPlace = searchForPlaceables(bcc, desirableOnHotbar);
if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround && ticks <= 0) {
Rotation rot = toPlace.get().rot;
baritone.getLookBehavior().updateTarget(rot, true);
ctx.player().inventory.currentItem = toPlace.get().hotbarSelection;
baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true);
if ((ctx.isLookingAt(toPlace.get().placeAgainst) && ctx.objectMouseOver().sideHit.equals(toPlace.get().side)) || ctx.playerRotations().isReallyCloseTo(rot)) {
baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true);
}
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
}
if (baritone.getInventoryBehavior().canAccessInventory()) {
ArrayList<Integer> usefulSlots = new ArrayList<>();
List<IBlockState> noValidHotbarOption = new ArrayList<>();
outer:
for (IBlockState desired : desirableOnHotbar) {
for (int i = 0; i < 9; i++) {
if (valid(approxPlaceable.get(i), desired, true)) {
usefulSlots.add(i);
continue outer;
}
}
noValidHotbarOption.add(desired);
}
outer:
for (int i = 9; i < 36; i++) {
for (IBlockState desired : noValidHotbarOption) {
if (valid(approxPlaceable.get(i), desired, true)) {
if (!baritone.getInventoryBehavior().attemptToPutOnHotbar(i, usefulSlots::contains)) {
// awaiting inventory move, so pause
return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE);
}
break outer;
}
}
}
}
Goal goal = assemble(bcc, approxPlaceable.subList(0, 9));
if (goal == null) {
goal = assemble(bcc, approxPlaceable, true); // we're far away, so assume that we have our whole inventory to recalculate placeable properly
if (goal == null) {
if (Baritone.settings().skipFailedLayers.value && Baritone.settings().buildInLayers.value && layer * Baritone.settings().layerHeight.value < realSchematic.heightY()) {
logDirect("Skipping layer that I cannot construct! Layer #" + layer);
layer++;
return onTick(calcFailed, isSafeToCancel, recursions + 1);
}
logDirect("Unable to do it. Pausing. resume to resume, cancel to cancel");
paused = true;
return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE);
}
}
return new PathingCommandContext(goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc);
}
private boolean recalc(BuilderCalculationContext bcc) {
if (incorrectPositions == null) {
incorrectPositions = new HashSet<>();
fullRecalc(bcc);
if (incorrectPositions.isEmpty()) {
return false;
}
}
recalcNearby(bcc);
if (incorrectPositions.isEmpty()) {
fullRecalc(bcc);
}
return !incorrectPositions.isEmpty();
}
private void trim() {
HashSet<BetterBlockPos> copy = new HashSet<>(incorrectPositions);
copy.removeIf(pos -> pos.distanceSq(ctx.player().posX, ctx.player().posY, ctx.player().posZ) > 200);
if (!copy.isEmpty()) {
incorrectPositions = copy;
}
}
private void recalcNearby(BuilderCalculationContext bcc) {
BetterBlockPos center = ctx.playerFeet();
int radius = Baritone.settings().builderTickScanRadius.value;
for (int dx = -radius; dx <= radius; dx++) {
for (int dy = -radius; dy <= radius; dy++) {
for (int dz = -radius; dz <= radius; dz++) {
int x = center.x + dx;
int y = center.y + dy;
int z = center.z + dz;
IBlockState desired = bcc.getSchematic(x, y, z, bcc.bsi.get0(x, y, z));
if (desired != null) {
// we care about this position
BetterBlockPos pos = new BetterBlockPos(x, y, z);
if (valid(bcc.bsi.get0(x, y, z), desired, false)) {
incorrectPositions.remove(pos);
observedCompleted.add(BetterBlockPos.longHash(pos));
} else {
incorrectPositions.add(pos);
observedCompleted.remove(BetterBlockPos.longHash(pos));
}
}
}
}
}
}
private void fullRecalc(BuilderCalculationContext bcc) {
incorrectPositions = new HashSet<>();
for (int y = 0; y < schematic.heightY(); y++) {
for (int z = 0; z < schematic.lengthZ(); z++) {
for (int x = 0; x < schematic.widthX(); x++) {
int blockX = x + origin.getX();
int blockY = y + origin.getY();
int blockZ = z + origin.getZ();
IBlockState current = bcc.bsi.get0(blockX, blockY, blockZ);
if (!schematic.inSchematic(x, y, z, current)) {
continue;
}
if (bcc.bsi.worldContainsLoadedChunk(blockX, blockZ)) { // check if its in render distance, not if its in cache
// we can directly observe this block, it is in render distance
if (valid(bcc.bsi.get0(blockX, blockY, blockZ), schematic.desiredState(x, y, z, current, this.approxPlaceable), false)) {
observedCompleted.add(BetterBlockPos.longHash(blockX, blockY, blockZ));
} else {
incorrectPositions.add(new BetterBlockPos(blockX, blockY, blockZ));
observedCompleted.remove(BetterBlockPos.longHash(blockX, blockY, blockZ));
if (incorrectPositions.size() > Baritone.settings().incorrectSize.value) {
return;
}
}
continue;
}
// this is not in render distance
if (!observedCompleted.contains(BetterBlockPos.longHash(blockX, blockY, blockZ))
&& !Baritone.settings().buildSkipBlocks.value.contains(schematic.desiredState(x, y, z, current, this.approxPlaceable).getBlock())) {
// and we've never seen this position be correct
// therefore mark as incorrect
incorrectPositions.add(new BetterBlockPos(blockX, blockY, blockZ));
if (incorrectPositions.size() > Baritone.settings().incorrectSize.value) {
return;
}
}
}
}
}
}
private Goal assemble(BuilderCalculationContext bcc, List<IBlockState> approxPlaceable) {
return assemble(bcc, approxPlaceable, false);
}
private Goal assemble(BuilderCalculationContext bcc, List<IBlockState> approxPlaceable, boolean logMissing) {
List<BetterBlockPos> placeable = new ArrayList<>();
List<BetterBlockPos> breakable = new ArrayList<>();
List<BetterBlockPos> sourceLiquids = new ArrayList<>();
List<BetterBlockPos> flowingLiquids = new ArrayList<>();
Map<IBlockState, Integer> missing = new HashMap<>();
incorrectPositions.forEach(pos -> {
IBlockState state = bcc.bsi.get0(pos);
if (state.getBlock() instanceof BlockAir) {
if (containsBlockState(approxPlaceable, bcc.getSchematic(pos.x, pos.y, pos.z, state))) {
placeable.add(pos);
} else {
IBlockState desired = bcc.getSchematic(pos.x, pos.y, pos.z, state);
missing.put(desired, 1 + missing.getOrDefault(desired, 0));
}
} else {
if (state.getBlock() instanceof BlockLiquid) {
// if the block itself is JUST a liquid (i.e. not just a waterlogged block), we CANNOT break it
// TODO for 1.13 make sure that this only matches pure water, not waterlogged blocks
if (!MovementHelper.possiblyFlowing(state)) {
// if it's a source block then we want to replace it with a throwaway
sourceLiquids.add(pos);
} else {
flowingLiquids.add(pos);
}
} else {
breakable.add(pos);
}
}
});
List<Goal> toBreak = new ArrayList<>();
breakable.forEach(pos -> toBreak.add(breakGoal(pos, bcc)));
List<Goal> toPlace = new ArrayList<>();
placeable.forEach(pos -> {
if (!placeable.contains(pos.down()) && !placeable.contains(pos.down(2))) {
toPlace.add(placementGoal(pos, bcc));
}
});
sourceLiquids.forEach(pos -> toPlace.add(new GoalBlock(pos.up())));
if (!toPlace.isEmpty()) {
return new JankyGoalComposite(new GoalComposite(toPlace.toArray(new Goal[0])), new GoalComposite(toBreak.toArray(new Goal[0])));
}
if (toBreak.isEmpty()) {
if (logMissing && !missing.isEmpty()) {
logDirect("Missing materials for at least:");
logDirect(missing.entrySet().stream()
.map(e -> String.format("%sx %s", e.getValue(), e.getKey()))
.collect(Collectors.joining("\n")));
}
if (logMissing && !flowingLiquids.isEmpty()) {
logDirect("Unreplaceable liquids at at least:");
logDirect(flowingLiquids.stream()
.map(p -> String.format("%s %s %s", p.x, p.y, p.z))
.collect(Collectors.joining("\n")));
}
return null;
}
return new GoalComposite(toBreak.toArray(new Goal[0]));
}
public static class JankyGoalComposite implements Goal {
private final Goal primary;
private final Goal fallback;
public JankyGoalComposite(Goal primary, Goal fallback) {
this.primary = primary;
this.fallback = fallback;
}
@Override
public boolean isInGoal(int x, int y, int z) {
return primary.isInGoal(x, y, z) || fallback.isInGoal(x, y, z);
}
@Override
public double heuristic(int x, int y, int z) {
return primary.heuristic(x, y, z);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
JankyGoalComposite goal = (JankyGoalComposite) o;
return Objects.equals(primary, goal.primary)
&& Objects.equals(fallback, goal.fallback);
}
@Override
public int hashCode() {
int hash = -1701079641;
hash = hash * 1196141026 + primary.hashCode();
hash = hash * -80327868 + fallback.hashCode();
return hash;
}
@Override
public String toString() {
return "JankyComposite Primary: " + primary + " Fallback: " + fallback;
}
}
public static class GoalBreak extends GoalGetToBlock {
public GoalBreak(BlockPos pos) {
super(pos);
}
@Override
public boolean isInGoal(int x, int y, int z) {
// can't stand right on top of a block, that might not work (what if it's unsupported, can't break then)
if (y > this.y) {
return false;
}
// but any other adjacent works for breaking, including inside or below
return super.isInGoal(x, y, z);
}
@Override
public String toString() {
return String.format(
"GoalBreak{x=%s,y=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z)
);
}
@Override
public int hashCode() {
return super.hashCode() * 1636324008;
}
}
private Goal placementGoal(BlockPos pos, BuilderCalculationContext bcc) {
if (ctx.world().getBlockState(pos).getBlock() != Blocks.AIR) { // TODO can this even happen?
return new GoalPlace(pos);
}
boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR;
IBlockState current = ctx.world().getBlockState(pos);
for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN_____SO_EVERY_DIRECTION_EXCEPT_UP) {
//noinspection ConstantConditions
if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ(), current).getBlock(), pos, false, facing, null)) {
return new GoalAdjacent(pos, pos.offset(facing), allowSameLevel);
}
}
return new GoalPlace(pos);
}
private Goal breakGoal(BlockPos pos, BuilderCalculationContext bcc) {
if (Baritone.settings().goalBreakFromAbove.value && bcc.bsi.get0(pos.up()).getBlock() instanceof BlockAir && bcc.bsi.get0(pos.up(2)).getBlock() instanceof BlockAir) { // TODO maybe possible without the up(2) check?
return new JankyGoalComposite(new GoalBreak(pos), new GoalGetToBlock(pos.up()) {
@Override
public boolean isInGoal(int x, int y, int z) {
if (y > this.y || (x == this.x && y == this.y && z == this.z)) {
return false;
}
return super.isInGoal(x, y, z);
}
});
}
return new GoalBreak(pos);
}
public static class GoalAdjacent extends GoalGetToBlock {
private boolean allowSameLevel;
private BlockPos no;
public GoalAdjacent(BlockPos pos, BlockPos no, boolean allowSameLevel) {
super(pos);
this.no = no;
this.allowSameLevel = allowSameLevel;
}
@Override
public boolean isInGoal(int x, int y, int z) {
if (x == this.x && y == this.y && z == this.z) {
return false;
}
if (x == no.getX() && y == no.getY() && z == no.getZ()) {
return false;
}
if (!allowSameLevel && y == this.y - 1) {
return false;
}
if (y < this.y - 1) {
return false;
}
return super.isInGoal(x, y, z);
}
@Override
public double heuristic(int x, int y, int z) {
// prioritize lower y coordinates
return this.y * 100 + super.heuristic(x, y, z);
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) {
return false;
}
GoalAdjacent goal = (GoalAdjacent) o;
return allowSameLevel == goal.allowSameLevel
&& Objects.equals(no, goal.no);
}
@Override
public int hashCode() {
int hash = 806368046;
hash = hash * 1412661222 + super.hashCode();
hash = hash * 1730799370 + (int) BetterBlockPos.longHash(no.getX(), no.getY(), no.getZ());
hash = hash * 260592149 + (allowSameLevel ? -1314802005 : 1565710265);
return hash;
}
@Override
public String toString() {
return String.format(
"GoalAdjacent{x=%s,y=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z)
);
}
}
public static class GoalPlace extends GoalBlock {
public GoalPlace(BlockPos placeAt) {
super(placeAt.up());
}
@Override
public double heuristic(int x, int y, int z) {
// prioritize lower y coordinates
return this.y * 100 + super.heuristic(x, y, z);
}
@Override
public int hashCode() {
return super.hashCode() * 1910811835;
}
@Override
public String toString() {
return String.format(
"GoalPlace{x=%s,y=%s,z=%s}",
SettingsUtil.maybeCensor(x),
SettingsUtil.maybeCensor(y),
SettingsUtil.maybeCensor(z)
);
}
}
@Override
public void onLostControl() {
incorrectPositions = null;
name = null;
schematic = null;
realSchematic = null;
layer = Baritone.settings().startAtLayer.value;
numRepeats = 0;
paused = false;
observedCompleted = null;
}
@Override
public String displayName0() {
return paused ? "Builder Paused" : "Building " + name;
}
private List<IBlockState> approxPlaceable(int size) {
List<IBlockState> result = new ArrayList<>();
for (int i = 0; i < size; i++) {
ItemStack stack = ctx.player().inventory.mainInventory.get(i);
if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) {
result.add(Blocks.AIR.getDefaultState());
continue;
}
// <toxic cloud>
result.add(((ItemBlock) stack.getItem()).getBlock().getStateForPlacement(ctx.world(), ctx.playerFeet(), EnumFacing.UP, (float) ctx.player().posX, (float) ctx.player().posY, (float) ctx.player().posZ, stack.getItem().getMetadata(stack.getMetadata()), ctx.player()));
// </toxic cloud>
}
return result;
}
public static final Set<IProperty<?>> orientationProps =
ImmutableSet.of(BlockRotatedPillar.AXIS, BlockLog.LOG_AXIS, BlockHorizontal.FACING,
BlockStairs.FACING, BlockStairs.HALF, BlockStairs.SHAPE,
BlockPane.NORTH, BlockPane.EAST, BlockPane.SOUTH, BlockPane.WEST, BlockVine.UP,
BlockTrapDoor.OPEN, BlockTrapDoor.HALF
);
private boolean sameBlockstate(IBlockState first, IBlockState second) {
if (first.getBlock() != second.getBlock()) {
return false;
}
boolean ignoreDirection = Baritone.settings().buildIgnoreDirection.value;
List<String> ignoredProps = Baritone.settings().buildIgnoreProperties.value;
if (!ignoreDirection && ignoredProps.isEmpty()) {
return first.equals(second); // early return if no properties are being ignored
}
ImmutableMap<IProperty<?>, Comparable<?>> map1 = first.getProperties();
ImmutableMap<IProperty<?>, Comparable<?>> map2 = second.getProperties();
for (IProperty<?> prop : map1.keySet()) {
if (map1.get(prop) != map2.get(prop)
&& !(ignoreDirection && orientationProps.contains(prop))