From 251110c4f89afaac13458471a8e036509ce52bcd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 25 Dec 2018 21:07:17 -0800 Subject: [PATCH 01/41] the start of something big --- src/main/java/baritone/Baritone.java | 11 +- .../baritone/behavior/PathingBehavior.java | 31 ++- .../pathing/movement/CalculationContext.java | 25 +- .../movement/movements/MovementAscend.java | 15 +- .../movement/movements/MovementDescend.java | 2 +- .../movement/movements/MovementParkour.java | 6 +- .../movement/movements/MovementPillar.java | 11 +- .../movement/movements/MovementTraverse.java | 9 +- .../java/baritone/process/BuilderProcess.java | 229 ++++++++++++++++++ .../utils/ExampleBaritoneControl.java | 5 + src/main/java/baritone/utils/ISchematic.java | 39 +++ .../baritone/utils/PathingCommandContext.java | 32 +++ .../baritone/utils/PathingControlManager.java | 10 +- 13 files changed, 380 insertions(+), 45 deletions(-) create mode 100644 src/main/java/baritone/process/BuilderProcess.java create mode 100644 src/main/java/baritone/utils/ISchematic.java create mode 100644 src/main/java/baritone/utils/PathingCommandContext.java diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 41fa36c50..358a4f2bf 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -25,10 +25,7 @@ import baritone.api.utils.IPlayerContext; import baritone.behavior.*; import baritone.cache.WorldProvider; import baritone.event.GameEventHandler; -import baritone.process.CustomGoalProcess; -import baritone.process.FollowProcess; -import baritone.process.GetToBlockProcess; -import baritone.process.MineProcess; +import baritone.process.*; import baritone.utils.BaritoneAutoTest; import baritone.utils.ExampleBaritoneControl; import baritone.utils.InputOverrideHandler; @@ -83,6 +80,7 @@ public class Baritone implements IBaritone { private MineProcess mineProcess; private GetToBlockProcess getToBlockProcess; private CustomGoalProcess customGoalProcess; + private BuilderProcess builderProcess; private PathingControlManager pathingControlManager; @@ -118,6 +116,7 @@ public class Baritone implements IBaritone { mineProcess = new MineProcess(this); customGoalProcess = new CustomGoalProcess(this); // very high iq getToBlockProcess = new GetToBlockProcess(this); + builderProcess = new BuilderProcess(this); } this.worldProvider = new WorldProvider(); @@ -171,6 +170,10 @@ public class Baritone implements IBaritone { return this.followProcess; } + public BuilderProcess getBuilderProcess() { + return this.builderProcess; + } + @Override public LookBehavior getLookBehavior() { return this.lookBehavior; diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 6f0cf32b0..a75091737 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -26,6 +26,7 @@ import baritone.api.event.events.TickEvent; import baritone.api.pathing.calc.IPath; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalXZ; +import baritone.api.process.PathingCommand; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.PathCalculationResult; import baritone.api.utils.interfaces.IGoalRenderPos; @@ -37,9 +38,9 @@ import baritone.pathing.path.CutoffPath; import baritone.pathing.path.PathExecutor; import baritone.utils.Helper; import baritone.utils.PathRenderer; +import baritone.utils.PathingCommandContext; import baritone.utils.pathing.Favoring; import net.minecraft.util.math.BlockPos; -import net.minecraft.world.chunk.EmptyChunk; import java.util.ArrayList; import java.util.Comparator; @@ -149,7 +150,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return; } queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true); + findPathInNewThread(pathStart(), true, new CalculationContext(baritone, true)); } return; } @@ -184,7 +185,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // and this path has 5 seconds or less left logDebug("Path almost over. Planning ahead..."); queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED); - findPathInNewThread(current.getPath().getDest(), false); + findPathInNewThread(current.getPath().getDest(), false, new CalculationContext(baritone, true)); } } } @@ -219,9 +220,15 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, this.goal = goal; } - public boolean secretInternalSetGoalAndPath(Goal goal) { - secretInternalSetGoal(goal); - return secretInternalPath(); + public boolean secretInternalSetGoalAndPath(PathingCommand command) { + secretInternalSetGoal(command.goal); + CalculationContext context; + if (command instanceof PathingCommandContext) { + context = ((PathingCommandContext) command).desiredCalcContext; + } else { + context = new CalculationContext(baritone, true); + } + return secretInternalPath(context); } @Override @@ -315,7 +322,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * * @return true if this call started path calculation, false if it was already calculating or executing a path */ - public boolean secretInternalPath() { + private boolean secretInternalPath(CalculationContext context) { if (goal == null) { return false; } @@ -331,7 +338,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return false; } queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true); + findPathInNewThread(pathStart(), true, context); return true; } } @@ -394,7 +401,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, * @param start * @param talkAboutIt */ - private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt) { + private void findPathInNewThread(final BlockPos start, final boolean talkAboutIt, CalculationContext context) { // this must be called with synchronization on pathCalcLock! // actually, we can check this, muahaha if (!Thread.holdsLock(pathCalcLock)) { @@ -404,6 +411,9 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, if (inProgress != null) { throw new IllegalStateException("Already doing it"); // should have been checked by caller } + if (!context.safeForThreadedUse) { + throw new IllegalStateException("Improper context thread safety level"); + } Goal goal = this.goal; if (goal == null) { logDebug("no goal"); // TODO should this be an exception too? definitely should be checked by caller @@ -418,7 +428,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, primaryTimeout = Baritone.settings().planAheadPrimaryTimeoutMS.get(); failureTimeout = Baritone.settings().planAheadFailureTimeoutMS.get(); } - CalculationContext context = new CalculationContext(baritone, true); // not safe to create on the other thread, it looks up a lot of stuff in minecraft AbstractNodeCostSearch pathfinder = createPathfinder(start, goal, current == null ? null : current.getPath(), context); if (!Objects.equals(pathfinder.getGoal(), goal)) { // will return the exact same object if simplification didn't happen logDebug("Simplifying " + goal.getClass() + " to GoalXZ due to distance"); @@ -499,7 +508,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, Goal transformed = goal; if (Baritone.settings().simplifyUnloadedYCoord.get() && goal instanceof IGoalRenderPos) { BlockPos pos = ((IGoalRenderPos) goal).getGoalPos(); - if (context.world.getChunk(pos) instanceof EmptyChunk) { + if (!context.bsi.worldContainsLoadedChunk(pos.getX(), pos.getZ())) { transformed = new GoalXZ(pos.getX(), pos.getZ()); } } diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 725ab569c..66ed3d93c 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -34,6 +34,8 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import static baritone.api.pathing.movement.ActionCosts.COST_INF; + /** * @author Brady * @since 8/7/2018 @@ -42,6 +44,7 @@ public class CalculationContext { private static final ItemStack STACK_BUCKET_WATER = new ItemStack(Items.WATER_BUCKET); + public final boolean safeForThreadedUse; public final IBaritone baritone; public final EntityPlayerSP player; public final World world; @@ -51,7 +54,7 @@ public class CalculationContext { public final boolean hasWaterBucket; public final boolean hasThrowaway; public final boolean canSprint; - public final double placeBlockCost; + protected final double placeBlockCost; // protected because you should call the function instead public final boolean allowBreak; public final boolean allowParkour; public final boolean allowParkourPlace; @@ -71,12 +74,12 @@ public class CalculationContext { } public CalculationContext(IBaritone baritone, boolean forUseOnAnotherThread) { + this.safeForThreadedUse = forUseOnAnotherThread; this.baritone = baritone; this.player = baritone.getPlayerContext().player(); this.world = baritone.getPlayerContext().world(); this.worldData = (WorldData) baritone.getWorldProvider().getCurrentWorld(); - this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); // TODO TODO TODO - // new CalculationContext() needs to happen, can't add an argument (i'll beat you), can we get the world provider from currentlyTicking? + this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); this.toolSet = new ToolSet(player); this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(baritone.getPlayerContext(), false); this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether(); @@ -125,14 +128,18 @@ public class CalculationContext { return get(x, y, z).getBlock(); } - public boolean canPlaceThrowawayAt(int x, int y, int z) { + public double costOfPlacingAt(int x, int y, int z) { if (!hasThrowaway) { // only true if allowPlace is true, see constructor - return false; + return COST_INF; } if (isPossiblyProtected(x, y, z)) { - return false; + return COST_INF; } - return worldBorder.canPlaceAt(x, z); // TODO perhaps MovementHelper.canPlaceAgainst could also use this? + if (!worldBorder.canPlaceAt(x, z)) { + // TODO perhaps MovementHelper.canPlaceAgainst could also use this? + return COST_INF; + } + return placeBlockCost; } public boolean canBreakAt(int x, int y, int z) { @@ -142,6 +149,10 @@ public class CalculationContext { return !isPossiblyProtected(x, y, z); } + public double placeBucketCost() { + return placeBlockCost; // shrug + } + public boolean isPossiblyProtected(int x, int y, int z) { // TODO more protection logic here; see #220 return false; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 9973e94b3..1faa5cf58 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -58,14 +58,16 @@ public class MovementAscend extends Movement { public static double cost(CalculationContext context, int x, int y, int z, int destX, int destZ) { IBlockState toPlace = context.get(destX, y, destZ); - boolean hasToPlace = false; + double additionalPlacementCost = 0; if (!MovementHelper.canWalkOn(context.bsi, destX, y, destZ, toPlace)) { - if (!context.canPlaceThrowawayAt(destX, y, destZ)) { + additionalPlacementCost = context.costOfPlacingAt(destX, y, destZ); + if (additionalPlacementCost >= COST_INF) { return COST_INF; } if (!MovementHelper.isReplacable(destX, y, destZ, toPlace, context.bsi)) { return COST_INF; } + boolean foundPlaceOption = false; for (int i = 0; i < 5; i++) { int againstX = destX + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getXOffset(); int againstY = y + HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i].getYOffset(); @@ -74,11 +76,11 @@ public class MovementAscend extends Movement { continue; } if (MovementHelper.canPlaceAgainst(context.bsi, againstX, againstY, againstZ)) { - hasToPlace = true; + foundPlaceOption = true; break; } } - if (!hasToPlace) { // didn't find a valid place =( + if (!foundPlaceOption) { // didn't find a valid place =( return COST_INF; } } @@ -129,10 +131,7 @@ public class MovementAscend extends Movement { walk += context.jumpPenalty; } - double totalCost = walk; - if (hasToPlace) { - totalCost += context.placeBlockCost; - } + double totalCost = walk + additionalPlacementCost; // start with srcUp2 since we already have its state // includeFalling isn't needed because of the falling check above -- if srcUp3 is falling we will have already exited with COST_INF if we'd actually have to break it totalCost += MovementHelper.getMiningDurationTicks(context, x, y + 2, z, srcUp2, false); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index ba915ac6d..800346a17 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -181,7 +181,7 @@ public class MovementDescend extends Movement { res.x = destX; res.y = newY + 1;// this is the block we're falling onto, so dest is +1 res.z = destZ; - res.cost = tentativeCost + context.placeBlockCost; + res.cost = tentativeCost + context.placeBucketCost(); return true; } if (unprotectedFallHeight <= context.maxFallHeightNoWater + 1) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 5bc5b1db5..09bdd73a1 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -125,9 +125,11 @@ public class MovementParkour extends Movement { if (!context.allowParkourPlace) { return; } + // time 2 pop off with that dank skynet parkour place int destX = x + 4 * xDiff; int destZ = z + 4 * zDiff; - if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) { + double placeCost = context.costOfPlacingAt(destX, y - 1, destZ); + if (placeCost >= COST_INF) { return; } IBlockState toReplace = context.get(destX, y - 1, destZ); @@ -145,7 +147,7 @@ public class MovementParkour extends Movement { res.x = destX; res.y = y; res.z = destZ; - res.cost = costFromJumpDistance(4) + context.placeBlockCost + context.jumpPenalty; + res.cost = costFromJumpDistance(4) + placeCost + context.jumpPenalty; return; } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index fafba24a2..81303be7d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -73,8 +73,13 @@ public class MovementPillar extends Movement { return LADDER_UP_ONE_COST; // allow ascending pillars of water, but only if we're already in one } } - if (!ladder && !context.canPlaceThrowawayAt(x, y, z)) { // we need to place a block where we started to jump on it - return COST_INF; + double placeCost = 0; + if (!ladder) { + // we need to place a block where we started to jump on it + placeCost = context.costOfPlacingAt(x, y, z); + if (placeCost >= COST_INF) { + return COST_INF; + } } if (from instanceof BlockLiquid || (fromDown.getBlock() instanceof BlockLiquid && context.assumeWalkOnWater)) { // otherwise, if we're standing in water, we cannot pillar @@ -112,7 +117,7 @@ public class MovementPillar extends Movement { if (ladder) { return LADDER_UP_ONE_COST + hardness * 5; } else { - return JUMP_ONE_BLOCK_COST + context.placeBlockCost + context.jumpPenalty + hardness; + return JUMP_ONE_BLOCK_COST + placeCost + context.jumpPenalty + hardness; } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 84e423589..b2fd416b9 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -114,7 +114,8 @@ public class MovementTraverse extends Movement { // this happens when assume walk on water is true and this is a traverse in water, which isn't allowed return COST_INF; } - if (!context.canPlaceThrowawayAt(destX, y - 1, destZ)) { + double placeCost = context.costOfPlacingAt(destX, y - 1, destZ); + if (placeCost >= COST_INF) { return COST_INF; } double hardness1 = MovementHelper.getMiningDurationTicks(context, destX, y, destZ, pb1, false); @@ -131,18 +132,18 @@ public class MovementTraverse extends Movement { continue; } if (MovementHelper.canPlaceAgainst(context.bsi, againstX, againstY, againstZ)) { // found a side place option - return WC + context.placeBlockCost + hardness1 + hardness2; + return WC + placeCost + hardness1 + hardness2; } } // now that we've checked all possible directions to side place, we actually need to backplace if (srcDown == Blocks.SOUL_SAND || (srcDown instanceof BlockSlab && !((BlockSlab) srcDown).isDouble())) { - return COST_INF; // can't sneak and backplace against soul sand or half slabs =/ + return COST_INF; // can't sneak and backplace against soul sand or half slabs (regardless of whether it's top half or bottom half) =/ } if (srcDown == Blocks.FLOWING_WATER || srcDown == Blocks.WATER) { return COST_INF; // this is obviously impossible } WC = WC * SNEAK_ONE_BLOCK_COST / WALK_ONE_BLOCK_COST;//since we are sneak backplacing, we are sneaking lol - return WC + context.placeBlockCost + hardness1 + hardness2; + return WC + placeCost + hardness1 + hardness2; } return COST_INF; } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java new file mode 100644 index 000000000..f01f7c04f --- /dev/null +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -0,0 +1,229 @@ +/* + * 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 . + */ + +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.PathingCommand; +import baritone.api.process.PathingCommandType; +import baritone.api.utils.BetterBlockPos; +import baritone.pathing.movement.CalculationContext; +import baritone.utils.BaritoneProcessHelper; +import baritone.utils.BlockStateInterface; +import baritone.utils.ISchematic; +import baritone.utils.PathingCommandContext; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.Vec3i; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +import static baritone.api.pathing.movement.ActionCosts.COST_INF; + +public class BuilderProcess extends BaritoneProcessHelper { + public BuilderProcess(Baritone baritone) { + super(baritone); + } + + private HashSet incorrectPositions; + private String name; + private ISchematic schematic; + private Vec3i origin; + + public boolean build(String schematicFile) { + File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); + NBTTagCompound tag; + try { + tag = CompressedStreamTools.read(file); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + if (tag == null) { + return false; + } + name = schematicFile; + schematic = parse(tag); + origin = ctx.playerFeet(); + return true; + } + + private static ISchematic parse(NBTTagCompound schematic) { + throw new UnsupportedOperationException("would rather die than parse " + schematic); + } + + @Override + public boolean isActive() { + return schematic != null; + } + + @Override + public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { + // TODO somehow tell inventorybehavior what we'd like to have on the hotbar + // perhaps take the 16 closest positions in incorrectPositions to ctx.playerFeet that aren't desired to be air, and then snag the top 4 most common block states, then request those on the hotbar + + + // this will work as is, but it'll be trashy + // need to iterate over incorrectPositions and see which ones we can "correct" from our current standing position + + // considerations: + // shouldn't break blocks that are supporting our current path segment, maybe? + // + return new PathingCommandContext(new GoalComposite(assemble()), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, new BuilderCalculationContext(schematic, origin)); + } + + private Goal[] assemble() { + BlockStateInterface bsi = new CalculationContext(baritone).bsi; + return incorrectPositions.stream().map(pos -> + bsi.get0(pos).getBlock() == Blocks.AIR ? + // it's air and it shouldn't be + new GoalBlock(pos.up()) + // it's a block and it shouldn't be + : new GoalGetToBlock(pos) // replace with GoalTwoBlocks to mine using pathfinding system only + ).toArray(Goal[]::new); + } + + @Override + public void onLostControl() { + incorrectPositions = null; + name = null; + schematic = null; + } + + @Override + public String displayName() { + return "Building " + name; + } + + /** + * Hotbar contents, if they were placed + *

+ * Always length nine, empty slots become Blocks.AIR.getDefaultState() + * + * @return + */ + public List placable() { + List result = new ArrayList<>(); + for (int i = 0; i < 9; i++) { + ItemStack stack = ctx.player().inventory.mainInventory.get(i); + if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) { + result.add(Blocks.AIR.getDefaultState()); + continue; + } + // + 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())); + // + } + return result; + } + + public class BuilderCalculationContext extends CalculationContext { + private final List placable; + private final ISchematic schematic; + private final int originX; + private final int originY; + private final int originZ; + + public BuilderCalculationContext(ISchematic schematic, Vec3i schematicOrigin) { + super(BuilderProcess.this.baritone, true); // wew lad + this.placable = placable(); + this.schematic = schematic; + this.originX = schematicOrigin.getX(); + this.originY = schematicOrigin.getY(); + this.originZ = schematicOrigin.getZ(); + } + + private IBlockState getSchematic(int x, int y, int z) { + if (schematic.inSchematic(x - originX, y - originY, z - originZ)) { + return schematic.desiredState(x - originX, y - originY, z - originZ); + } else { + return null; + } + } + + @Override + public double costOfPlacingAt(int x, int y, int z) { + if (isPossiblyProtected(x, y, z) || !worldBorder.canPlaceAt(x, z)) { // make calculation fail properly if we can't build + return COST_INF; + } + IBlockState sch = getSchematic(x, y, z); + if (sch != null) { + // TODO this can return true even when allowPlace is off.... is that an issue? + if (placable.contains(sch)) { + return 0; // thats right we gonna make it FREE to place a block where it should go in a structure + // no place block penalty at all 😎 + // i'm such an idiot that i just tried to copy and paste the epic gamer moment emoji too + // get added to unicode when? + } + if (!hasThrowaway) { + return COST_INF; + } + if (sch.getBlock() == Blocks.AIR) { + // we want this to be air, but they're asking if they can place here + // this won't be a schematic block, this will be a throwaway + return placeBlockCost * 2; // we're going to have to break it eventually + } else { + // we want it to be something that we don't have + // even more of a pain to place something wrong + return placeBlockCost * 3; + } + } else { + if (hasThrowaway) { + return placeBlockCost; + } else { + return COST_INF; + } + } + } + + @Override + public boolean canBreakAt(int x, int y, int z) { + if (!allowBreak || isPossiblyProtected(x, y, z)) { + return false; + } + IBlockState sch = getSchematic(x, y, z); + if (sch != null) { + if (sch.getBlock() == Blocks.AIR) { + // it should be air + // regardless of current contents, we can break it + return true; + } + // it should be a real block + // is it already that block? + return !bsi.get0(x, y, z).equals(sch); // can break if it's wrong + // TODO do blocks in render distace only? + // TODO allow breaking blocks that we have a tool to harvest and immediately place back? + } else { + return true; // why not lol + } + } + } +} diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 508a5e1bc..53b93aabb 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -239,6 +239,11 @@ public class ExampleBaritoneControl extends Behavior implements Helper { logDirect("Queued " + count + " chunks for repacking"); return true; } + if (msg.startsWith("build")) { + String file = msg.substring(5) + ".schematic"; + logDirect("" + baritone.getBuilderProcess().build(file)); + return true; + } if (msg.equals("axis")) { customGoalProcess.setGoalAndPath(new GoalAxis()); return true; diff --git a/src/main/java/baritone/utils/ISchematic.java b/src/main/java/baritone/utils/ISchematic.java new file mode 100644 index 000000000..db494c291 --- /dev/null +++ b/src/main/java/baritone/utils/ISchematic.java @@ -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 . + */ + +package baritone.utils; + +import net.minecraft.block.state.IBlockState; + +public interface ISchematic { + /** + * Does the block at this coordinate matter to the schematic? + *

+ * Normally just a check for if the coordinate is in the cube. + *

+ * 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 + * @param y + * @param z + * @return + */ + boolean inSchematic(int x, int y, int z); + + IBlockState desiredState(int x, int y, int z); +} \ No newline at end of file diff --git a/src/main/java/baritone/utils/PathingCommandContext.java b/src/main/java/baritone/utils/PathingCommandContext.java new file mode 100644 index 000000000..1e8bfe6a4 --- /dev/null +++ b/src/main/java/baritone/utils/PathingCommandContext.java @@ -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 . + */ + +package baritone.utils; + +import baritone.api.pathing.goals.Goal; +import baritone.api.process.PathingCommand; +import baritone.api.process.PathingCommandType; +import baritone.pathing.movement.CalculationContext; + +public class PathingCommandContext extends PathingCommand { + public final CalculationContext desiredCalcContext; + + public PathingCommandContext(Goal goal, PathingCommandType commandType, CalculationContext context) { + super(goal, commandType); + this.desiredCalcContext = context; + } +} diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index f5fff5460..97685ac0a 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -98,18 +98,18 @@ public class PathingControlManager implements IPathingControlManager { break; case FORCE_REVALIDATE_GOAL_AND_PATH: if (!p.isPathing() && !p.getInProgress().isPresent()) { - p.secretInternalSetGoalAndPath(command.goal); + p.secretInternalSetGoalAndPath(command); } break; case REVALIDATE_GOAL_AND_PATH: if (!p.isPathing() && !p.getInProgress().isPresent()) { - p.secretInternalSetGoalAndPath(command.goal); + p.secretInternalSetGoalAndPath(command); } break; case SET_GOAL_AND_PATH: // now this i can do if (command.goal != null) { - baritone.getPathingBehavior().secretInternalSetGoalAndPath(command.goal); + baritone.getPathingBehavior().secretInternalSetGoalAndPath(command); } break; default: @@ -132,13 +132,13 @@ public class PathingControlManager implements IPathingControlManager { // pwnage p.softCancelIfSafe(); } - p.secretInternalSetGoalAndPath(command.goal); + p.secretInternalSetGoalAndPath(command); break; case REVALIDATE_GOAL_AND_PATH: if (Baritone.settings().cancelOnGoalInvalidation.get() && (command.goal == null || revalidateGoal(command.goal))) { p.softCancelIfSafe(); } - p.secretInternalSetGoalAndPath(command.goal); + p.secretInternalSetGoalAndPath(command); break; default: } From c45cbebcce4f8ad12cd37a898af72fc10424aa68 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 27 Dec 2018 08:06:10 -1000 Subject: [PATCH 02/41] fixed --- src/main/java/baritone/process/BuilderProcess.java | 8 ++++++-- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index f01f7c04f..8bb966ea3 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -41,6 +41,7 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.Vec3i; import java.io.File; +import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; @@ -60,9 +61,11 @@ public class BuilderProcess extends BaritoneProcessHelper { public boolean build(String schematicFile) { File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); + System.out.println(file + " " + file.exists()); + NBTTagCompound tag; - try { - tag = CompressedStreamTools.read(file); + try (FileInputStream fileIn = new FileInputStream(file)) { + tag = CompressedStreamTools.readCompressed(fileIn); } catch (IOException e) { e.printStackTrace(); return false; @@ -107,6 +110,7 @@ public class BuilderProcess extends BaritoneProcessHelper { // it's air and it shouldn't be new GoalBlock(pos.up()) // it's a block and it shouldn't be + // todo disallow right above : new GoalGetToBlock(pos) // replace with GoalTwoBlocks to mine using pathfinding system only ).toArray(Goal[]::new); } diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 53b93aabb..550095756 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -240,7 +240,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.startsWith("build")) { - String file = msg.substring(5) + ".schematic"; + String file = msg.substring(6) + ".schematic"; logDirect("" + baritone.getBuilderProcess().build(file)); return true; } From 702b9169485010daec4b8581750595aa06f6c0b6 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 8 Jan 2019 20:45:02 -0800 Subject: [PATCH 03/41] preliminary schematic stuff --- .../api/pathing/goals/GoalGetToBlock.java | 6 +- .../baritone/behavior/PathingBehavior.java | 9 +- .../pathing/movement/CalculationContext.java | 9 +- .../pathing/movement/MovementHelper.java | 4 +- .../movement/movements/MovementAscend.java | 6 + .../movement/movements/MovementPillar.java | 4 +- .../java/baritone/process/BuilderProcess.java | 200 +++++++++++++++--- src/main/java/baritone/utils/ISchematic.java | 6 + .../java/baritone/utils/MapArtSchematic.java | 52 +++++ src/main/java/baritone/utils/Schematic.java | 93 ++++++++ 10 files changed, 346 insertions(+), 43 deletions(-) create mode 100644 src/main/java/baritone/utils/MapArtSchematic.java create mode 100644 src/main/java/baritone/utils/Schematic.java diff --git a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java index c4856cdd6..fb2a07aaf 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalGetToBlock.java @@ -28,9 +28,9 @@ import net.minecraft.util.math.BlockPos; */ public class GoalGetToBlock implements Goal, IGoalRenderPos { - private final int x; - private final int y; - private final int z; + public final int x; + public final int y; + public final int z; public GoalGetToBlock(BlockPos pos) { this.x = pos.getX(); diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index a75091737..060205984 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -57,6 +57,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private boolean safeToCancel; private boolean pauseRequestedLastTick; + private boolean unpausedLastTick; private boolean cancelRequested; private boolean calcFailedLastTick; @@ -102,10 +103,14 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private void tickPath() { if (pauseRequestedLastTick && safeToCancel) { pauseRequestedLastTick = false; - baritone.getInputOverrideHandler().clearAllKeys(); - baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); + if (unpausedLastTick) { + baritone.getInputOverrideHandler().clearAllKeys(); + baritone.getInputOverrideHandler().getBlockBreakHelper().stopBreakingBlock(); + } + unpausedLastTick = false; return; } + unpausedLastTick = true; if (cancelRequested) { cancelRequested = false; baritone.getInputOverrideHandler().clearAllKeys(); diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 66ed3d93c..4611d9755 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -142,11 +142,14 @@ public class CalculationContext { return placeBlockCost; } - public boolean canBreakAt(int x, int y, int z) { + public double breakCostMultiplierAt(int x, int y, int z) { if (!allowBreak) { - return false; + return COST_INF; } - return !isPossiblyProtected(x, y, z); + if (isPossiblyProtected(x, y, z)) { + return COST_INF; + } + return 1; } public double placeBucketCost() { diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index d07f05e78..96c4a7690 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -341,7 +341,8 @@ public interface MovementHelper extends ActionCosts, Helper { static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, IBlockState state, boolean includeFalling) { Block block = state.getBlock(); if (!canWalkThrough(context.bsi, x, y, z, state)) { - if (!context.canBreakAt(x, y, z)) { + double mult = context.breakCostMultiplierAt(x, y, z); + if (mult >= COST_INF) { return COST_INF; } if (avoidBreaking(context.bsi, x, y, z, state)) { @@ -358,6 +359,7 @@ public interface MovementHelper extends ActionCosts, Helper { double result = m / strVsBlock; result += context.breakBlockAdditionalCost; + result *= mult; if (includeFalling) { IBlockState above = context.get(x, y + 1, z); if (above.getBlock() instanceof BlockFalling) { diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 7da7ad159..5fafdeedc 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -240,4 +240,10 @@ public class MovementAscend extends Movement { } return true; } + + @Override + public boolean safeToCancel(MovementState state) { + // if we had to place, don't allow pause + return state.getStatus() != MovementStatus.RUNNING || ticksWithoutPlacement == 0; + } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index dd93eeed0..18a248c18 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -35,6 +35,8 @@ import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; +import java.util.Objects; + public class MovementPillar extends Movement { public MovementPillar(IBaritone baritone, BetterBlockPos start, BetterBlockPos end) { @@ -229,7 +231,7 @@ public class MovementPillar extends Movement { if (!(fr instanceof BlockAir || fr.isReplaceable(ctx.world(), src))) { state.setInput(Input.CLICK_LEFT, true); blockIsThere = false; - } else if (ctx.player().isSneaking()) { // 1 tick after we're able to place + } else if (ctx.player().isSneaking() && (Objects.equals(src.down(), ctx.objectMouseOver().getBlockPos()) || Objects.equals(src, ctx.objectMouseOver().getBlockPos()))) { // 1 tick after we're able to place state.setInput(Input.CLICK_RIGHT, true); } } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 8bb966ea3..27142120f 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -25,11 +25,15 @@ import baritone.api.pathing.goals.GoalGetToBlock; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.Rotation; +import baritone.api.utils.RotationUtils; +import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; +import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; -import baritone.utils.BlockStateInterface; import baritone.utils.ISchematic; import baritone.utils.PathingCommandContext; +import baritone.utils.Schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; @@ -38,14 +42,15 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; +import net.minecraft.util.Tuple; +import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; +import java.util.*; +import java.util.stream.Collectors; import static baritone.api.pathing.movement.ActionCosts.COST_INF; @@ -80,7 +85,7 @@ public class BuilderProcess extends BaritoneProcessHelper { } private static ISchematic parse(NBTTagCompound schematic) { - throw new UnsupportedOperationException("would rather die than parse " + schematic); + return new Schematic(schematic); } @Override @@ -88,6 +93,32 @@ public class BuilderProcess extends BaritoneProcessHelper { return schematic != null; } + public Optional> toBreakNearPlayer(BuilderCalculationContext bcc) { + BetterBlockPos center = ctx.playerFeet(); + for (int dx = -5; dx <= 5; dx++) { + for (int dy = 0; dy <= 5; dy++) { + for (int dz = -5; dz <= 5; dz++) { + int x = center.x + dx; + int y = center.y + dy; + int z = center.z + dz; + IBlockState desired = bcc.getSchematic(x, y, z); + if (desired == null) { + continue; // irrelevant + } + IBlockState curr = bcc.bsi.get0(x, y, z); + if (curr.getBlock() != Blocks.AIR && !valid(curr, desired)) { + BetterBlockPos pos = new BetterBlockPos(x, y, z); + Optional rot = RotationUtils.reachable(ctx.player(), pos, ctx.playerController().getBlockReachDistance()); + if (rot.isPresent()) { + return Optional.of(new Tuple<>(pos, rot.get())); + } + } + } + } + } + return Optional.empty(); + } + @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { // TODO somehow tell inventorybehavior what we'd like to have on the hotbar @@ -97,22 +128,113 @@ public class BuilderProcess extends BaritoneProcessHelper { // this will work as is, but it'll be trashy // need to iterate over incorrectPositions and see which ones we can "correct" from our current standing position - // considerations: - // shouldn't break blocks that are supporting our current path segment, maybe? - // - return new PathingCommandContext(new GoalComposite(assemble()), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, new BuilderCalculationContext(schematic, origin)); + + BuilderCalculationContext bcc = new BuilderCalculationContext(schematic, origin); + if (!recalc(bcc)) { + logDirect("Done building"); + onLostControl(); + return null; + } + Optional> toBreak = toBreakNearPlayer(bcc); + baritone.getInputOverrideHandler().clearAllKeys(); + if (toBreak.isPresent() && isSafeToCancel && ctx.player().onGround) { + // we'd like to pause to break this block + // only change look direction if it's safe (don't want to fuck up an in progress parkour for example + Rotation rot = toBreak.get().getSecond(); + BetterBlockPos pos = toBreak.get().getFirst(); + baritone.getLookBehavior().updateTarget(rot, true); + MovementHelper.switchToBestToolFor(ctx, bcc.get(pos)); + if (Objects.equals(ctx.objectMouseOver().getBlockPos(), rot) || ctx.playerRotations().isReallyCloseTo(rot)) { + baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); + } + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } + + Goal[] goals = assemble(bcc); + if (goals.length == 0) { + logDirect("Unable to do it =("); + onLostControl(); + return null; + } + return new PathingCommandContext(new GoalComposite(goals), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc); } - private Goal[] assemble() { - BlockStateInterface bsi = new CalculationContext(baritone).bsi; - return incorrectPositions.stream().map(pos -> - bsi.get0(pos).getBlock() == Blocks.AIR ? - // it's air and it shouldn't be - new GoalBlock(pos.up()) - // it's a block and it shouldn't be - // todo disallow right above - : new GoalGetToBlock(pos) // replace with GoalTwoBlocks to mine using pathfinding system only - ).toArray(Goal[]::new); + public boolean recalc(BuilderCalculationContext bcc) { + if (incorrectPositions == null) { + incorrectPositions = new HashSet<>(); + fullRecalc(bcc); + if (incorrectPositions.isEmpty()) { + return false; + } + } + recalcNearby(bcc); + if (incorrectPositions.isEmpty()) { + fullRecalc(bcc); + } + return !incorrectPositions.isEmpty(); + } + + public void recalcNearby(BuilderCalculationContext bcc) { + BetterBlockPos center = ctx.playerFeet(); + for (int dx = -5; dx <= 5; dx++) { + for (int dy = -5; dy <= 5; dy++) { + for (int dz = -5; dz <= 5; dz++) { + int x = center.x + dx; + int y = center.y + dy; + int z = center.z + dz; + IBlockState desired = bcc.getSchematic(x, y, z); + if (desired != null) { + // we care about this position + if (valid(bcc.bsi.get0(x, y, z), desired)) { + incorrectPositions.remove(new BetterBlockPos(x, y, z)); + } else { + incorrectPositions.add(new BetterBlockPos(x, y, z)); + } + } + } + } + } + } + + public void fullRecalc(BuilderCalculationContext bcc) { + incorrectPositions = new HashSet<>(); + for (int y = 0; y < schematic.heightY(); y++) { + for (int z = 0; z < schematic.lengthZ(); z++) { + for (int x = 0; x < schematic.widthX(); x++) { + if (schematic.inSchematic(x, y, z)) { + if (!valid(bcc.bsi.get0(x + origin.getX(), y + origin.getY(), z + origin.getZ()), schematic.desiredState(x, y, z))) { + incorrectPositions.add(new BetterBlockPos(x + origin.getX(), y + origin.getY(), z + origin.getZ())); + } + } + } + } + } + } + + private Goal[] assemble(BuilderCalculationContext bcc) { + List approxPlacable = placable(); + List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); + if (!placable.isEmpty()) { + return placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(BetterBlockPos::up).map(GoalBlock::new).toArray(Goal[]::new); + } + return incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); + } + + 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 (x == this.x && y == this.y + 1 && z == this.z) { + return false; + } + // but any other adjacent works for breaking, including inside or below + return super.isInGoal(x, y, z); + } } @Override @@ -149,6 +271,11 @@ public class BuilderProcess extends BaritoneProcessHelper { return result; } + public boolean valid(IBlockState current, IBlockState desired) { + // TODO more complicated comparison logic I guess + return desired == null || current.equals(desired); + } + public class BuilderCalculationContext extends CalculationContext { private final List placable; private final ISchematic schematic; @@ -181,6 +308,11 @@ public class BuilderProcess extends BaritoneProcessHelper { IBlockState sch = getSchematic(x, y, z); if (sch != null) { // TODO this can return true even when allowPlace is off.... is that an issue? + if (sch.getBlock() == Blocks.AIR) { + // we want this to be air, but they're asking if they can place here + // this won't be a schematic block, this will be a throwaway + return placeBlockCost * 2; // we're going to have to break it eventually + } if (placable.contains(sch)) { return 0; // thats right we gonna make it FREE to place a block where it should go in a structure // no place block penalty at all 😎 @@ -190,15 +322,9 @@ public class BuilderProcess extends BaritoneProcessHelper { if (!hasThrowaway) { return COST_INF; } - if (sch.getBlock() == Blocks.AIR) { - // we want this to be air, but they're asking if they can place here - // this won't be a schematic block, this will be a throwaway - return placeBlockCost * 2; // we're going to have to break it eventually - } else { - // we want it to be something that we don't have - // even more of a pain to place something wrong - return placeBlockCost * 3; - } + // we want it to be something that we don't have + // even more of a pain to place something wrong + return placeBlockCost * 3; } else { if (hasThrowaway) { return placeBlockCost; @@ -209,24 +335,32 @@ public class BuilderProcess extends BaritoneProcessHelper { } @Override - public boolean canBreakAt(int x, int y, int z) { + public double breakCostMultiplierAt(int x, int y, int z) { if (!allowBreak || isPossiblyProtected(x, y, z)) { - return false; + return COST_INF; } IBlockState sch = getSchematic(x, y, z); if (sch != null) { if (sch.getBlock() == Blocks.AIR) { // it should be air // regardless of current contents, we can break it - return true; + return 1; } // it should be a real block // is it already that block? - return !bsi.get0(x, y, z).equals(sch); // can break if it's wrong + if (valid(bsi.get0(x, y, z), sch)) { + return 3; + } else { + // can break if it's wrong + // would be great to return less than 1 here, but that would actually make the cost calculation messed up + // since we're breaking a block, if we underestimate the cost, then it'll fail when it really takes the correct amount of time + return 1; + + } // TODO do blocks in render distace only? // TODO allow breaking blocks that we have a tool to harvest and immediately place back? } else { - return true; // why not lol + return 1; // why not lol } } } diff --git a/src/main/java/baritone/utils/ISchematic.java b/src/main/java/baritone/utils/ISchematic.java index db494c291..b68f1a1c5 100644 --- a/src/main/java/baritone/utils/ISchematic.java +++ b/src/main/java/baritone/utils/ISchematic.java @@ -36,4 +36,10 @@ public interface ISchematic { boolean inSchematic(int x, int y, int z); IBlockState desiredState(int x, int y, int z); + + int widthX(); + + int heightY(); + + int lengthZ(); } \ No newline at end of file diff --git a/src/main/java/baritone/utils/MapArtSchematic.java b/src/main/java/baritone/utils/MapArtSchematic.java new file mode 100644 index 000000000..9813b6373 --- /dev/null +++ b/src/main/java/baritone/utils/MapArtSchematic.java @@ -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 . + */ + +package baritone.utils; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.nbt.NBTTagCompound; + +public class MapArtSchematic extends Schematic { + private final int[][] heightMap; + + public MapArtSchematic(NBTTagCompound schematic) { + super(schematic); + heightMap = new int[widthX][lengthZ]; + for (int x = 0; x < widthX; x++) { + https: + for (int z = 0; z < lengthZ; z++) { + IBlockState[] column = states[x][z]; + for (int y = heightY - 1; y >= 0; y--) { + if (column[y].getBlock() != Blocks.AIR) { + heightMap[x][z] = y; + continue https; + } + } + System.out.println("Column " + x + "," + z + " has no blocks, but it's apparently map art? wtf"); + System.out.println("Letting it be whatever"); + heightMap[x][z] = 256; + } + } + } + + @Override + public boolean inSchematic(int x, int y, int z) { + // in map art, we only care about coordinates in or above the art + return super.inSchematic(x, y, z) && y >= heightMap[x][z]; + } +} diff --git a/src/main/java/baritone/utils/Schematic.java b/src/main/java/baritone/utils/Schematic.java new file mode 100644 index 000000000..dbc80a733 --- /dev/null +++ b/src/main/java/baritone/utils/Schematic.java @@ -0,0 +1,93 @@ +/* + * 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 . + */ + +package baritone.utils; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.nbt.NBTTagCompound; + +public class Schematic implements ISchematic { + public final int widthX; + public final int heightY; + public final int lengthZ; + protected final IBlockState[][][] states; + + public Schematic(NBTTagCompound schematic) { + String type = schematic.getString("Materials"); + if (!type.equals("Alpha")) { + throw new IllegalStateException("bad schematic " + type); + } + widthX = schematic.getInteger("Width"); + heightY = schematic.getInteger("Height"); + lengthZ = schematic.getInteger("Length"); + byte[] blocks = schematic.getByteArray("Blocks"); + byte[] metadata = schematic.getByteArray("Data"); + + byte[] additional = null; + if (schematic.hasKey("AddBlocks")) { + byte[] addBlocks = schematic.getByteArray("AddBlocks"); + additional = new byte[addBlocks.length * 2]; + for (int i = 0; i < addBlocks.length; i++) { + additional[i * 2 + 0] = (byte) ((addBlocks[i] >> 4) & 0xF); // lower nibble + additional[i * 2 + 1] = (byte) ((addBlocks[i] >> 0) & 0xF); // upper nibble + } + } + states = new IBlockState[widthX][lengthZ][heightY]; + for (int y = 0; y < heightY; y++) { + for (int z = 0; z < lengthZ; z++) { + for (int x = 0; x < widthX; x++) { + int blockInd = (y * lengthZ + z) * widthX + x; + + int blockID = blocks[blockInd] & 0xFF; + if (additional != null) { + // additional is 0 through 15 inclusive since it's & 0xF above + blockID |= additional[blockInd] << 8; + } + Block block = Block.REGISTRY.getObjectById(blockID); + int meta = metadata[blockInd] & 0xFF; + states[x][z][y] = block.getStateFromMeta(meta); + } + } + } + } + + @Override + public boolean inSchematic(int x, int y, int z) { + return x >= 0 && x < widthX && y >= 0 && y < heightY && z >= 0 && z < lengthZ; + } + + @Override + public IBlockState desiredState(int x, int y, int z) { + return states[x][z][y]; + } + + @Override + public int widthX() { + return widthX; + } + + @Override + public int heightY() { + return heightY; + } + + @Override + public int lengthZ() { + return lengthZ; + } +} From c74c01271d54a48c52826c0be7361c40c0cc7ff8 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 9 Jan 2019 14:36:44 -0800 Subject: [PATCH 04/41] better strategy --- .../baritone/api/pathing/goals/GoalBlock.java | 6 +++--- .../pathing/movement/CalculationContext.java | 2 +- .../movement/movements/MovementTraverse.java | 14 ++++++++++++-- .../java/baritone/process/BuilderProcess.java | 17 +++++++++++++++-- 4 files changed, 31 insertions(+), 8 deletions(-) diff --git a/src/api/java/baritone/api/pathing/goals/GoalBlock.java b/src/api/java/baritone/api/pathing/goals/GoalBlock.java index e0a60b59a..89dd63048 100644 --- a/src/api/java/baritone/api/pathing/goals/GoalBlock.java +++ b/src/api/java/baritone/api/pathing/goals/GoalBlock.java @@ -30,17 +30,17 @@ public class GoalBlock implements Goal, IGoalRenderPos { /** * The X block position of this goal */ - private final int x; + public final int x; /** * The Y block position of this goal */ - private final int y; + public final int y; /** * The Z block position of this goal */ - private final int z; + public final int z; public GoalBlock(BlockPos pos) { this(pos.getX(), pos.getY(), pos.getZ()); diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 4611d9755..95887efde 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -65,7 +65,7 @@ public class CalculationContext { public final int maxFallHeightBucket; public final double waterWalkSpeed; public final double breakBlockAdditionalCost; - public final double jumpPenalty; + public double jumpPenalty; public final double walkOnWaterOnePenalty; public final BetterWorldBorder worldBorder; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 9f7c0fdf1..57bc333ce 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -275,14 +275,24 @@ public class MovementTraverse extends Movement { double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; double faceY = (dest.getY() + against1.getY()) * 0.5D; double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true)); + Rotation rot = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); + state.setTarget(new MovementState.MovementTarget(rot, true)); EnumFacing side = ctx.objectMouseOver().sideHit; if (Objects.equals(ctx.getSelectedBlock().orElse(null), against1) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && ctx.getSelectedBlock().get().offset(side).equals(positionToPlace)) { return state.setInput(Input.CLICK_RIGHT, true); } + if (ctx.playerRotations().isReallyCloseTo(rot)) { + double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); + if (dist > 0.83) { + // might need to go forward a bit + return state.setInput(Input.MOVE_FORWARD, true); + } + // don't left click for one tick + return state.setInput(Input.CLICK_LEFT, true); + } + return state; //System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); - return state.setInput(Input.CLICK_LEFT, true); } } if (!Baritone.settings().assumeSafeWalk.get()) { diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 27142120f..b4b137251 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -215,7 +215,7 @@ public class BuilderProcess extends BaritoneProcessHelper { List approxPlacable = placable(); List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); if (!placable.isEmpty()) { - return placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(BetterBlockPos::up).map(GoalBlock::new).toArray(Goal[]::new); + return placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(GoalPlace::new).toArray(Goal[]::new); } return incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); } @@ -229,7 +229,7 @@ public class BuilderProcess extends BaritoneProcessHelper { @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 (x == this.x && y == this.y + 1 && z == this.z) { + if (y > this.y) { return false; } // but any other adjacent works for breaking, including inside or below @@ -237,6 +237,17 @@ public class BuilderProcess extends BaritoneProcessHelper { } } + public static class GoalPlace extends GoalBlock { + public GoalPlace(BlockPos placeAt) { + super(placeAt.up()); + } + + public double heuristic(int x, int y, int z) { + // prioritize lower y coordinates + return this.y * 100 + super.heuristic(x, y, z); + } + } + @Override public void onLostControl() { incorrectPositions = null; @@ -290,6 +301,8 @@ public class BuilderProcess extends BaritoneProcessHelper { this.originX = schematicOrigin.getX(); this.originY = schematicOrigin.getY(); this.originZ = schematicOrigin.getZ(); + + this.jumpPenalty += 10; } private IBlockState getSchematic(int x, int y, int z) { From b109fc742093ccb9e2a1bf05afa9de7ce9fbef03 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 9 Jan 2019 15:07:06 -0800 Subject: [PATCH 05/41] fun =) --- .../movement/movements/MovementTraverse.java | 2 +- .../java/baritone/process/BuilderProcess.java | 41 +++++++++++++++---- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 57bc333ce..1c5c4f2ea 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -279,7 +279,7 @@ public class MovementTraverse extends Movement { state.setTarget(new MovementState.MovementTarget(rot, true)); EnumFacing side = ctx.objectMouseOver().sideHit; - if (Objects.equals(ctx.getSelectedBlock().orElse(null), against1) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) && ctx.getSelectedBlock().get().offset(side).equals(positionToPlace)) { + if ((Objects.equals(ctx.getSelectedBlock(), dest.down()) || (Objects.equals(ctx.getSelectedBlock().orElse(null), against1) && ctx.getSelectedBlock().get().offset(side).equals(positionToPlace))) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get())) { return state.setInput(Input.CLICK_RIGHT, true); } if (ctx.playerRotations().isReallyCloseTo(rot)) { diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index b4b137251..e64a66274 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -150,13 +150,13 @@ public class BuilderProcess extends BaritoneProcessHelper { return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } - Goal[] goals = assemble(bcc); - if (goals.length == 0) { + Goal goal = assemble(bcc); + if (goal == null) { logDirect("Unable to do it =("); onLostControl(); return null; } - return new PathingCommandContext(new GoalComposite(goals), PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc); + return new PathingCommandContext(goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc); } public boolean recalc(BuilderCalculationContext bcc) { @@ -211,13 +211,40 @@ public class BuilderProcess extends BaritoneProcessHelper { } } - private Goal[] assemble(BuilderCalculationContext bcc) { + private Goal assemble(BuilderCalculationContext bcc) { List approxPlacable = placable(); List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); - if (!placable.isEmpty()) { - return placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(GoalPlace::new).toArray(Goal[]::new); + Goal[] toBreak = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); + Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(GoalPlace::new).toArray(Goal[]::new); + + if (toPlace.length != 0) { + return new JankyGoalComposite(new GoalComposite(toPlace), new GoalComposite(toBreak)); + } + if (toBreak.length == 0) { + return null; + } + return new GoalComposite(toBreak); + } + + public static class JankyGoalComposite implements Goal { + private final Goal primary; + private final Goal fallback; + + public JankyGoalComposite(Goal primary, Goal fallback) { + this.primary = primary; + this.fallback = fallback; + } + + + @Override + public boolean isInGoal(int x, int y, int z) { + return primary.isInGoal(x, y, z) || fallback.isInGoal(x, y, z); + } + + @Override + public double heuristic(int x, int y, int z) { + return primary.heuristic(x, y, z); } - return incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); } public static class GoalBreak extends GoalGetToBlock { From 1dca02517e412565071ef95d0a1a5fe19dd99bbd Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 9 Jan 2019 15:42:49 -0800 Subject: [PATCH 06/41] disable backtrack cost favoring while building --- src/main/java/baritone/behavior/PathingBehavior.java | 2 +- .../baritone/pathing/movement/CalculationContext.java | 2 ++ src/main/java/baritone/process/BuilderProcess.java | 1 + src/main/java/baritone/utils/pathing/Favoring.java | 10 +++++----- .../baritone/utils/pathing/SegmentedCalculator.java | 2 +- 5 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 060205984..b789b0966 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -517,7 +517,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, transformed = new GoalXZ(pos.getX(), pos.getZ()); } } - Favoring favoring = new Favoring(context.getBaritone().getPlayerContext(), previous); + Favoring favoring = new Favoring(context.getBaritone().getPlayerContext(), previous, context); return new AStarPathFinder(start.getX(), start.getY(), start.getZ(), transformed, favoring, context); } diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 95887efde..03fa6ddb5 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -65,6 +65,7 @@ public class CalculationContext { public final int maxFallHeightBucket; public final double waterWalkSpeed; public final double breakBlockAdditionalCost; + public double backtrackCostFavoringCoefficient; public double jumpPenalty; public final double walkOnWaterOnePenalty; public final BetterWorldBorder worldBorder; @@ -100,6 +101,7 @@ public class CalculationContext { float mult = depth / 3.0F; this.waterWalkSpeed = ActionCosts.WALK_ONE_IN_WATER_COST * (1 - mult) + ActionCosts.WALK_ONE_BLOCK_COST * mult; this.breakBlockAdditionalCost = Baritone.settings().blockBreakAdditionalPenalty.get(); + this.backtrackCostFavoringCoefficient = Baritone.settings().backtrackCostFavoringCoefficient.get(); this.jumpPenalty = Baritone.settings().jumpPenalty.get(); this.walkOnWaterOnePenalty = Baritone.settings().walkOnWaterOnePenalty.get(); // why cache these things here, why not let the movements just get directly from settings? diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index e64a66274..a679c0287 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -330,6 +330,7 @@ public class BuilderProcess extends BaritoneProcessHelper { this.originZ = schematicOrigin.getZ(); this.jumpPenalty += 10; + this.backtrackCostFavoringCoefficient = 1; } private IBlockState getSchematic(int x, int y, int z) { diff --git a/src/main/java/baritone/utils/pathing/Favoring.java b/src/main/java/baritone/utils/pathing/Favoring.java index 7ffe49ffd..8a6017582 100644 --- a/src/main/java/baritone/utils/pathing/Favoring.java +++ b/src/main/java/baritone/utils/pathing/Favoring.java @@ -17,27 +17,27 @@ package baritone.utils.pathing; -import baritone.Baritone; import baritone.api.pathing.calc.IPath; import baritone.api.utils.BetterBlockPos; import baritone.api.utils.IPlayerContext; +import baritone.pathing.movement.CalculationContext; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; public final class Favoring { private final Long2DoubleOpenHashMap favorings; - public Favoring(IPlayerContext ctx, IPath previous) { - this(previous); + public Favoring(IPlayerContext ctx, IPath previous, CalculationContext context) { + this(previous, context); for (Avoidance avoid : Avoidance.create(ctx)) { avoid.applySpherical(favorings); } System.out.println("Favoring size: " + favorings.size()); } - public Favoring(IPath previous) { // create one just from previous path, no mob avoidances + public Favoring(IPath previous, CalculationContext context) { // create one just from previous path, no mob avoidances favorings = new Long2DoubleOpenHashMap(); favorings.defaultReturnValue(1.0D); - double coeff = Baritone.settings().backtrackCostFavoringCoefficient.get(); + double coeff = context.backtrackCostFavoringCoefficient; if (coeff != 1D && previous != null) { previous.positions().forEach(pos -> favorings.put(BetterBlockPos.longHash(pos), coeff)); } diff --git a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java index e1d6dd106..523825ab8 100644 --- a/src/main/java/baritone/utils/pathing/SegmentedCalculator.java +++ b/src/main/java/baritone/utils/pathing/SegmentedCalculator.java @@ -87,7 +87,7 @@ public class SegmentedCalculator { private PathCalculationResult segment(Optional previous) { BetterBlockPos segmentStart = previous.map(IPath::getDest).orElse(start); // <-- e p i c - AbstractNodeCostSearch search = new AStarPathFinder(segmentStart.x, segmentStart.y, segmentStart.z, goal, new Favoring(previous.orElse(null)), context); // this is on another thread, so cannot include mob avoidances. + AbstractNodeCostSearch search = new AStarPathFinder(segmentStart.x, segmentStart.y, segmentStart.z, goal, new Favoring(previous.orElse(null), context), context); // this is on another thread, so cannot include mob avoidances. return search.calculate(Baritone.settings().primaryTimeoutMS.get(), Baritone.settings().failureTimeoutMS.get()); // use normal time settings, not the plan ahead settings, so as to not overwhelm the computer } From 1381d8d94c07629c807c76e8e238522b1638b458 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 10 Jan 2019 13:50:53 -0800 Subject: [PATCH 07/41] two small tweaks --- .../baritone/pathing/movement/movements/MovementPillar.java | 3 +++ src/main/java/baritone/utils/PathingControlManager.java | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 18a248c18..92ac6cbee 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -82,6 +82,9 @@ public class MovementPillar extends Movement { if (placeCost >= COST_INF) { return COST_INF; } + if (fromDown.getBlock() == Blocks.AIR) { + placeCost += 0.1; // slightly (1/200th of a second) penalize pillaring on what's currently air + } } if (from instanceof BlockLiquid || (fromDown.getBlock() instanceof BlockLiquid && context.assumeWalkOnWater)) { // otherwise, if we're standing in water, we cannot pillar diff --git a/src/main/java/baritone/utils/PathingControlManager.java b/src/main/java/baritone/utils/PathingControlManager.java index 1368658b8..d98790882 100644 --- a/src/main/java/baritone/utils/PathingControlManager.java +++ b/src/main/java/baritone/utils/PathingControlManager.java @@ -82,11 +82,12 @@ public class PathingControlManager implements IPathingControlManager { public void preTick() { inControlLastTick = inControlThisTick; + PathingBehavior p = baritone.getPathingBehavior(); command = doTheStuff(); if (command == null) { + p.cancelSegmentIfSafe(); return; } - PathingBehavior p = baritone.getPathingBehavior(); switch (command.commandType) { case REQUEST_PAUSE: p.requestPause(); From 81786f7a7cb73b1064c7fdd4a7677519049abb0e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 10 Jan 2019 13:51:26 -0800 Subject: [PATCH 08/41] reuse calculationcontext for planning ahead next segment --- .../baritone/behavior/PathingBehavior.java | 54 ++++++++----------- 1 file changed, 23 insertions(+), 31 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index b789b0966..767de6b86 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -54,6 +54,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, private PathExecutor next; private Goal goal; + private CalculationContext context; private boolean safeToCancel; private boolean pauseRequestedLastTick; @@ -155,7 +156,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, return; } queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true, new CalculationContext(baritone, true)); + findPathInNewThread(pathStart(), true, context); } return; } @@ -190,7 +191,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // and this path has 5 seconds or less left logDebug("Path almost over. Planning ahead..."); queuePathEvent(PathEvent.NEXT_SEGMENT_CALC_STARTED); - findPathInNewThread(current.getPath().getDest(), false, new CalculationContext(baritone, true)); + findPathInNewThread(current.getPath().getDest(), false, context); } } } @@ -227,13 +228,31 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, public boolean secretInternalSetGoalAndPath(PathingCommand command) { secretInternalSetGoal(command.goal); - CalculationContext context; if (command instanceof PathingCommandContext) { context = ((PathingCommandContext) command).desiredCalcContext; } else { context = new CalculationContext(baritone, true); } - return secretInternalPath(context); + if (goal == null) { + return false; + } + BlockPos pathStart = pathStart(); + if (goal.isInGoal(ctx.playerFeet()) || goal.isInGoal(pathStart)) { + return false; + } + synchronized (pathPlanLock) { + if (current != null) { + return false; + } + synchronized (pathCalcLock) { + if (inProgress != null) { + return false; + } + queuePathEvent(PathEvent.CALC_STARTED); + findPathInNewThread(pathStart, true, context); + return true; + } + } } @Override @@ -322,33 +341,6 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, inProgress = null; } - /** - * Start calculating a path if we aren't already - * - * @return true if this call started path calculation, false if it was already calculating or executing a path - */ - private boolean secretInternalPath(CalculationContext context) { - if (goal == null) { - return false; - } - if (goal.isInGoal(ctx.playerFeet())) { - return false; - } - synchronized (pathPlanLock) { - if (current != null) { - return false; - } - synchronized (pathCalcLock) { - if (inProgress != null) { - return false; - } - queuePathEvent(PathEvent.CALC_STARTED); - findPathInNewThread(pathStart(), true, context); - return true; - } - } - } - public void secretCursedFunctionDoNotCall(IPath path) { synchronized (pathPlanLock) { current = new PathExecutor(this, path); From f95dc40f4c7c970861afd60b2f9e3267178c4dab Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 10 Jan 2019 17:23:20 -0800 Subject: [PATCH 09/41] consolidate triple duplicated placement code --- .../baritone/behavior/PathingBehavior.java | 4 +- .../pathing/movement/MovementHelper.java | 47 ++++++++++ .../movement/movements/MovementAscend.java | 57 +++--------- .../movement/movements/MovementParkour.java | 38 +------- .../movement/movements/MovementTraverse.java | 86 +++++++------------ 5 files changed, 97 insertions(+), 135 deletions(-) diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index 767de6b86..283033fa5 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -375,7 +375,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } if (MovementHelper.canWalkOn(ctx, possibleSupport.down()) && MovementHelper.canWalkThrough(ctx, possibleSupport) && MovementHelper.canWalkThrough(ctx, possibleSupport.up())) { // this is plausible - logDebug("Faking path start assuming player is standing off the edge of a block"); + //logDebug("Faking path start assuming player is standing off the edge of a block"); return possibleSupport; } } @@ -384,7 +384,7 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, // !onGround // we're in the middle of a jump if (MovementHelper.canWalkOn(ctx, feet.down().down())) { - logDebug("Faking path start assuming player is midair and falling"); + //logDebug("Faking path start assuming player is midair and falling"); return feet.down(); } } diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 96c4a7690..790144f9d 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -19,6 +19,7 @@ package baritone.pathing.movement; import baritone.Baritone; import baritone.api.pathing.movement.ActionCosts; +import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.*; import baritone.api.utils.input.Input; import baritone.pathing.movement.MovementState.MovementTarget; @@ -35,6 +36,10 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.Vec3d; + +import static baritone.pathing.movement.Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP; /** * Static helpers for cost calculation @@ -487,4 +492,46 @@ public interface MovementHelper extends ActionCosts, Helper { return state.getBlock() instanceof BlockLiquid && state.getValue(BlockLiquid.LEVEL) != 0; } + + static PlaceResult attemptToPlaceABlock(MovementState state, IPlayerContext ctx, BlockPos placeAt, boolean preferDown) { + boolean found = false; + for (int i = 0; i < 5; i++) { + BlockPos against1 = placeAt.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); + if (MovementHelper.canPlaceAgainst(ctx, against1)) { + if (!MovementHelper.throwaway(ctx, true)) { // get ready to place a throwaway block + Helper.HELPER.logDebug("bb pls get me some blocks. dirt or cobble"); + state.setStatus(MovementStatus.UNREACHABLE); + return PlaceResult.NO_OPTION; + } + double faceX = (placeAt.getX() + against1.getX() + 1.0D) * 0.5D; + double faceY = (placeAt.getY() + against1.getY() + 1.0D) * 0.5D; + double faceZ = (placeAt.getZ() + against1.getZ() + 1.0D) * 0.5D; + Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); + RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance()); + if (res != null && res.typeOfHit == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(placeAt)) { + state.setTarget(new MovementState.MovementTarget(place, true)); + found = true; + + if (!preferDown) { + // if preferDown is true, we want the last option + // if preferDown is false, we want the first + break; + } + } + } + } + if (ctx.getSelectedBlock().isPresent()) { + BlockPos selectedBlock = ctx.getSelectedBlock().get(); + EnumFacing side = ctx.objectMouseOver().sideHit; + // only way for selectedBlock.equals(placeAt) to be true is if it's replacable + if (selectedBlock.equals(placeAt) || (MovementHelper.canPlaceAgainst(ctx, selectedBlock) && selectedBlock.offset(side).equals(placeAt))) { + return PlaceResult.READY_TO_PLACE; + } + } + return found ? PlaceResult.ATTEMPTING : PlaceResult.NO_OPTION; + } + + enum PlaceResult { + READY_TO_PLACE, ATTEMPTING, NO_OPTION; + } } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 5fafdeedc..8508e776d 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -21,7 +21,6 @@ import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -32,10 +31,6 @@ import net.minecraft.block.BlockFalling; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; - -import java.util.Objects; public class MovementAscend extends Movement { @@ -161,55 +156,29 @@ public class MovementAscend extends Movement { IBlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace); if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) { - for (int i = 0; i < 5; i++) { - BlockPos anAgainst = positionToPlace.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); - if (anAgainst.equals(src)) { - continue; - } - if (MovementHelper.canPlaceAgainst(ctx, anAgainst)) { - if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block - return state.setStatus(MovementStatus.UNREACHABLE); - } - double faceX = (dest.getX() + anAgainst.getX() + 1.0D) * 0.5D; - double faceY = (dest.getY() + anAgainst.getY()) * 0.5D; - double faceZ = (dest.getZ() + anAgainst.getZ() + 1.0D) * 0.5D; - state.setTarget(new MovementState.MovementTarget(RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()), true)); - EnumFacing side = ctx.objectMouseOver().sideHit; - - ctx.getSelectedBlock().ifPresent(selectedBlock -> { - if (Objects.equals(selectedBlock, anAgainst) && selectedBlock.offset(side).equals(positionToPlace)) { - ticksWithoutPlacement++; - state.setInput(Input.SNEAK, true); - if (ctx.player().isSneaking()) { - state.setInput(Input.CLICK_RIGHT, true); - } - if (ticksWithoutPlacement > 10) { - // After 10 ticks without placement, we might be standing in the way, move back - state.setInput(Input.MOVE_BACK, true); - } - } else { - state.setInput(Input.CLICK_LEFT, true); // break whatever replaceable block is in the way - } - //System.out.println("Trying to look at " + anAgainst + ", actually looking at" + selectedBlock); - }); - return state; + ticksWithoutPlacement++; + if (MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false) == PlaceResult.READY_TO_PLACE) { + state.setInput(Input.SNEAK, true); + if (ctx.player().isSneaking()) { + state.setInput(Input.CLICK_RIGHT, true); } } - return state.setStatus(MovementStatus.UNREACHABLE); + if (ticksWithoutPlacement > 10) { + // After 10 ticks without placement, we might be standing in the way, move back + state.setInput(Input.MOVE_BACK, true); + } + + return state; } MovementHelper.moveTowards(ctx, state, dest); if (MovementHelper.isBottomSlab(jumpingOnto) && !MovementHelper.isBottomSlab(BlockStateInterface.get(ctx, src.down()))) { return state; // don't jump while walking from a non double slab into a bottom slab } - - if (Baritone.settings().assumeStep.get()) { + if (Baritone.settings().assumeStep.get() || ctx.playerFeet().equals(src.up())) { + // no need to hit space if we're already jumping return state; } - if (ctx.playerFeet().equals(src.up())) { - return state; // no need to hit space if we're already jumping - } - if (headBonkClear()) { return state.setInput(Input.JUMP, true); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 7c4ca19ab..2d668bfb3 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -20,9 +20,6 @@ package baritone.pathing.movement.movements; import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.RayTraceUtils; -import baritone.api.utils.Rotation; -import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.Movement; @@ -35,9 +32,6 @@ import net.minecraft.block.BlockStairs; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.util.math.Vec3d; public class MovementParkour extends Movement { @@ -211,35 +205,9 @@ public class MovementParkour extends Movement { } } else if (!ctx.playerFeet().equals(src)) { if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().posY - ctx.playerFeet().getY() > 0.0001) { - - if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround) { - BlockPos positionToPlace = dest.down(); - for (int i = 4; i >= 0; i--) { // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory - BlockPos against1 = positionToPlace.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); - if (against1.up().equals(src.offset(direction, 3))) { // we can't turn around that fast - continue; - } - if (MovementHelper.canPlaceAgainst(ctx, against1)) { - if (!MovementHelper.throwaway(ctx, true)) {//get ready to place a throwaway block - return state.setStatus(MovementStatus.UNREACHABLE); - } - double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; - double faceY = (dest.getY() + against1.getY()) * 0.5D; - double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; - Rotation place = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); - RayTraceResult res = RayTraceUtils.rayTraceTowards(ctx.player(), place, ctx.playerController().getBlockReachDistance()); - if (res != null && res.typeOfHit == RayTraceResult.Type.BLOCK && res.getBlockPos().equals(against1) && res.getBlockPos().offset(res.sideHit).equals(dest.down())) { - state.setTarget(new MovementState.MovementTarget(place, true)); - break; - } - } - } - ctx.getSelectedBlock().ifPresent(selectedBlock -> { - EnumFacing side = ctx.objectMouseOver().sideHit; - if (MovementHelper.canPlaceAgainst(ctx, selectedBlock) && selectedBlock.offset(side).equals(dest.down())) { - state.setInput(Input.CLICK_RIGHT, true); - } - }); + if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround && MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), true) == PlaceResult.READY_TO_PLACE) { + // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory + state.setInput(Input.CLICK_RIGHT, true); } if (dist == 3) { // this is a 2 block gap, dest = src + direction * 3 double xDiff = (src.x + 0.5) - ctx.player().posX; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 1c5c4f2ea..6c78e7d3a 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -36,7 +36,6 @@ import net.minecraft.block.BlockFenceGate; import net.minecraft.block.BlockSlab; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; -import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; @@ -248,63 +247,40 @@ public class MovementTraverse extends Movement { return state; } else { wasTheBridgeBlockAlwaysThere = false; - for (int i = 0; i < 5; i++) { - BlockPos against1 = dest.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); - if (against1.equals(src)) { - continue; - } - against1 = against1.down(); - if (MovementHelper.canPlaceAgainst(ctx, against1)) { - if (!MovementHelper.throwaway(ctx, true)) { // get ready to place a throwaway block - logDebug("bb pls get me some blocks. dirt or cobble"); - return state.setStatus(MovementStatus.UNREACHABLE); - } - if (!Baritone.settings().assumeSafeWalk.get()) { - state.setInput(Input.SNEAK, true); - } - Block standingOn = BlockStateInterface.get(ctx, ctx.playerFeet().down()).getBlock(); - if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 - double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); - if (dist < 0.85) { // 0.5 + 0.3 + epsilon - MovementHelper.moveTowards(ctx, state, dest); - return state.setInput(Input.MOVE_FORWARD, false) - .setInput(Input.MOVE_BACK, true); - } - } - state.setInput(Input.MOVE_BACK, false); - double faceX = (dest.getX() + against1.getX() + 1.0D) * 0.5D; - double faceY = (dest.getY() + against1.getY()) * 0.5D; - double faceZ = (dest.getZ() + against1.getZ() + 1.0D) * 0.5D; - Rotation rot = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); - state.setTarget(new MovementState.MovementTarget(rot, true)); - - EnumFacing side = ctx.objectMouseOver().sideHit; - if ((Objects.equals(ctx.getSelectedBlock(), dest.down()) || (Objects.equals(ctx.getSelectedBlock().orElse(null), against1) && ctx.getSelectedBlock().get().offset(side).equals(positionToPlace))) && (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get())) { - return state.setInput(Input.CLICK_RIGHT, true); - } - if (ctx.playerRotations().isReallyCloseTo(rot)) { - double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); - if (dist > 0.83) { - // might need to go forward a bit - return state.setInput(Input.MOVE_FORWARD, true); - } - // don't left click for one tick - return state.setInput(Input.CLICK_LEFT, true); - } - return state; - //System.out.println("Trying to look at " + against1 + ", actually looking at" + RayTraceUtils.getSelectedBlock()); - } - } if (!Baritone.settings().assumeSafeWalk.get()) { state.setInput(Input.SNEAK, true); } + Block standingOn = BlockStateInterface.get(ctx, ctx.playerFeet().down()).getBlock(); + if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 + double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); + if (dist < 0.85) { // 0.5 + 0.3 + epsilon + MovementHelper.moveTowards(ctx, state, dest); + return state.setInput(Input.MOVE_FORWARD, false) + .setInput(Input.MOVE_BACK, true); + } + } + state.setInput(Input.MOVE_BACK, false); + switch (MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false)) { + case READY_TO_PLACE: + if (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) { + state.setInput(Input.CLICK_RIGHT, true); + } + return state; + case ATTEMPTING: + double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); + if (dist > 0.83) { + // might need to go forward a bit + return state.setInput(Input.MOVE_FORWARD, true); + } else if (ctx.playerRotations().isReallyCloseTo(state.getGoal().rotation)) { + // well i guess theres something in the way + return state.setInput(Input.CLICK_LEFT, true); + } + case NO_OPTION: + break; + } if (whereAmI.equals(dest)) { // If we are in the block that we are trying to get to, we are sneaking over air and we need to place a block beneath us against the one we just walked off of // Out.log(from + " " + to + " " + faceX + "," + faceY + "," + faceZ + " " + whereAmI); - if (!MovementHelper.throwaway(ctx, true)) {// get ready to place a throwaway block - logDebug("bb pls get me some blocks. dirt or cobble"); - return state.setStatus(MovementStatus.UNREACHABLE); - } double faceX = (dest.getX() + src.getX() + 1.0D) * 0.5D; double faceY = (dest.getY() + src.getY() - 1.0D) * 0.5D; double faceZ = (dest.getZ() + src.getZ() + 1.0D) * 0.5D; @@ -321,12 +297,14 @@ public class MovementTraverse extends Movement { } else { state.setTarget(new MovementState.MovementTarget(backToFace, true)); } - state.setInput(Input.SNEAK, true); if (Objects.equals(ctx.getSelectedBlock().orElse(null), goalLook)) { return state.setInput(Input.CLICK_RIGHT, true); // wait to right click until we are able to place } // Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt()); - return state.setInput(Input.CLICK_LEFT, true); + if (ctx.playerRotations().isReallyCloseTo(state.getGoal().rotation)) { + state.setInput(Input.CLICK_LEFT, true); + } + return state; } else { MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); return state; From 863ae447b9d36fb272d303c7e5babd2c361b8f49 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 10 Jan 2019 18:15:05 -0800 Subject: [PATCH 10/41] except we actually make it work --- .../movement/movements/MovementTraverse.java | 44 ++++++++++--------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index 6c78e7d3a..fa8922918 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -247,9 +247,6 @@ public class MovementTraverse extends Movement { return state; } else { wasTheBridgeBlockAlwaysThere = false; - if (!Baritone.settings().assumeSafeWalk.get()) { - state.setInput(Input.SNEAK, true); - } Block standingOn = BlockStateInterface.get(ctx, ctx.playerFeet().down()).getBlock(); if (standingOn.equals(Blocks.SOUL_SAND) || standingOn instanceof BlockSlab) { // see issue #118 double dist = Math.max(Math.abs(dest.getX() + 0.5 - ctx.player().posX), Math.abs(dest.getZ() + 0.5 - ctx.player().posZ)); @@ -259,24 +256,32 @@ public class MovementTraverse extends Movement { .setInput(Input.MOVE_BACK, true); } } - state.setInput(Input.MOVE_BACK, false); - switch (MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false)) { - case READY_TO_PLACE: + double dist1 = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); + PlaceResult p = MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false); + if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.get()) { + state.setInput(Input.SNEAK, true); + } + switch (p) { + case READY_TO_PLACE: { if (ctx.player().isSneaking() || Baritone.settings().assumeSafeWalk.get()) { state.setInput(Input.CLICK_RIGHT, true); } return state; - case ATTEMPTING: - double dist = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); - if (dist > 0.83) { + } + case ATTEMPTING: { + if (dist1 > 0.83) { // might need to go forward a bit - return state.setInput(Input.MOVE_FORWARD, true); - } else if (ctx.playerRotations().isReallyCloseTo(state.getGoal().rotation)) { + float yaw = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), VecUtils.getBlockPosCenter(dest), ctx.playerRotations()).getYaw(); + if (Math.abs(state.getTarget().rotation.getYaw() - yaw) < 0.1) { + // but only if our attempted place is straight ahead + return state.setInput(Input.MOVE_FORWARD, true); + } + } else if (ctx.playerRotations().isReallyCloseTo(state.getTarget().rotation)) { // well i guess theres something in the way return state.setInput(Input.CLICK_LEFT, true); } - case NO_OPTION: - break; + return state; + } } if (whereAmI.equals(dest)) { // If we are in the block that we are trying to get to, we are sneaking over air and we need to place a block beneath us against the one we just walked off of @@ -289,8 +294,8 @@ public class MovementTraverse extends Movement { Rotation backToFace = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(faceX, faceY, faceZ), ctx.playerRotations()); float pitch = backToFace.getPitch(); - double dist = Math.max(Math.abs(ctx.player().posX - faceX), Math.abs(ctx.player().posZ - faceZ)); - if (dist < 0.29) { + double dist2 = Math.max(Math.abs(ctx.player().posX - faceX), Math.abs(ctx.player().posZ - faceZ)); + if (dist2 < 0.29) { // see issue #208 float yaw = RotationUtils.calcRotationFromVec3d(VecUtils.getBlockPosCenter(dest), ctx.playerHead(), ctx.playerRotations()).getYaw(); state.setTarget(new MovementState.MovementTarget(new Rotation(yaw, pitch), true)); state.setInput(Input.MOVE_BACK, true); @@ -301,15 +306,14 @@ public class MovementTraverse extends Movement { return state.setInput(Input.CLICK_RIGHT, true); // wait to right click until we are able to place } // Out.log("Trying to look at " + goalLook + ", actually looking at" + Baritone.whatAreYouLookingAt()); - if (ctx.playerRotations().isReallyCloseTo(state.getGoal().rotation)) { + if (ctx.playerRotations().isReallyCloseTo(state.getTarget().rotation)) { state.setInput(Input.CLICK_LEFT, true); } return state; - } else { - MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); - return state; - // TODO MovementManager.moveTowardsBlock(to); // move towards not look at because if we are bridging for a couple blocks in a row, it is faster if we dont spin around and walk forwards then spin around and place backwards for every block } + MovementHelper.moveTowards(ctx, state, positionsToBreak[0]); + return state; + // TODO MovementManager.moveTowardsBlock(to); // move towards not look at because if we are bridging for a couple blocks in a row, it is faster if we dont spin around and walk forwards then spin around and place backwards for every block } } From a965859095b71f312a051146e745c428bf53477a Mon Sep 17 00:00:00 2001 From: babbaj Date: Fri, 11 Jan 2019 01:13:14 -0500 Subject: [PATCH 11/41] make code easy to understand --- .../java/baritone/utils/MapArtSchematic.java | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/main/java/baritone/utils/MapArtSchematic.java b/src/main/java/baritone/utils/MapArtSchematic.java index 9813b6373..5ff16f3f0 100644 --- a/src/main/java/baritone/utils/MapArtSchematic.java +++ b/src/main/java/baritone/utils/MapArtSchematic.java @@ -17,6 +17,8 @@ package baritone.utils; +import java.util.OptionalInt; +import java.util.function.Predicate; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; @@ -27,23 +29,33 @@ public class MapArtSchematic extends Schematic { public MapArtSchematic(NBTTagCompound schematic) { super(schematic); heightMap = new int[widthX][lengthZ]; + for (int x = 0; x < widthX; x++) { - https: for (int z = 0; z < lengthZ; z++) { IBlockState[] column = states[x][z]; - for (int y = heightY - 1; y >= 0; y--) { - if (column[y].getBlock() != Blocks.AIR) { - heightMap[x][z] = y; - continue https; - } + + OptionalInt lowestBlockY = getLowest(column, block -> block != Blocks.AIR); + if (lowestBlockY.isPresent()) { + heightMap[x][z] = lowestBlockY.getAsInt(); + } else { + System.out.println("Column " + x + "," + z + " has no blocks, but it's apparently map art? wtf"); + System.out.println("Letting it be whatever"); + heightMap[x][z] = 256; } - System.out.println("Column " + x + "," + z + " has no blocks, but it's apparently map art? wtf"); - System.out.println("Letting it be whatever"); - heightMap[x][z] = 256; + } } } + private static OptionalInt getLowest(T[] arr, Predicate predicate) { + for (int y = arr.length - 1; y >= 0; y--) { + if (predicate.test(arr[y])) { + return OptionalInt.of(y); + } + } + return OptionalInt.empty(); + } + @Override public boolean inSchematic(int x, int y, int z) { // in map art, we only care about coordinates in or above the art From 14bc65468a9e5995448725a4183a376018946300 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Fri, 11 Jan 2019 10:02:21 -0800 Subject: [PATCH 12/41] tweaks --- src/main/java/baritone/utils/MapArtSchematic.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/utils/MapArtSchematic.java b/src/main/java/baritone/utils/MapArtSchematic.java index 5ff16f3f0..711a4ed81 100644 --- a/src/main/java/baritone/utils/MapArtSchematic.java +++ b/src/main/java/baritone/utils/MapArtSchematic.java @@ -17,12 +17,13 @@ package baritone.utils; -import java.util.OptionalInt; -import java.util.function.Predicate; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; +import java.util.OptionalInt; +import java.util.function.Predicate; + public class MapArtSchematic extends Schematic { private final int[][] heightMap; @@ -34,7 +35,7 @@ public class MapArtSchematic extends Schematic { for (int z = 0; z < lengthZ; z++) { IBlockState[] column = states[x][z]; - OptionalInt lowestBlockY = getLowest(column, block -> block != Blocks.AIR); + OptionalInt lowestBlockY = lastIndexMatching(column, block -> block != Blocks.AIR); if (lowestBlockY.isPresent()) { heightMap[x][z] = lowestBlockY.getAsInt(); } else { @@ -47,7 +48,7 @@ public class MapArtSchematic extends Schematic { } } - private static OptionalInt getLowest(T[] arr, Predicate predicate) { + private static OptionalInt lastIndexMatching(T[] arr, Predicate predicate) { for (int y = arr.length - 1; y >= 0; y--) { if (predicate.test(arr[y])) { return OptionalInt.of(y); From a6ce4694fcb2020529a339c452a27cdc37d88464 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 12 Jan 2019 19:51:21 -0800 Subject: [PATCH 13/41] hotbar selection uwu --- src/main/java/baritone/Baritone.java | 7 ++- .../baritone/behavior/InventoryBehavior.java | 60 +++++++++++++++++++ .../pathing/movement/CalculationContext.java | 2 +- .../pathing/movement/MovementHelper.java | 45 ++------------ .../movement/movements/MovementAscend.java | 2 +- .../movement/movements/MovementParkour.java | 2 +- .../movement/movements/MovementPillar.java | 3 +- .../movement/movements/MovementTraverse.java | 2 +- .../java/baritone/process/BuilderProcess.java | 28 +++++++-- 9 files changed, 98 insertions(+), 53 deletions(-) diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index 358a4f2bf..8a3bf8c3a 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -74,6 +74,7 @@ public class Baritone implements IBaritone { private PathingBehavior pathingBehavior; private LookBehavior lookBehavior; private MemoryBehavior memoryBehavior; + private InventoryBehavior inventoryBehavior; private InputOverrideHandler inputOverrideHandler; private FollowProcess followProcess; @@ -105,7 +106,7 @@ public class Baritone implements IBaritone { pathingBehavior = new PathingBehavior(this); lookBehavior = new LookBehavior(this); memoryBehavior = new MemoryBehavior(this); - new InventoryBehavior(this); + inventoryBehavior = new InventoryBehavior(this); inputOverrideHandler = new InputOverrideHandler(this); new ExampleBaritoneControl(this); } @@ -174,6 +175,10 @@ public class Baritone implements IBaritone { return this.builderProcess; } + public InventoryBehavior getInventoryBehavior() { + return this.inventoryBehavior; + } + @Override public LookBehavior getLookBehavior() { return this.lookBehavior; diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index a49cbb7de..29e45a962 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -21,8 +21,10 @@ import baritone.Baritone; import baritone.api.event.events.TickEvent; import baritone.utils.ToolSet; import net.minecraft.block.Block; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.init.Blocks; import net.minecraft.inventory.ClickType; +import net.minecraft.item.Item; import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; @@ -87,4 +89,62 @@ public class InventoryBehavior extends Behavior { } return bestInd; } + + public boolean hasGenericThrowaway() { + for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { + if (throwaway(false, item)) { + return true; + } + } + return false; + } + + public boolean selectThrowawayForLocation(int x, int y, int z) { + Item maybe = baritone.getBuilderProcess().placeAt(x, y, z); + if (maybe != null && throwaway(true, maybe)) { + return true; // gotem + } + for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { + if (throwaway(true, item)) { + return true; + } + } + return false; + } + + private boolean throwaway(boolean select, Item desired) { + EntityPlayerSP p = ctx.player(); + NonNullList inv = p.inventory.mainInventory; + for (byte i = 0; i < 9; i++) { + ItemStack item = inv.get(i); + // this usage of settings() is okay because it's only called once during pathing + // (while creating the CalculationContext at the very beginning) + // and then it's called during execution + // since this function is never called during cost calculation, we don't need to migrate + // acceptableThrowawayItems to the CalculationContext + if (desired.equals(item.getItem())) { + if (select) { + p.inventory.currentItem = i; + } + return true; + } + } + if (desired.equals(p.inventory.offHandInventory.get(0).getItem())) { + // main hand takes precedence over off hand + // that means that if we have block A selected in main hand and block B in off hand, right clicking places block B + // we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem + // so we need to select in the main hand something that doesn't right click + // so not a shovel, not a hoe, not a block, etc + for (byte i = 0; i < 9; i++) { + ItemStack item = inv.get(i); + if (item.isEmpty() || item.getItem() instanceof ItemPickaxe) { + if (select) { + p.inventory.currentItem = i; + } + return true; + } + } + } + return false; + } } diff --git a/src/main/java/baritone/pathing/movement/CalculationContext.java b/src/main/java/baritone/pathing/movement/CalculationContext.java index 6af1dae95..ebca5f194 100644 --- a/src/main/java/baritone/pathing/movement/CalculationContext.java +++ b/src/main/java/baritone/pathing/movement/CalculationContext.java @@ -81,7 +81,7 @@ public class CalculationContext { this.worldData = (WorldData) baritone.getWorldProvider().getCurrentWorld(); this.bsi = new BlockStateInterface(world, worldData, forUseOnAnotherThread); this.toolSet = new ToolSet(player); - this.hasThrowaway = Baritone.settings().allowPlace.get() && MovementHelper.throwaway(baritone.getPlayerContext(), false); + this.hasThrowaway = Baritone.settings().allowPlace.get() && ((Baritone) baritone).getInventoryBehavior().hasGenericThrowaway(); this.hasWaterBucket = Baritone.settings().allowWaterBucketFall.get() && InventoryPlayer.isHotbar(player.inventory.getSlotFor(STACK_BUCKET_WATER)) && !world.provider.isNether(); this.canSprint = Baritone.settings().allowSprint.get() && player.getFoodStats().getFoodLevel() > 6; this.placeBlockCost = Baritone.settings().blockPlacementPenalty.get(); diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 790144f9d..9bfebcc2a 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -18,6 +18,7 @@ package baritone.pathing.movement; import baritone.Baritone; +import baritone.api.IBaritone; import baritone.api.pathing.movement.ActionCosts; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.*; @@ -31,10 +32,7 @@ import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.IBlockState; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.init.Blocks; -import net.minecraft.item.ItemPickaxe; -import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; -import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; @@ -403,42 +401,6 @@ public interface MovementHelper extends ActionCosts, Helper { ctx.player().inventory.currentItem = ts.getBestSlot(b.getBlock()); } - static boolean throwaway(IPlayerContext ctx, boolean select) { - EntityPlayerSP p = ctx.player(); - NonNullList inv = p.inventory.mainInventory; - for (byte i = 0; i < 9; i++) { - ItemStack item = inv.get(i); - // this usage of settings() is okay because it's only called once during pathing - // (while creating the CalculationContext at the very beginning) - // and then it's called during execution - // since this function is never called during cost calculation, we don't need to migrate - // acceptableThrowawayItems to the CalculationContext - if (Baritone.settings().acceptableThrowawayItems.get().contains(item.getItem())) { - if (select) { - p.inventory.currentItem = i; - } - return true; - } - } - if (Baritone.settings().acceptableThrowawayItems.get().contains(p.inventory.offHandInventory.get(0).getItem())) { - // main hand takes precedence over off hand - // that means that if we have block A selected in main hand and block B in off hand, right clicking places block B - // we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem - // so we need to select in the main hand something that doesn't right click - // so not a shovel, not a hoe, not a block, etc - for (byte i = 0; i < 9; i++) { - ItemStack item = inv.get(i); - if (item.isEmpty() || item.getItem() instanceof ItemPickaxe) { - if (select) { - p.inventory.currentItem = i; - } - return true; - } - } - } - return false; - } - static void moveTowards(IPlayerContext ctx, MovementState state, BlockPos pos) { EntityPlayerSP player = ctx.player(); state.setTarget(new MovementTarget( @@ -493,12 +455,13 @@ public interface MovementHelper extends ActionCosts, Helper { && state.getValue(BlockLiquid.LEVEL) != 0; } - static PlaceResult attemptToPlaceABlock(MovementState state, IPlayerContext ctx, BlockPos placeAt, boolean preferDown) { + static PlaceResult attemptToPlaceABlock(MovementState state, IBaritone baritone, BlockPos placeAt, boolean preferDown) { + IPlayerContext ctx = baritone.getPlayerContext(); boolean found = false; for (int i = 0; i < 5; i++) { BlockPos against1 = placeAt.offset(HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP[i]); if (MovementHelper.canPlaceAgainst(ctx, against1)) { - if (!MovementHelper.throwaway(ctx, true)) { // get ready to place a throwaway block + if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(placeAt.getX(), placeAt.getY(), placeAt.getZ())) { // get ready to place a throwaway block Helper.HELPER.logDebug("bb pls get me some blocks. dirt or cobble"); state.setStatus(MovementStatus.UNREACHABLE); return PlaceResult.NO_OPTION; diff --git a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java index 8508e776d..d937cc8f7 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementAscend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementAscend.java @@ -157,7 +157,7 @@ public class MovementAscend extends Movement { IBlockState jumpingOnto = BlockStateInterface.get(ctx, positionToPlace); if (!MovementHelper.canWalkOn(ctx, positionToPlace, jumpingOnto)) { ticksWithoutPlacement++; - if (MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false) == PlaceResult.READY_TO_PLACE) { + if (MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false) == PlaceResult.READY_TO_PLACE) { state.setInput(Input.SNEAK, true); if (ctx.player().isSneaking()) { state.setInput(Input.CLICK_RIGHT, true); diff --git a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java index 2d668bfb3..98898690b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementParkour.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementParkour.java @@ -205,7 +205,7 @@ public class MovementParkour extends Movement { } } else if (!ctx.playerFeet().equals(src)) { if (ctx.playerFeet().equals(src.offset(direction)) || ctx.player().posY - ctx.playerFeet().getY() > 0.0001) { - if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround && MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), true) == PlaceResult.READY_TO_PLACE) { + if (!MovementHelper.canWalkOn(ctx, dest.down()) && !ctx.player().onGround && MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), true) == PlaceResult.READY_TO_PLACE) { // go in the opposite order to check DOWN before all horizontals -- down is preferable because you don't have to look to the side while in midair, which could mess up the trajectory state.setInput(Input.CLICK_RIGHT, true); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index 92ac6cbee..a9d1e20e7 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -17,6 +17,7 @@ package baritone.pathing.movement.movements; +import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.pathing.movement.MovementStatus; import baritone.api.utils.BetterBlockPos; @@ -202,7 +203,7 @@ public class MovementPillar extends Movement { return state; } else { // Get ready to place a throwaway block - if (!MovementHelper.throwaway(ctx, true)) { + if (!((Baritone) baritone).getInventoryBehavior().selectThrowawayForLocation(src.x, src.y, src.z)) { return state.setStatus(MovementStatus.UNREACHABLE); } diff --git a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java index fa8922918..40597e97b 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementTraverse.java @@ -257,7 +257,7 @@ public class MovementTraverse extends Movement { } } double dist1 = Math.max(Math.abs(ctx.player().posX - (dest.getX() + 0.5D)), Math.abs(ctx.player().posZ - (dest.getZ() + 0.5D))); - PlaceResult p = MovementHelper.attemptToPlaceABlock(state, ctx, dest.down(), false); + PlaceResult p = MovementHelper.attemptToPlaceABlock(state, baritone, dest.down(), false); if ((p == PlaceResult.READY_TO_PLACE || dist1 < 0.6) && !Baritone.settings().assumeSafeWalk.get()) { state.setInput(Input.SNEAK, true); } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index a679c0287..875fa81bc 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -37,6 +37,7 @@ import baritone.utils.Schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; +import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; @@ -93,6 +94,21 @@ public class BuilderProcess extends BaritoneProcessHelper { return schematic != null; } + public Item placeAt(int x, int y, int z) { + if (!isActive()) { + return null; + } + if (!schematic.inSchematic(x - origin.getX(), y - origin.getY(), z - origin.getZ())) { + return null; + } + IBlockState state = schematic.desiredState(x - origin.getX(), y - origin.getY(), z - origin.getZ()); + if (state.getBlock() == Blocks.AIR) { + return null; + } + return new ItemBlock(state.getBlock()); + } + + public Optional> toBreakNearPlayer(BuilderCalculationContext bcc) { BetterBlockPos center = ctx.playerFeet(); for (int dx = -5; dx <= 5; dx++) { @@ -129,7 +145,7 @@ public class BuilderProcess extends BaritoneProcessHelper { // need to iterate over incorrectPositions and see which ones we can "correct" from our current standing position - BuilderCalculationContext bcc = new BuilderCalculationContext(schematic, origin); + BuilderCalculationContext bcc = new BuilderCalculationContext(); if (!recalc(bcc)) { logDirect("Done building"); onLostControl(); @@ -321,13 +337,13 @@ public class BuilderProcess extends BaritoneProcessHelper { private final int originY; private final int originZ; - public BuilderCalculationContext(ISchematic schematic, Vec3i schematicOrigin) { + public BuilderCalculationContext() { super(BuilderProcess.this.baritone, true); // wew lad this.placable = placable(); - this.schematic = schematic; - this.originX = schematicOrigin.getX(); - this.originY = schematicOrigin.getY(); - this.originZ = schematicOrigin.getZ(); + this.schematic = BuilderProcess.this.schematic; + this.originX = origin.getX(); + this.originY = origin.getY(); + this.originZ = origin.getZ(); this.jumpPenalty += 10; this.backtrackCostFavoringCoefficient = 1; From e2cdd6a7f90b710109c662793e7fc9c72c2c7133 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 14 Jan 2019 19:49:26 -0800 Subject: [PATCH 14/41] builder with multiple materials --- .../baritone/behavior/InventoryBehavior.java | 22 +++++++++---------- .../java/baritone/process/BuilderProcess.java | 5 ++--- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 29e45a962..231f577ee 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -21,15 +21,15 @@ import baritone.Baritone; import baritone.api.event.events.TickEvent; import baritone.utils.ToolSet; import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.init.Blocks; import net.minecraft.inventory.ClickType; -import net.minecraft.item.Item; -import net.minecraft.item.ItemPickaxe; -import net.minecraft.item.ItemStack; -import net.minecraft.item.ItemTool; +import net.minecraft.item.*; import net.minecraft.util.NonNullList; +import java.util.function.Predicate; + public class InventoryBehavior extends Behavior { public InventoryBehavior(Baritone baritone) { super(baritone); @@ -92,7 +92,7 @@ public class InventoryBehavior extends Behavior { public boolean hasGenericThrowaway() { for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { - if (throwaway(false, item)) { + if (throwaway(false, item::equals)) { return true; } } @@ -100,19 +100,19 @@ public class InventoryBehavior extends Behavior { } public boolean selectThrowawayForLocation(int x, int y, int z) { - Item maybe = baritone.getBuilderProcess().placeAt(x, y, z); - if (maybe != null && throwaway(true, maybe)) { + IBlockState maybe = baritone.getBuilderProcess().placeAt(x, y, z); + if (maybe != null && throwaway(true, item -> item instanceof ItemBlock && ((ItemBlock) item).getBlock().equals(maybe.getBlock()))) { return true; // gotem } for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { - if (throwaway(true, item)) { + if (throwaway(true, item::equals)) { return true; } } return false; } - private boolean throwaway(boolean select, Item desired) { + private boolean throwaway(boolean select, Predicate desired) { EntityPlayerSP p = ctx.player(); NonNullList inv = p.inventory.mainInventory; for (byte i = 0; i < 9; i++) { @@ -122,14 +122,14 @@ public class InventoryBehavior extends Behavior { // and then it's called during execution // since this function is never called during cost calculation, we don't need to migrate // acceptableThrowawayItems to the CalculationContext - if (desired.equals(item.getItem())) { + if (desired.test(item.getItem())) { if (select) { p.inventory.currentItem = i; } return true; } } - if (desired.equals(p.inventory.offHandInventory.get(0).getItem())) { + if (desired.test(p.inventory.offHandInventory.get(0).getItem())) { // main hand takes precedence over off hand // that means that if we have block A selected in main hand and block B in off hand, right clicking places block B // we've already checked above ^ and the main hand can't possible have an acceptablethrowawayitem diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 875fa81bc..0b34fb075 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -37,7 +37,6 @@ import baritone.utils.Schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; -import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; @@ -94,7 +93,7 @@ public class BuilderProcess extends BaritoneProcessHelper { return schematic != null; } - public Item placeAt(int x, int y, int z) { + public IBlockState placeAt(int x, int y, int z) { if (!isActive()) { return null; } @@ -105,7 +104,7 @@ public class BuilderProcess extends BaritoneProcessHelper { if (state.getBlock() == Blocks.AIR) { return null; } - return new ItemBlock(state.getBlock()); + return state; } From d5b393d6bdd9ca265e61f3e8833854b145467040 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 14 Jan 2019 21:41:40 -0800 Subject: [PATCH 15/41] area clear --- .../java/baritone/process/BuilderProcess.java | 10 ++-- .../java/baritone/utils/AirSchematic.java | 53 +++++++++++++++++++ .../utils/ExampleBaritoneControl.java | 30 +++++++++++ src/main/java/baritone/utils/ISchematic.java | 4 +- src/main/java/baritone/utils/Schematic.java | 5 -- 5 files changed, 93 insertions(+), 9 deletions(-) create mode 100644 src/main/java/baritone/utils/AirSchematic.java diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 0b34fb075..1ac201e16 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -78,12 +78,16 @@ public class BuilderProcess extends BaritoneProcessHelper { if (tag == null) { return false; } - name = schematicFile; - schematic = parse(tag); - origin = ctx.playerFeet(); + build(schematicFile, parse(tag), ctx.playerFeet()); return true; } + public void build(String name, ISchematic schematic, Vec3i origin) { + this.name = name; + this.schematic = schematic; + this.origin = origin; + } + private static ISchematic parse(NBTTagCompound schematic) { return new Schematic(schematic); } diff --git a/src/main/java/baritone/utils/AirSchematic.java b/src/main/java/baritone/utils/AirSchematic.java new file mode 100644 index 000000000..bced26e76 --- /dev/null +++ b/src/main/java/baritone/utils/AirSchematic.java @@ -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 . + */ + +package baritone.utils; + +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; + +public class AirSchematic implements ISchematic { + public final int widthX; + public final int heightY; + public final int lengthZ; + + public AirSchematic(int widthX, int heightY, int lengthZ) { + this.widthX = widthX; + this.heightY = heightY; + this.lengthZ = lengthZ; + } + + @Override + public IBlockState desiredState(int x, int y, int z) { + return Blocks.AIR.getDefaultState(); + } + + @Override + public int widthX() { + return widthX; + } + + @Override + public int heightY() { + return heightY; + } + + @Override + public int lengthZ() { + return lengthZ; + } +} diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 550095756..6e65c087a 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -284,6 +284,36 @@ public class ExampleBaritoneControl extends Behavior implements Helper { }); return true; } + if (msg.startsWith("cleararea")) { + String suffix = msg.substring("cleararea".length()); + BlockPos corner1; + BlockPos corner2; + if (suffix.isEmpty()) { + // clear the area from the current goal to here + Goal goal = baritone.getPathingBehavior().getGoal(); + if (goal == null || !(goal instanceof GoalBlock)) { + logDirect("Need to specify goal of opposite corner"); + return true; + } + corner1 = ((GoalBlock) goal).getGoalPos(); + corner2 = ctx.playerFeet(); + } else { + try { + String[] spl = suffix.split(" "); + corner1 = ctx.playerFeet(); + corner2 = new BlockPos(Integer.parseInt(spl[0]), Integer.parseInt(spl[1]), Integer.parseInt(spl[2])); + } catch (NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException ex) { + logDirect("unable to parse"); + return true; + } + } + 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; + baritone.getBuilderProcess().build("clear area", new AirSchematic(widthX, heightY, lengthZ), origin); + return true; + } if (msg.equals("reset")) { Baritone.settings().reset(); logDirect("Baritone settings reset"); diff --git a/src/main/java/baritone/utils/ISchematic.java b/src/main/java/baritone/utils/ISchematic.java index b68f1a1c5..77ba8634c 100644 --- a/src/main/java/baritone/utils/ISchematic.java +++ b/src/main/java/baritone/utils/ISchematic.java @@ -33,7 +33,9 @@ public interface ISchematic { * @param z * @return */ - boolean inSchematic(int x, int y, int z); + default boolean inSchematic(int x, int y, int z) { + return x >= 0 && x < widthX() && y >= 0 && y < heightY() && z >= 0 && z < lengthZ(); + } IBlockState desiredState(int x, int y, int z); diff --git a/src/main/java/baritone/utils/Schematic.java b/src/main/java/baritone/utils/Schematic.java index dbc80a733..3fef4b1e1 100644 --- a/src/main/java/baritone/utils/Schematic.java +++ b/src/main/java/baritone/utils/Schematic.java @@ -66,11 +66,6 @@ public class Schematic implements ISchematic { } } - @Override - public boolean inSchematic(int x, int y, int z) { - return x >= 0 && x < widthX && y >= 0 && y < heightY && z >= 0 && z < lengthZ; - } - @Override public IBlockState desiredState(int x, int y, int z) { return states[x][z][y]; From ceda14096c0a27ae69a9104197effdbde8d69a30 Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 15 Jan 2019 22:07:06 -0600 Subject: [PATCH 16/41] Builder Process API exposure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Professional style 💪 --- src/api/java/baritone/api/IBaritone.java | 11 +++-- .../baritone/api/process/IBuilderProcess.java | 49 +++++++++++++++++++ .../java/baritone/api}/utils/ISchematic.java | 34 +++++++++++-- src/main/java/baritone/Baritone.java | 1 + .../java/baritone/process/BuilderProcess.java | 27 ++++++---- .../java/baritone/utils/AirSchematic.java | 1 + src/main/java/baritone/utils/Schematic.java | 1 + 7 files changed, 105 insertions(+), 19 deletions(-) create mode 100644 src/api/java/baritone/api/process/IBuilderProcess.java rename src/{main/java/baritone => api/java/baritone/api}/utils/ISchematic.java (56%) diff --git a/src/api/java/baritone/api/IBaritone.java b/src/api/java/baritone/api/IBaritone.java index 6bdb7d108..a2f414e7d 100644 --- a/src/api/java/baritone/api/IBaritone.java +++ b/src/api/java/baritone/api/IBaritone.java @@ -22,10 +22,7 @@ import baritone.api.behavior.IPathingBehavior; import baritone.api.cache.IWorldProvider; import baritone.api.event.listener.IEventBus; import baritone.api.pathing.calc.IPathingControlManager; -import baritone.api.process.ICustomGoalProcess; -import baritone.api.process.IFollowProcess; -import baritone.api.process.IGetToBlockProcess; -import baritone.api.process.IMineProcess; +import baritone.api.process.*; import baritone.api.utils.IInputOverrideHandler; import baritone.api.utils.IPlayerContext; @@ -53,6 +50,12 @@ public interface IBaritone { */ IMineProcess getMineProcess(); + /** + * @return The {@link IBuilderProcess} instance + * @see IBuilderProcess + */ + IBuilderProcess getBuilderProcess(); + /** * @return The {@link IPathingBehavior} instance * @see IPathingBehavior diff --git a/src/api/java/baritone/api/process/IBuilderProcess.java b/src/api/java/baritone/api/process/IBuilderProcess.java new file mode 100644 index 000000000..694c8752b --- /dev/null +++ b/src/api/java/baritone/api/process/IBuilderProcess.java @@ -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 . + */ + +package baritone.api.process; + +import baritone.api.utils.ISchematic; +import net.minecraft.util.math.Vec3i; + +import java.io.File; + +/** + * @author Brady + * @since 1/15/2019 + */ +public interface IBuilderProcess extends IBaritoneProcess { + + /** + * Requests a build for the specified schematic, labeled as specified, with the specified origin. + * + * @param name A user-friendly name for the schematic + * @param schematic The object representation of the schematic + * @param origin The origin position of the schematic being built + */ + void build(String name, ISchematic schematic, Vec3i origin); + + /** + * Requests a build for the specified schematic, labeled as specified, with the specified origin. + * + * @param name A user-friendly name for the schematic + * @param schematic The file path of the schematic + * @param origin The origin position of the schematic being built + * @return Whether or not the schematic was able to load from file + */ + boolean build(String name, File schematic, Vec3i origin); +} diff --git a/src/main/java/baritone/utils/ISchematic.java b/src/api/java/baritone/api/utils/ISchematic.java similarity index 56% rename from src/main/java/baritone/utils/ISchematic.java rename to src/api/java/baritone/api/utils/ISchematic.java index 77ba8634c..1f2cd8742 100644 --- a/src/main/java/baritone/utils/ISchematic.java +++ b/src/api/java/baritone/api/utils/ISchematic.java @@ -15,11 +15,18 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.api.utils; import net.minecraft.block.state.IBlockState; +/** + * Basic representation of a schematic. Provides the dimensions and + * the desired statefor a given position relative to the origin. + * + * @author leijurv + */ public interface ISchematic { + /** * Does the block at this coordinate matter to the schematic? *

@@ -28,20 +35,37 @@ 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 - * @param y - * @param z - * @return + * @param x The x position of the block, relative to the origin + * @param y The y position of the block, relative to the origin + * @param z The z position of the block, relative to the origin + * @return Whether or not the specified position is within the bounds of this schematic */ default boolean inSchematic(int x, int y, int z) { return x >= 0 && x < widthX() && y >= 0 && y < heightY() && z >= 0 && z < lengthZ(); } + /** + * Returns the desired block state at a given (X, Y, Z) position relative to the origin (0, 0, 0). + * + * @param x The x position of the block, relative to the origin + * @param y The y position of the block, relative to the origin + * @param z The z position of the block, relative to the origin + * @return The desired block state at the specified position + */ IBlockState desiredState(int x, int y, int z); + /** + * @return The width (X axis length) of this schematic + */ int widthX(); + /** + * @return The height (Y axis length) of this schematic + */ int heightY(); + /** + * @return The length (Z axis length) of this schematic + */ int lengthZ(); } \ No newline at end of file diff --git a/src/main/java/baritone/Baritone.java b/src/main/java/baritone/Baritone.java index ec745a277..18f61f7a3 100755 --- a/src/main/java/baritone/Baritone.java +++ b/src/main/java/baritone/Baritone.java @@ -172,6 +172,7 @@ public class Baritone implements IBaritone { return this.followProcess; } + @Override public BuilderProcess getBuilderProcess() { return this.builderProcess; } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 1ac201e16..cafbeee01 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -22,16 +22,17 @@ import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalComposite; import baritone.api.pathing.goals.GoalGetToBlock; +import baritone.api.process.IBuilderProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; import baritone.api.utils.BetterBlockPos; +import baritone.api.utils.ISchematic; import baritone.api.utils.Rotation; import baritone.api.utils.RotationUtils; import baritone.api.utils.input.Input; import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; -import baritone.utils.ISchematic; import baritone.utils.PathingCommandContext; import baritone.utils.Schematic; import net.minecraft.block.state.IBlockState; @@ -54,7 +55,8 @@ import java.util.stream.Collectors; import static baritone.api.pathing.movement.ActionCosts.COST_INF; -public class BuilderProcess extends BaritoneProcessHelper { +public class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { + public BuilderProcess(Baritone baritone) { super(baritone); } @@ -67,9 +69,20 @@ public class BuilderProcess extends BaritoneProcessHelper { public boolean build(String schematicFile) { File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); System.out.println(file + " " + file.exists()); + return build(schematicFile, file, ctx.playerFeet()); + } + @Override + public void build(String name, ISchematic schematic, Vec3i origin) { + this.name = name; + this.schematic = schematic; + this.origin = origin; + } + + @Override + public boolean build(String name, File schematic, Vec3i origin) { NBTTagCompound tag; - try (FileInputStream fileIn = new FileInputStream(file)) { + try (FileInputStream fileIn = new FileInputStream(schematic)) { tag = CompressedStreamTools.readCompressed(fileIn); } catch (IOException e) { e.printStackTrace(); @@ -78,16 +91,10 @@ public class BuilderProcess extends BaritoneProcessHelper { if (tag == null) { return false; } - build(schematicFile, parse(tag), ctx.playerFeet()); + build(name, parse(tag), origin); return true; } - public void build(String name, ISchematic schematic, Vec3i origin) { - this.name = name; - this.schematic = schematic; - this.origin = origin; - } - private static ISchematic parse(NBTTagCompound schematic) { return new Schematic(schematic); } diff --git a/src/main/java/baritone/utils/AirSchematic.java b/src/main/java/baritone/utils/AirSchematic.java index bced26e76..3d70f1b14 100644 --- a/src/main/java/baritone/utils/AirSchematic.java +++ b/src/main/java/baritone/utils/AirSchematic.java @@ -17,6 +17,7 @@ package baritone.utils; +import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; diff --git a/src/main/java/baritone/utils/Schematic.java b/src/main/java/baritone/utils/Schematic.java index 3fef4b1e1..0cae99ca2 100644 --- a/src/main/java/baritone/utils/Schematic.java +++ b/src/main/java/baritone/utils/Schematic.java @@ -17,6 +17,7 @@ package baritone.utils; +import baritone.api.utils.ISchematic; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; From 0c0bbeff27d0745abe17e9dd328858b193944638 Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 16 Jan 2019 12:39:15 -0600 Subject: [PATCH 17/41] Minor AirSchematic access modifier change --- src/main/java/baritone/utils/AirSchematic.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/baritone/utils/AirSchematic.java b/src/main/java/baritone/utils/AirSchematic.java index 3d70f1b14..6580b4f81 100644 --- a/src/main/java/baritone/utils/AirSchematic.java +++ b/src/main/java/baritone/utils/AirSchematic.java @@ -22,9 +22,10 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; public class AirSchematic implements ISchematic { - public final int widthX; - public final int heightY; - public final int lengthZ; + + private final int widthX; + private final int heightY; + private final int lengthZ; public AirSchematic(int widthX, int heightY, int lengthZ) { this.widthX = widthX; From aa3833915b3dd6a75649536ffde8e56401178b8d Mon Sep 17 00:00:00 2001 From: Brady Date: Wed, 16 Jan 2019 13:45:32 -0600 Subject: [PATCH 18/41] Repackage schematic implementations --- src/main/java/baritone/process/BuilderProcess.java | 2 +- src/main/java/baritone/utils/ExampleBaritoneControl.java | 1 + src/main/java/baritone/utils/{ => schematic}/AirSchematic.java | 2 +- .../java/baritone/utils/{ => schematic}/MapArtSchematic.java | 3 ++- src/main/java/baritone/utils/{ => schematic}/Schematic.java | 2 +- 5 files changed, 6 insertions(+), 4 deletions(-) rename src/main/java/baritone/utils/{ => schematic}/AirSchematic.java (97%) rename src/main/java/baritone/utils/{ => schematic}/MapArtSchematic.java (98%) rename src/main/java/baritone/utils/{ => schematic}/Schematic.java (98%) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index cafbeee01..2d0a157a1 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -34,7 +34,7 @@ import baritone.pathing.movement.CalculationContext; import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; import baritone.utils.PathingCommandContext; -import baritone.utils.Schematic; +import baritone.utils.schematic.Schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 6e65c087a..d7c3fd717 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -34,6 +34,7 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.process.CustomGoalProcess; import baritone.utils.pathing.SegmentedCalculator; +import baritone.utils.schematic.AirSchematic; import net.minecraft.block.Block; import net.minecraft.client.multiplayer.ChunkProviderClient; import net.minecraft.entity.Entity; diff --git a/src/main/java/baritone/utils/AirSchematic.java b/src/main/java/baritone/utils/schematic/AirSchematic.java similarity index 97% rename from src/main/java/baritone/utils/AirSchematic.java rename to src/main/java/baritone/utils/schematic/AirSchematic.java index 6580b4f81..fd253105e 100644 --- a/src/main/java/baritone/utils/AirSchematic.java +++ b/src/main/java/baritone/utils/schematic/AirSchematic.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.utils.schematic; import baritone.api.utils.ISchematic; import net.minecraft.block.state.IBlockState; diff --git a/src/main/java/baritone/utils/MapArtSchematic.java b/src/main/java/baritone/utils/schematic/MapArtSchematic.java similarity index 98% rename from src/main/java/baritone/utils/MapArtSchematic.java rename to src/main/java/baritone/utils/schematic/MapArtSchematic.java index 711a4ed81..69a46762f 100644 --- a/src/main/java/baritone/utils/MapArtSchematic.java +++ b/src/main/java/baritone/utils/schematic/MapArtSchematic.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.utils.schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -25,6 +25,7 @@ import java.util.OptionalInt; import java.util.function.Predicate; public class MapArtSchematic extends Schematic { + private final int[][] heightMap; public MapArtSchematic(NBTTagCompound schematic) { diff --git a/src/main/java/baritone/utils/Schematic.java b/src/main/java/baritone/utils/schematic/Schematic.java similarity index 98% rename from src/main/java/baritone/utils/Schematic.java rename to src/main/java/baritone/utils/schematic/Schematic.java index 0cae99ca2..55dfb6192 100644 --- a/src/main/java/baritone/utils/Schematic.java +++ b/src/main/java/baritone/utils/schematic/Schematic.java @@ -15,7 +15,7 @@ * along with Baritone. If not, see . */ -package baritone.utils; +package baritone.utils.schematic; import baritone.api.utils.ISchematic; import net.minecraft.block.Block; From cef88cde20793340852dc1d24907dc9e82d85586 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 17 Jan 2019 12:25:48 -0800 Subject: [PATCH 19/41] epic super --- src/main/java/baritone/utils/schematic/MapArtSchematic.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/schematic/MapArtSchematic.java b/src/main/java/baritone/utils/schematic/MapArtSchematic.java index 69a46762f..1be131952 100644 --- a/src/main/java/baritone/utils/schematic/MapArtSchematic.java +++ b/src/main/java/baritone/utils/schematic/MapArtSchematic.java @@ -49,7 +49,7 @@ public class MapArtSchematic extends Schematic { } } - private static OptionalInt lastIndexMatching(T[] arr, Predicate predicate) { + private static OptionalInt lastIndexMatching(T[] arr, Predicate predicate) { for (int y = arr.length - 1; y >= 0; y--) { if (predicate.test(arr[y])) { return OptionalInt.of(y); From 1c1fbe83ec68fd365c73aea1713a350b87f2ce2f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Sat, 19 Jan 2019 22:12:54 -0800 Subject: [PATCH 20/41] idk lol --- src/main/java/baritone/process/BuilderProcess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 2d0a157a1..cadb54160 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -58,7 +58,7 @@ import static baritone.api.pathing.movement.ActionCosts.COST_INF; public class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { public BuilderProcess(Baritone baritone) { - super(baritone); + super(baritone, 0); } private HashSet incorrectPositions; From a822d3ef0524587cea8712a8f71ad9d19744e28c Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 6 Feb 2019 16:22:40 -0800 Subject: [PATCH 21/41] horrifying placement --- .../java/baritone/behavior/LookBehavior.java | 2 +- .../baritone/pathing/movement/Movement.java | 2 +- .../pathing/movement/MovementHelper.java | 15 +- .../java/baritone/process/BuilderProcess.java | 187 +++++++++++++++++- .../baritone/utils/InputOverrideHandler.java | 6 +- 5 files changed, 195 insertions(+), 17 deletions(-) diff --git a/src/main/java/baritone/behavior/LookBehavior.java b/src/main/java/baritone/behavior/LookBehavior.java index c2d0326c9..8b115e906 100644 --- a/src/main/java/baritone/behavior/LookBehavior.java +++ b/src/main/java/baritone/behavior/LookBehavior.java @@ -73,7 +73,7 @@ public final class LookBehavior extends Behavior implements ILookBehavior { float desiredPitch = this.target.getPitch(); ctx.player().rotationPitch = desiredPitch; if (desiredPitch == oldPitch) { - nudgeToLevel(); + //nudgeToLevel(); } this.target = null; } diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 4599637ae..4e7eb26f3 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -34,7 +34,7 @@ import java.util.Optional; public abstract class Movement implements IMovement, MovementHelper { - protected static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN}; + public static final EnumFacing[] HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP = {EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST, EnumFacing.DOWN}; protected final IBaritone baritone; protected final IPlayerContext ctx; diff --git a/src/main/java/baritone/pathing/movement/MovementHelper.java b/src/main/java/baritone/pathing/movement/MovementHelper.java index 9bfebcc2a..437aa2c3f 100644 --- a/src/main/java/baritone/pathing/movement/MovementHelper.java +++ b/src/main/java/baritone/pathing/movement/MovementHelper.java @@ -80,6 +80,9 @@ public interface MovementHelper extends ActionCosts, Helper { // be opened by just interacting. return block != Blocks.IRON_DOOR; } + if (block == Blocks.CARPET) { + return canWalkOn(bsi, x, y - 1, z); + } boolean snow = block instanceof BlockSnow; boolean trapdoor = block instanceof BlockTrapDoor; if (snow || trapdoor) { @@ -321,20 +324,22 @@ public interface MovementHelper extends ActionCosts, Helper { } static boolean canPlaceAgainst(BlockStateInterface bsi, int x, int y, int z) { - return canPlaceAgainst(bsi.get0(x, y, z)); + return canPlaceAgainst(bsi, x, y, z, bsi.get0(x, y, z)); } static boolean canPlaceAgainst(BlockStateInterface bsi, BlockPos pos) { - return canPlaceAgainst(bsi.get0(pos.getX(), pos.getY(), pos.getZ())); + return canPlaceAgainst(bsi, pos.getX(), pos.getY(), pos.getZ()); } static boolean canPlaceAgainst(IPlayerContext ctx, BlockPos pos) { return canPlaceAgainst(new BlockStateInterface(ctx), pos); } - static boolean canPlaceAgainst(IBlockState state) { - // TODO isBlockNormalCube isn't the best check for whether or not we can place a block against it. e.g. glass isn't normalCube but we can place against it - return state.isBlockNormalCube(); + static boolean canPlaceAgainst(BlockStateInterface bsi, int x, int y, int z, IBlockState state) { + // can we look at the center of a side face of this block and likely be able to place? + // (thats how this check is used) + // therefore dont include weird things that we technically could place against (like carpet) but practically can't + return state.isBlockNormalCube() || state.isFullBlock() || state.getBlock() == Blocks.GLASS || state.getBlock() == Blocks.STAINED_GLASS; } static double getMiningDurationTicks(CalculationContext context, int x, int y, int z, boolean includeFalling) { diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index cadb54160..5718ea273 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -25,14 +25,13 @@ import baritone.api.pathing.goals.GoalGetToBlock; import baritone.api.process.IBuilderProcess; import baritone.api.process.PathingCommand; import baritone.api.process.PathingCommandType; -import baritone.api.utils.BetterBlockPos; -import baritone.api.utils.ISchematic; -import baritone.api.utils.Rotation; -import baritone.api.utils.RotationUtils; +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.Schematic; import net.minecraft.block.state.IBlockState; @@ -44,8 +43,7 @@ import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.Tuple; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3i; +import net.minecraft.util.math.*; import java.io.File; import java.io.FileInputStream; @@ -65,6 +63,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro private String name; private ISchematic schematic; private Vec3i origin; + private int ticks; public boolean build(String schematicFile) { File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); @@ -145,6 +144,125 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return Optional.empty(); } + public class Placement { + final int hotbarSelection; + final BlockPos placeAgainst; + final EnumFacing side; + final Rotation rot; + + public Placement(int hotbarSelection, BlockPos placeAgainst, EnumFacing side, Rotation rot) { + this.hotbarSelection = hotbarSelection; + this.placeAgainst = placeAgainst; + this.side = side; + this.rot = rot; + } + } + + public Optional searchForPlacables(BuilderCalculationContext bcc) { + BetterBlockPos center = ctx.playerFeet(); + for (int dx = -5; dx <= 5; dx++) { + for (int dy = -5; dy <= 1; dy++) { + for (int dz = -5; dz <= 5; dz++) { + int x = center.x + dx; + int y = center.y + dy; + int z = center.z + dz; + IBlockState desired = bcc.getSchematic(x, y, z); + if (desired == null) { + continue; // irrelevant + } + IBlockState curr = bcc.bsi.get0(x, y, z); + if (MovementHelper.isReplacable(x, y, z, curr, bcc.bsi) && !valid(curr, desired)) { + if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() == Blocks.AIR) { + continue; + } + Optional opt = possibleToPlace(desired, x, y, z, bcc.bsi); + if (opt.isPresent()) { + return opt; + } + } + } + } + } + return Optional.empty(); + } + + public Optional possibleToPlace(IBlockState toPlace, int x, int y, int z, BlockStateInterface bsi) { + for (EnumFacing against : EnumFacing.values()) { + BetterBlockPos placeAgainstPos = new BetterBlockPos(x, y, z).offset(against); + IBlockState placeAgainstState = bsi.get0(placeAgainstPos); + if (MovementHelper.isReplacable(placeAgainstPos.x, placeAgainstPos.y, placeAgainstPos.z, placeAgainstState, bsi)) { + continue; + } + if (!ctx.world().mayPlace(toPlace.getBlock(), new BetterBlockPos(x, y, z), false, against, null)) { + continue; + } + AxisAlignedBB aabb = placeAgainstState.getBoundingBox(ctx.world(), placeAgainstPos); + for (Vec3d placementMultiplier : aabbSideMultipliers(against)) { + double placeX = placeAgainstPos.x + aabb.minX * placementMultiplier.x + aabb.maxX * (1 - placementMultiplier.x); + double placeY = placeAgainstPos.y + aabb.minY * placementMultiplier.y + aabb.maxY * (1 - placementMultiplier.y); + double placeZ = placeAgainstPos.z + aabb.minZ * placementMultiplier.z + aabb.maxZ * (1 - placementMultiplier.z); + Rotation rot = RotationUtils.calcRotationFromVec3d(ctx.playerHead(), new Vec3d(placeX, placeY, placeZ)); + RayTraceResult result = RayTraceUtils.rayTraceTowards(ctx.player(), rot, ctx.playerController().getBlockReachDistance()); + if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK && result.getBlockPos().equals(placeAgainstPos) && result.sideHit == against.getOpposite()) { + OptionalInt hotbar = hasAnyItemThatWouldPlace(toPlace, result, rot); + if (hotbar.isPresent()) { + return Optional.of(new Placement(hotbar.getAsInt(), placeAgainstPos, against.getOpposite(), rot)); + } + } + } + } + return Optional.empty(); + } + + + public OptionalInt hasAnyItemThatWouldPlace(IBlockState desired, RayTraceResult result, Rotation rot) { + for (int i = 0; i < 9; i++) { + ItemStack stack = ctx.player().inventory.mainInventory.get(i); + if (stack.isEmpty() || !(stack.getItem() instanceof ItemBlock)) { + continue; + } + float originalYaw = ctx.player().rotationYaw; + float originalPitch = ctx.player().rotationPitch; + // the state depends on the facing of the player sometimes + ctx.player().rotationYaw = rot.getYaw(); + ctx.player().rotationPitch = rot.getPitch(); + IBlockState wouldBePlaced = ((ItemBlock) stack.getItem()).getBlock().getStateForPlacement( + ctx.world(), + result.getBlockPos().offset(result.sideHit), + result.sideHit, + (float) result.hitVec.x - result.getBlockPos().getX(), // as in PlayerControllerMP + (float) result.hitVec.y - result.getBlockPos().getY(), + (float) result.hitVec.z - result.getBlockPos().getZ(), + stack.getItem().getMetadata(stack.getMetadata()), + ctx.player() + ); + ctx.player().rotationYaw = originalYaw; + ctx.player().rotationPitch = originalPitch; + if (valid(wouldBePlaced, desired)) { + return OptionalInt.of(i); + } + } + return OptionalInt.empty(); + } + + private static Vec3d[] aabbSideMultipliers(EnumFacing side) { + switch (side) { + case UP: + return new Vec3d[]{new Vec3d(0.5, 1, 0.5)}; + case DOWN: + return new Vec3d[]{new Vec3d(0.5, 0, 0.5)}; + case NORTH: + case SOUTH: + case EAST: + case WEST: + double x = side.getXOffset() == 0 ? 0.5 : (1 + side.getXOffset()) / 2D; + double z = side.getZOffset() == 0 ? 0.5 : (1 + side.getZOffset()) / 2D; + return new Vec3d[]{new Vec3d(x, 0.25, z), new Vec3d(x, 0.75, z)}; + default: // null + throw new NullPointerException(); + } + } + @Override public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) { // TODO somehow tell inventorybehavior what we'd like to have on the hotbar @@ -161,6 +279,11 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro onLostControl(); return null; } + if (baritone.getInputOverrideHandler().isInputForcedDown(Input.CLICK_LEFT)) { + ticks = 5; + } else { + ticks--; + } Optional> toBreak = toBreakNearPlayer(bcc); baritone.getInputOverrideHandler().clearAllKeys(); if (toBreak.isPresent() && isSafeToCancel && ctx.player().onGround) { @@ -170,11 +293,22 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro BetterBlockPos pos = toBreak.get().getFirst(); baritone.getLookBehavior().updateTarget(rot, true); MovementHelper.switchToBestToolFor(ctx, bcc.get(pos)); - if (Objects.equals(ctx.objectMouseOver().getBlockPos(), rot) || ctx.playerRotations().isReallyCloseTo(rot)) { + if (Objects.equals(ctx.objectMouseOver().getBlockPos(), pos) || ctx.playerRotations().isReallyCloseTo(rot)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); } return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } + Optional toPlace = searchForPlacables(bcc); + if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround && ticks <= 0) { + Rotation rot = toPlace.get().rot; + baritone.getLookBehavior().updateTarget(rot, true); + ctx.player().inventory.currentItem = toPlace.get().hotbarSelection; + baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true); + if ((Objects.equals(ctx.objectMouseOver().getBlockPos(), toPlace.get().placeAgainst) && ctx.objectMouseOver().sideHit.equals(toPlace.get().side)) || ctx.playerRotations().isReallyCloseTo(rot)) { + baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_RIGHT, true); + } + return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); + } Goal goal = assemble(bcc); if (goal == null) { @@ -241,7 +375,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro List approxPlacable = placable(); List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); Goal[] toBreak = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); - Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(GoalPlace::new).toArray(Goal[]::new); + Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(pos -> placementgoal(pos, bcc)).toArray(Goal[]::new); if (toPlace.length != 0) { return new JankyGoalComposite(new GoalComposite(toPlace), new GoalComposite(toBreak)); @@ -290,6 +424,43 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } } + public Goal placementgoal(BlockPos pos, BuilderCalculationContext bcc) { + boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR; + for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP) { + if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ()).getBlock(), pos, false, facing, null)) { + return new GoalAdjacent(pos, allowSameLevel); + } + } + return new GoalPlace(pos); + } + + public static class GoalAdjacent extends GoalGetToBlock { + boolean allowSameLevel; + + public GoalAdjacent(BlockPos pos, boolean allowSameLevel) { + super(pos); + this.allowSameLevel = allowSameLevel; + } + + public boolean isInGoal(int x, int y, int z) { + if (x == this.x && y == this.y && z == this.z) { + return false; + } + if (!allowSameLevel && y == this.y - 1) { + return false; + } + if (y < this.y - 1) { + return false; + } + return super.isInGoal(x, y, z); + } + + public double heuristic(int x, int y, int z) { + // prioritize lower y coordinates + return this.y * 100 + super.heuristic(x, y, z); + } + } + public static class GoalPlace extends GoalBlock { public GoalPlace(BlockPos placeAt) { super(placeAt.up()); diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 93fbe8759..14fe46cc0 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -69,7 +69,9 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri return false; } if (input == Input.CLICK_RIGHT) { - return isInputForcedDown(Input.CLICK_RIGHT); + boolean ret = isInputForcedDown(Input.CLICK_RIGHT); + System.out.println("click right ret: " + ret); + return ret; } return null; } @@ -122,7 +124,7 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri } private boolean inControl() { - return baritone.getPathingBehavior().isPathing() || baritone != BaritoneAPI.getProvider().getPrimaryBaritone(); + return baritone.getPathingBehavior().isPathing() || baritone.getBuilderProcess().isActive() || baritone != BaritoneAPI.getProvider().getPrimaryBaritone(); } public BlockBreakHelper getBlockBreakHelper() { From 4c4bce35611a4978b15c34b61a7574ad4cab0568 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 6 Feb 2019 22:10:52 -0800 Subject: [PATCH 22/41] define origin --- .../java/baritone/process/BuilderProcess.java | 4 ++-- .../baritone/utils/ExampleBaritoneControl.java | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 5718ea273..bfc8c3b91 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -65,10 +65,10 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro private Vec3i origin; private int ticks; - public boolean build(String schematicFile) { + public boolean build(String schematicFile, BlockPos origin) { File file = new File(new File(Minecraft.getMinecraft().gameDir, "schematics"), schematicFile); System.out.println(file + " " + file.exists()); - return build(schematicFile, file, ctx.playerFeet()); + return build(schematicFile, file, origin); } @Override diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 427bc83a4..b2114ad20 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -255,8 +255,19 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } if (msg.startsWith("build")) { - String file = msg.substring(6) + ".schematic"; - logDirect("" + baritone.getBuilderProcess().build(file)); + String file; + BlockPos origin; + try { + String[] coords = msg.substring("build".length()).split(" "); + file = coords[0] + ".schematic"; + origin = new BlockPos(Integer.parseInt(coords[1]), Integer.parseInt(coords[2]), Integer.parseInt(coords[3])); + } catch (Exception ex) { + file = msg.substring(5) + ".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("axis")) { From 8694d926c48a427d07b2c3aa1f7640df0c50f4fc Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 10:45:51 -0800 Subject: [PATCH 23/41] remove unneeded printouts --- src/main/java/baritone/utils/InputOverrideHandler.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/baritone/utils/InputOverrideHandler.java b/src/main/java/baritone/utils/InputOverrideHandler.java index 14fe46cc0..6a8f92150 100755 --- a/src/main/java/baritone/utils/InputOverrideHandler.java +++ b/src/main/java/baritone/utils/InputOverrideHandler.java @@ -69,9 +69,7 @@ public final class InputOverrideHandler extends Behavior implements IInputOverri return false; } if (input == Input.CLICK_RIGHT) { - boolean ret = isInputForcedDown(Input.CLICK_RIGHT); - System.out.println("click right ret: " + ret); - return ret; + return isInputForcedDown(Input.CLICK_RIGHT); } return null; } From 0ef08142fd178902b2d319cc92e930f4697a6ec2 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 13:12:37 -0800 Subject: [PATCH 24/41] trim spaces from schematic name --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index b2114ad20..aeca0a0c9 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -262,7 +262,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { file = coords[0] + ".schematic"; origin = new BlockPos(Integer.parseInt(coords[1]), Integer.parseInt(coords[2]), Integer.parseInt(coords[3])); } catch (Exception ex) { - file = msg.substring(5) + ".schematic"; + file = msg.substring(5).trim() + ".schematic"; origin = ctx.playerFeet(); } logDirect("Loading '" + file + "' to build from origin " + origin); From 299540725e70f5b06a1ceb77537c89a7e7c2c239 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 7 Feb 2019 13:59:37 -0800 Subject: [PATCH 25/41] a start on inventory movement --- .../baritone/behavior/InventoryBehavior.java | 31 ++++++++++ .../java/baritone/process/BuilderProcess.java | 60 +++++++++++++------ .../utils/ExampleBaritoneControl.java | 2 +- 3 files changed, 74 insertions(+), 19 deletions(-) diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 908e304b9..f3ce4a93d 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -28,6 +28,9 @@ import net.minecraft.inventory.ClickType; import net.minecraft.item.*; import net.minecraft.util.NonNullList; +import java.util.ArrayList; +import java.util.OptionalInt; +import java.util.Random; import java.util.function.Predicate; public class InventoryBehavior extends Behavior { @@ -56,6 +59,34 @@ public class InventoryBehavior extends Behavior { } } + public void attemptToPutOnHotbar(int inMainInvy, Predicate disallowedHotbar) { + OptionalInt destination = getTempHotbarSlot(disallowedHotbar); + if (destination.isPresent()) { + swapWithHotBar(inMainInvy, destination.getAsInt()); + } + } + + public OptionalInt getTempHotbarSlot(Predicate disallowedHotbar) { + // we're using 0 and 8 for pickaxe and throwaway + ArrayList candidates = new ArrayList<>(); + for (int i = 1; i < 8; i++) { + if (ctx.player().inventory.mainInventory.get(i).isEmpty() && !disallowedHotbar.test(i)) { + candidates.add(i); + } + } + if (candidates.isEmpty()) { + for (int i = 1; i < 8; i++) { + if (!disallowedHotbar.test(i)) { + candidates.add(i); + } + } + } + if (candidates.isEmpty()) { + return OptionalInt.empty(); + } + return OptionalInt.of(candidates.get(new Random().nextInt(candidates.size()))); + } + private void swapWithHotBar(int inInventory, int inHotbar) { ctx.playerController().windowClick(ctx.player().inventoryContainer.windowId, inInventory < 9 ? inInventory + 36 : inInventory, inHotbar, ClickType.SWAP, ctx.player()); } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index bfc8c3b91..351f02535 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -158,7 +158,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } } - public Optional searchForPlacables(BuilderCalculationContext bcc) { + public Optional searchForPlacables(BuilderCalculationContext bcc, List desirableOnHotbar) { BetterBlockPos center = ctx.playerFeet(); for (int dx = -5; dx <= 5; dx++) { for (int dy = -5; dy <= 1; dy++) { @@ -175,6 +175,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro if (dy == 1 && bcc.bsi.get0(x, y + 1, z).getBlock() == Blocks.AIR) { continue; } + desirableOnHotbar.add(desired); Optional opt = possibleToPlace(desired, x, y, z, bcc.bsi); if (opt.isPresent()) { return opt; @@ -298,7 +299,8 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } - Optional toPlace = searchForPlacables(bcc); + List desirableOnHotbar = new ArrayList<>(); + Optional toPlace = searchForPlacables(bcc, desirableOnHotbar); if (toPlace.isPresent() && isSafeToCancel && ctx.player().onGround && ticks <= 0) { Rotation rot = toPlace.get().rot; baritone.getLookBehavior().updateTarget(rot, true); @@ -310,11 +312,41 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return new PathingCommand(null, PathingCommandType.REQUEST_PAUSE); } - Goal goal = assemble(bcc); + List approxPlacable = placable(36); + if (Baritone.settings().allowInventory.get()) { + ArrayList usefulSlots = new ArrayList<>(); + List noValidHotbarOption = new ArrayList<>(); + outer: + for (IBlockState desired : desirableOnHotbar) { + for (int i = 0; i < 9; i++) { + if (valid(approxPlacable.get(i), desired)) { + usefulSlots.add(i); + continue outer; + } + } + noValidHotbarOption.add(desired); + } + + outer: + for (int i = 9; i < 36; i++) { + for (IBlockState desired : noValidHotbarOption) { + if (valid(approxPlacable.get(i), desired)) { + baritone.getInventoryBehavior().attemptToPutOnHotbar(i, usefulSlots::contains); + break outer; + } + } + } + } + + + Goal goal = assemble(bcc, approxPlacable.subList(0, 9)); if (goal == null) { - logDirect("Unable to do it =("); - onLostControl(); - return null; + goal = assemble(bcc, approxPlacable); // we're far away, so assume that we have our whole inventory to recalculate placable properly + if (goal == null) { + logDirect("Unable to do it =("); + onLostControl(); + return null; + } } return new PathingCommandContext(goal, PathingCommandType.FORCE_REVALIDATE_GOAL_AND_PATH, bcc); } @@ -371,8 +403,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } } - private Goal assemble(BuilderCalculationContext bcc) { - List approxPlacable = placable(); + private Goal assemble(BuilderCalculationContext bcc, List approxPlacable) { List placable = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() == Blocks.AIR && approxPlacable.contains(bcc.getSchematic(pos.x, pos.y, pos.z))).collect(Collectors.toList()); Goal[] toBreak = incorrectPositions.stream().filter(pos -> bcc.bsi.get0(pos).getBlock() != Blocks.AIR).map(GoalBreak::new).toArray(Goal[]::new); Goal[] toPlace = placable.stream().filter(pos -> !placable.contains(pos.down()) && !placable.contains(pos.down(2))).map(pos -> placementgoal(pos, bcc)).toArray(Goal[]::new); @@ -484,16 +515,9 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return "Building " + name; } - /** - * Hotbar contents, if they were placed - *

- * Always length nine, empty slots become Blocks.AIR.getDefaultState() - * - * @return - */ - public List placable() { + public List placable(int size) { List result = new ArrayList<>(); - for (int i = 0; i < 9; i++) { + 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()); @@ -520,7 +544,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro public BuilderCalculationContext() { super(BuilderProcess.this.baritone, true); // wew lad - this.placable = placable(); + this.placable = placable(9); this.schematic = BuilderProcess.this.schematic; this.originX = origin.getX(); this.originY = origin.getY(); diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index aeca0a0c9..68c9eae1b 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -258,7 +258,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { String file; BlockPos origin; try { - String[] coords = msg.substring("build".length()).split(" "); + String[] coords = msg.substring("build".length()).trim().split(" "); file = coords[0] + ".schematic"; origin = new BlockPos(Integer.parseInt(coords[1]), Integer.parseInt(coords[2]), Integer.parseInt(coords[3])); } catch (Exception ex) { From 963641a818537a507bd20e09140fcfc609f3178d Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 19 Feb 2019 22:50:03 -0800 Subject: [PATCH 26/41] trim big schematics --- src/main/java/baritone/process/BuilderProcess.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 3db08d579..98e114c1b 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -280,6 +280,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro onLostControl(); return null; } + trim(bcc); if (baritone.getInputOverrideHandler().isInputForcedDown(Input.CLICK_LEFT)) { ticks = 5; } else { @@ -366,6 +367,14 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return !incorrectPositions.isEmpty(); } + public void trim(BuilderCalculationContext bcc) { + HashSet copy = new HashSet<>(incorrectPositions); + copy.removeIf(pos -> pos.distanceSq(ctx.player().posX, ctx.player().posY, ctx.player().posZ) > 200); + if (!copy.isEmpty()) { + incorrectPositions = copy; + } + } + public void recalcNearby(BuilderCalculationContext bcc) { BetterBlockPos center = ctx.playerFeet(); for (int dx = -5; dx <= 5; dx++) { From bf12763a100691035d20af5012f276771fb4c27b Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 20 Feb 2019 08:08:52 -0800 Subject: [PATCH 27/41] fix a bunch of bugs with placement --- .../api/pathing/movement/IMovement.java | 4 ---- .../baritone/behavior/MemoryBehavior.java | 3 +-- .../baritone/behavior/PathingBehavior.java | 4 ++++ .../baritone/pathing/movement/Movement.java | 19 ++++++++----------- .../baritone/pathing/path/PathExecutor.java | 4 ++-- .../java/baritone/process/BuilderProcess.java | 3 +++ .../utils/ExampleBaritoneControl.java | 2 +- 7 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/api/java/baritone/api/pathing/movement/IMovement.java b/src/api/java/baritone/api/pathing/movement/IMovement.java index c9b9ea4ba..dae8668d5 100644 --- a/src/api/java/baritone/api/pathing/movement/IMovement.java +++ b/src/api/java/baritone/api/pathing/movement/IMovement.java @@ -45,10 +45,6 @@ public interface IMovement { */ boolean safeToCancel(); - double recalculateCost(); - - double calculateCostWithoutCaching(); - boolean calculatedWhileLoaded(); BetterBlockPos getSrc(); diff --git a/src/main/java/baritone/behavior/MemoryBehavior.java b/src/main/java/baritone/behavior/MemoryBehavior.java index 390ac8592..34fd6b418 100644 --- a/src/main/java/baritone/behavior/MemoryBehavior.java +++ b/src/main/java/baritone/behavior/MemoryBehavior.java @@ -25,7 +25,6 @@ import baritone.api.event.events.TickEvent; import baritone.api.event.events.type.EventState; import baritone.cache.ContainerMemory; import baritone.cache.Waypoint; -import baritone.pathing.movement.CalculationContext; import baritone.utils.BlockStateInterface; import net.minecraft.block.Block; import net.minecraft.block.BlockBed; @@ -196,7 +195,7 @@ public final class MemoryBehavior extends Behavior { } private BlockPos neighboringConnectedBlock(BlockPos in) { - BlockStateInterface bsi = new CalculationContext(baritone).bsi; + BlockStateInterface bsi = baritone.bsi; Block block = bsi.get0(in).getBlock(); if (block != Blocks.TRAPPED_CHEST && block != Blocks.CHEST) { return null; // other things that have contents, but can be placed adjacent without combining diff --git a/src/main/java/baritone/behavior/PathingBehavior.java b/src/main/java/baritone/behavior/PathingBehavior.java index bc3443a7f..bda02de17 100644 --- a/src/main/java/baritone/behavior/PathingBehavior.java +++ b/src/main/java/baritone/behavior/PathingBehavior.java @@ -361,6 +361,10 @@ public final class PathingBehavior extends Behavior implements IPathingBehavior, } } + public CalculationContext secretInternalGetCalculationContext() { + return context; + } + /** * See issue #209 * diff --git a/src/main/java/baritone/pathing/movement/Movement.java b/src/main/java/baritone/pathing/movement/Movement.java index 07ee79aaa..96b650e74 100644 --- a/src/main/java/baritone/pathing/movement/Movement.java +++ b/src/main/java/baritone/pathing/movement/Movement.java @@ -76,31 +76,28 @@ public abstract class Movement implements IMovement, MovementHelper { this(baritone, src, dest, toBreak, null); } - @Override - public double getCost() { + public double getCost() throws NullPointerException { + return cost; + } + + public double getCost(CalculationContext context) { if (cost == null) { - cost = calculateCost(new CalculationContext(baritone)); + cost = calculateCost(context); } return cost; } public abstract double calculateCost(CalculationContext context); - @Override - public double recalculateCost() { + public double recalculateCost(CalculationContext context) { cost = null; - return getCost(); + return getCost(context); } public void override(double cost) { this.cost = cost; } - @Override - public double calculateCostWithoutCaching() { - return calculateCost(new CalculationContext(baritone)); - } - /** * Handles the execution of the latest Movement * State, and offers a Status to the calling class. diff --git a/src/main/java/baritone/pathing/path/PathExecutor.java b/src/main/java/baritone/pathing/path/PathExecutor.java index d4897eecb..4d3b5f3bc 100644 --- a/src/main/java/baritone/pathing/path/PathExecutor.java +++ b/src/main/java/baritone/pathing/path/PathExecutor.java @@ -232,14 +232,14 @@ public class PathExecutor implements IPathExecutor, Helper { // do this only once, when the movement starts, and deliberately get the cost as cached when this path was calculated, not the cost as it is right now currentMovementOriginalCostEstimate = movement.getCost(); for (int i = 1; i < Baritone.settings().costVerificationLookahead.get() && pathPosition + i < path.length() - 1; i++) { - if (path.movements().get(pathPosition + i).calculateCostWithoutCaching() >= ActionCosts.COST_INF && canCancel) { + if (((Movement) path.movements().get(pathPosition + i)).calculateCost(behavior.secretInternalGetCalculationContext()) >= ActionCosts.COST_INF && canCancel) { logDebug("Something has changed in the world and a future movement has become impossible. Cancelling."); cancel(); return true; } } } - double currentCost = movement.recalculateCost(); + double currentCost = ((Movement) movement).recalculateCost(behavior.secretInternalGetCalculationContext()); if (currentCost >= ActionCosts.COST_INF && canCancel) { logDebug("Something has changed in the world and this movement has become impossible. Cancelling."); cancel(); diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 98e114c1b..e7c2f65a6 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -465,6 +465,9 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } public Goal placementgoal(BlockPos pos, BuilderCalculationContext bcc) { + if (ctx.world().getBlockState(pos).getBlock() != Blocks.AIR) { + return new GoalPlace(pos); + } boolean allowSameLevel = ctx.world().getBlockState(pos.up()).getBlock() != Blocks.AIR; for (EnumFacing facing : Movement.HORIZONTALS_BUT_ALSO_DOWN____SO_EVERY_DIRECTION_EXCEPT_UP) { if (MovementHelper.canPlaceAgainst(ctx, pos.offset(facing)) && ctx.world().mayPlace(bcc.getSchematic(pos.getX(), pos.getY(), pos.getZ()).getBlock(), pos, false, facing, null)) { diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index ccca14ba1..d36265695 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -558,7 +558,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { while (moves.contains(null)) { moves.remove(null); } - moves.sort(Comparator.comparingDouble(Movement::getCost)); + moves.sort(Comparator.comparingDouble(move -> move.getCost(new CalculationContext(baritone)))); for (Movement move : moves) { String[] parts = move.getClass().toString().split("\\."); double cost = move.getCost(); From 2b672998e1ccff6953dfa6d9b1dcd403b4aa3936 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 21 Feb 2019 14:24:23 -0800 Subject: [PATCH 28/41] fix two weird ways of getting stuck --- .../java/baritone/process/BuilderProcess.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index e7c2f65a6..9ff8102dc 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -249,9 +249,9 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro private static Vec3d[] aabbSideMultipliers(EnumFacing side) { switch (side) { case UP: - return new Vec3d[]{new Vec3d(0.5, 1, 0.5)}; + 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)}; + 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: @@ -295,6 +295,12 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro BetterBlockPos pos = toBreak.get().getFirst(); baritone.getLookBehavior().updateTarget(rot, true); MovementHelper.switchToBestToolFor(ctx, bcc.get(pos)); + if (ctx.player().isSneaking()) { + // really horrible bug where a block is visible for breaking while sneaking but not otherwise + // so you can't see it, it goes to place something else, sneaks, then the next tick it tries to break + // and is unable since it's unsneaked in the intermediary tick + baritone.getInputOverrideHandler().setInputForceState(Input.SNEAK, true); + } if (Objects.equals(ctx.objectMouseOver().getBlockPos(), pos) || ctx.playerRotations().isReallyCloseTo(rot)) { baritone.getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); } @@ -445,6 +451,11 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro public double heuristic(int x, int y, int z) { return primary.heuristic(x, y, z); } + + @Override + public String toString() { + return "JankyComposite Primary: " + primary + " Fallback: " + fallback; + } } public static class GoalBreak extends GoalGetToBlock { From 3ae05b734867a15fb6b1c869dbb268948f6c6a44 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Thu, 28 Feb 2019 15:26:09 -0800 Subject: [PATCH 29/41] worldedit --- .../java/baritone/process/BuilderProcess.java | 11 +++- .../utils/ExampleBaritoneControl.java | 7 +-- .../java/baritone/utils/GuiClickMeme.java | 62 ++++++++++++++++--- .../java/baritone/utils/PathRenderer.java | 57 +++++++++-------- 4 files changed, 94 insertions(+), 43 deletions(-) diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 9ff8102dc..6c8099f94 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -33,6 +33,7 @@ import baritone.pathing.movement.MovementHelper; import baritone.utils.BaritoneProcessHelper; import baritone.utils.BlockStateInterface; import baritone.utils.PathingCommandContext; +import baritone.utils.schematic.AirSchematic; import baritone.utils.schematic.Schematic; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -94,6 +95,14 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro return true; } + public void clearArea(BlockPos corner1, BlockPos corner2) { + BlockPos origin = new BlockPos(Math.min(corner1.getX(), corner2.getX()), Math.min(corner1.getY(), corner2.getY()), Math.min(corner1.getZ(), corner2.getZ())); + int widthX = Math.abs(corner1.getX() - corner2.getX()) + 1; + int heightY = Math.abs(corner1.getY() - corner2.getY()) + 1; + int lengthZ = Math.abs(corner1.getZ() - corner2.getZ()) + 1; + build("clear area", new AirSchematic(widthX, heightY, lengthZ), origin); + } + private static ISchematic parse(NBTTagCompound schematic) { return new Schematic(schematic); } @@ -273,7 +282,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro // this will work as is, but it'll be trashy // need to iterate over incorrectPositions and see which ones we can "correct" from our current standing position - + baritone.getInputOverrideHandler().clearAllKeys(); BuilderCalculationContext bcc = new BuilderCalculationContext(); if (!recalc(bcc)) { logDirect("Done building"); diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 97d58162a..baa0ae7b5 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -35,7 +35,6 @@ import baritone.pathing.movement.Movement; import baritone.pathing.movement.Moves; import baritone.process.CustomGoalProcess; import baritone.utils.pathing.SegmentedCalculator; -import baritone.utils.schematic.AirSchematic; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ChunkProviderClient; @@ -336,11 +335,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return true; } } - 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; - baritone.getBuilderProcess().build("clear area", new AirSchematic(widthX, heightY, lengthZ), origin); + baritone.getBuilderProcess().clearArea(corner1, corner2); return true; } if (msg.equals("reset")) { diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClickMeme.java index 1db794bab..4bd878e13 100644 --- a/src/main/java/baritone/utils/GuiClickMeme.java +++ b/src/main/java/baritone/utils/GuiClickMeme.java @@ -17,22 +17,23 @@ package baritone.utils; +import baritone.Baritone; import baritone.api.BaritoneAPI; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalTwoBlocks; +import baritone.api.utils.BetterBlockPos; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; +import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import org.lwjgl.BufferUtils; import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.Display; import org.lwjgl.util.glu.GLU; import java.awt.*; -import java.io.IOException; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.Collections; @@ -48,7 +49,8 @@ public class GuiClickMeme extends GuiScreen { private final FloatBuffer TO_SCREEN_BUFFER = BufferUtils.createFloatBuffer(3); private final FloatBuffer TO_WORLD_BUFFER = BufferUtils.createFloatBuffer(3); - private BlockPos meme; + private BlockPos clickStart; + private BlockPos currentMouseOver; @Override public boolean doesGuiPauseGame() { @@ -65,19 +67,40 @@ public class GuiClickMeme extends GuiScreen { Vec3d viewerPos = new Vec3d(mc.getRenderManager().viewerPosX, mc.getRenderManager().viewerPosY, mc.getRenderManager().viewerPosZ); RayTraceResult result = mc.world.rayTraceBlocks(near.add(viewerPos), far.add(viewerPos), false, false, true); if (result != null && result.typeOfHit == RayTraceResult.Type.BLOCK) { - meme = result.getBlockPos(); + currentMouseOver = result.getBlockPos(); } } + } @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { - super.mouseClicked(mouseX, mouseY, mouseButton); + protected void mouseReleased(int mouseX, int mouseY, int mouseButton) { + System.out.println("Mouse released"); if (mouseButton == 0) { - BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalTwoBlocks(meme)); + if (clickStart != null && !clickStart.equals(currentMouseOver)) { + ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getBuilderProcess().clearArea(clickStart, currentMouseOver); + clickStart = null; + } else { + + + BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalTwoBlocks(currentMouseOver)); + } } else if (mouseButton == 1) { - BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(meme.up())); + BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalBlock(currentMouseOver.up())); } + clickStart = null; + } + + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) { + System.out.println("Mouse clicked"); + clickStart = currentMouseOver; + } + + @Override + protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { + System.out.println("Click move"); } public void onRender(float partialTicks) { @@ -85,11 +108,30 @@ public class GuiClickMeme extends GuiScreen { GlStateManager.getFloat(GL_PROJECTION_MATRIX, (FloatBuffer) PROJECTION.clear()); GlStateManager.glGetInteger(GL_VIEWPORT, (IntBuffer) VIEWPORT.clear()); - if (meme != null) { + if (currentMouseOver != null) { Entity e = mc.getRenderViewEntity(); // drawSingleSelectionBox WHEN? - PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(meme), Color.CYAN); + PathRenderer.drawManySelectionBoxes(e, Collections.singletonList(currentMouseOver), Color.CYAN); + if (clickStart != null && !clickStart.equals(currentMouseOver)) { + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); + GlStateManager.color(Color.RED.getColorComponents(null)[0], Color.RED.getColorComponents(null)[1], Color.RED.getColorComponents(null)[2], 0.4F); + GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get()); + GlStateManager.disableTexture2D(); + GlStateManager.depthMask(false); + GlStateManager.disableDepth(); + BetterBlockPos a = new BetterBlockPos(currentMouseOver); + BetterBlockPos b = new BetterBlockPos(clickStart); + PathRenderer.drawAABB(new AxisAlignedBB(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z), Math.max(a.x, b.x) + 1, Math.max(a.y, b.y) + 1, Math.max(a.z, b.z) + 1)); + GlStateManager.enableDepth(); + + GlStateManager.depthMask(true); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + } } + + } public Vec3d toWorld(double x, double y, double z) { diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index c0af870ee..807523e26 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -211,7 +211,7 @@ public final class PathRenderer implements Helper { GlStateManager.disableDepth(); } - float expand = 0.002F; + //BlockPos blockpos = movingObjectPositionIn.getBlockPos(); BlockStateInterface bsi = new BlockStateInterface(BaritoneAPI.getProvider().getPrimaryBaritone().getPlayerContext()); // TODO this assumes same dimension between primary baritone and render view? is this safe? positions.forEach(pos -> { @@ -222,31 +222,7 @@ public final class PathRenderer implements Helper { } else { toDraw = state.getSelectedBoundingBox(player.world, pos); } - toDraw = toDraw.expand(expand, expand, expand).offset(-mc.getRenderManager().viewerPosX, -mc.getRenderManager().viewerPosY, -mc.getRenderManager().viewerPosZ); - BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); - BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); - BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex(); - BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); - TESSELLATOR.draw(); - BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); - BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); - BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex(); - BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); - TESSELLATOR.draw(); - BUFFER.begin(GL_LINES, DefaultVertexFormats.POSITION); - BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); - BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex(); - BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex(); - BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex(); - BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex(); - BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); - TESSELLATOR.draw(); + drawAABB(toDraw); }); if (Baritone.settings().renderSelectionBoxesIgnoreDepth.get()) { @@ -258,6 +234,35 @@ public final class PathRenderer implements Helper { GlStateManager.disableBlend(); } + public static void drawAABB(AxisAlignedBB aabb) { + float expand = 0.002F; + AxisAlignedBB toDraw = aabb.expand(expand, expand, expand).offset(-mc.getRenderManager().viewerPosX, -mc.getRenderManager().viewerPosY, -mc.getRenderManager().viewerPosZ); + BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); + BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); + BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex(); + BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex(); + BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex(); + BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); + TESSELLATOR.draw(); + BUFFER.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION); + BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); + BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex(); + BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex(); + BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); + BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); + TESSELLATOR.draw(); + BUFFER.begin(GL_LINES, DefaultVertexFormats.POSITION); + BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.minZ).endVertex(); + BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.minZ).endVertex(); + BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.minZ).endVertex(); + BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.minZ).endVertex(); + BUFFER.pos(toDraw.maxX, toDraw.minY, toDraw.maxZ).endVertex(); + BUFFER.pos(toDraw.maxX, toDraw.maxY, toDraw.maxZ).endVertex(); + BUFFER.pos(toDraw.minX, toDraw.minY, toDraw.maxZ).endVertex(); + BUFFER.pos(toDraw.minX, toDraw.maxY, toDraw.maxZ).endVertex(); + TESSELLATOR.draw(); + } + public static void drawDankLitGoalBox(Entity player, Goal goal, float partialTicks, Color color) { double renderPosX = mc.getRenderManager().viewerPosX; double renderPosY = mc.getRenderManager().viewerPosY; From 882ac41291261d1e8219f5d821755f085d9c1e35 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 4 Mar 2019 11:28:41 -0800 Subject: [PATCH 30/41] player coords --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index baa0ae7b5..46f092c62 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -257,7 +257,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { try { String[] coords = msg.substring("build".length()).trim().split(" "); file = coords[0] + ".schematic"; - origin = new BlockPos(Integer.parseInt(coords[1]), Integer.parseInt(coords[2]), Integer.parseInt(coords[3])); + 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(); @@ -603,6 +603,10 @@ public class ExampleBaritoneControl extends Behavior implements Helper { return false; } + private int parseOrDefault(String str, int i) { + return str.equals("~") ? i : Integer.parseInt(str); + } + private void log(List stacks) { for (ItemStack stack : stacks) { if (!stack.isEmpty()) { From ba31d209c94e59222e9f13d5f0717bfbc3a3bda7 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Mon, 11 Mar 2019 23:29:39 -0700 Subject: [PATCH 31/41] except what if it compiled --- src/main/java/baritone/behavior/InventoryBehavior.java | 4 ++-- src/main/java/baritone/process/BuilderProcess.java | 4 ++-- src/main/java/baritone/utils/GuiClickMeme.java | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/baritone/behavior/InventoryBehavior.java b/src/main/java/baritone/behavior/InventoryBehavior.java index 70e5997aa..120bc7489 100644 --- a/src/main/java/baritone/behavior/InventoryBehavior.java +++ b/src/main/java/baritone/behavior/InventoryBehavior.java @@ -122,7 +122,7 @@ public class InventoryBehavior extends Behavior { } public boolean hasGenericThrowaway() { - for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { + for (Item item : Baritone.settings().acceptableThrowawayItems.value) { if (throwaway(false, item::equals)) { return true; } @@ -135,7 +135,7 @@ public class InventoryBehavior extends Behavior { if (maybe != null && throwaway(true, item -> item instanceof ItemBlock && ((ItemBlock) item).getBlock().equals(maybe.getBlock()))) { return true; // gotem } - for (Item item : Baritone.settings().acceptableThrowawayItems.get()) { + for (Item item : Baritone.settings().acceptableThrowawayItems.value) { if (throwaway(true, item::equals)) { return true; } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 6c8099f94..09ca34607 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -57,7 +57,7 @@ import static baritone.api.pathing.movement.ActionCosts.COST_INF; public class BuilderProcess extends BaritoneProcessHelper implements IBuilderProcess { public BuilderProcess(Baritone baritone) { - super(baritone, 0); + super(baritone); } private HashSet incorrectPositions; @@ -329,7 +329,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } List approxPlacable = placable(36); - if (Baritone.settings().allowInventory.get()) { + if (Baritone.settings().allowInventory.value) { ArrayList usefulSlots = new ArrayList<>(); List noValidHotbarOption = new ArrayList<>(); outer: diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClickMeme.java index 138471545..50a2d2457 100644 --- a/src/main/java/baritone/utils/GuiClickMeme.java +++ b/src/main/java/baritone/utils/GuiClickMeme.java @@ -115,7 +115,7 @@ public class GuiClickMeme extends GuiScreen { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.color(Color.RED.getColorComponents(null)[0], Color.RED.getColorComponents(null)[1], Color.RED.getColorComponents(null)[2], 0.4F); - GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.get()); + GlStateManager.glLineWidth(Baritone.settings().pathRenderLineWidthPixels.value); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); GlStateManager.disableDepth(); From fa8f2632f546d48be6d172c7aec9ae3aed3e3116 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 18:58:35 -0700 Subject: [PATCH 32/41] dont jump while breaking --- .../java/baritone/pathing/movement/movements/MovementPillar.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java index d725d95fb..d8ab5fef3 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementPillar.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementPillar.java @@ -235,6 +235,7 @@ public class MovementPillar extends Movement { if (reachable.isPresent()) { state.setTarget(new MovementState.MovementTarget(reachable.get(), true)); } + state.setInput(Input.JUMP, false); // breaking is like 5x slower when you're jumping state.setInput(Input.CLICK_LEFT, true); blockIsThere = false; } else if (ctx.player().isSneaking() && (Objects.equals(src.down(), ctx.objectMouseOver().getBlockPos()) || Objects.equals(src, ctx.objectMouseOver().getBlockPos())) && ctx.player().posY > dest.getY() + 0.1) { From a5601fd89ac5e089083c4abe9b29a5eb73f72b5f Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 18:59:20 -0700 Subject: [PATCH 33/41] nutty --- .../java/baritone/api/utils/input/Input.java | 66 +++---------------- 1 file changed, 9 insertions(+), 57 deletions(-) diff --git a/src/api/java/baritone/api/utils/input/Input.java b/src/api/java/baritone/api/utils/input/Input.java index 1e8d44b50..c44f33522 100644 --- a/src/api/java/baritone/api/utils/input/Input.java +++ b/src/api/java/baritone/api/utils/input/Input.java @@ -17,15 +17,6 @@ package baritone.api.utils.input; -import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.GameSettings; -import net.minecraft.client.settings.KeyBinding; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - /** * An {@link Enum} representing the inputs that control the player's * behavior. This includes moving, interacting with blocks, jumping, @@ -36,84 +27,45 @@ public enum Input { /** * The move forward input */ - MOVE_FORWARD(s -> s.keyBindForward), + MOVE_FORWARD, /** * The move back input */ - MOVE_BACK(s -> s.keyBindBack), + MOVE_BACK, /** * The move left input */ - MOVE_LEFT(s -> s.keyBindLeft), + MOVE_LEFT, /** * The move right input */ - MOVE_RIGHT(s -> s.keyBindRight), + MOVE_RIGHT, /** * The attack input */ - CLICK_LEFT(s -> s.keyBindAttack), + CLICK_LEFT, /** * The use item input */ - CLICK_RIGHT(s -> s.keyBindUseItem), + CLICK_RIGHT, /** * The jump input */ - JUMP(s -> s.keyBindJump), + JUMP, /** * The sneak input */ - SNEAK(s -> s.keyBindSneak), + SNEAK, /** * The sprint input */ - SPRINT(s -> s.keyBindSprint); - - /** - * Map of {@link KeyBinding} to {@link Input}. Values should be queried through {@link #getInputForBind(KeyBinding)} - */ - private static final Map bindToInputMap = new HashMap<>(); - - /** - * The actual game {@link KeyBinding} being forced. - */ - private final KeyBinding keyBinding; - - Input(Function keyBindingMapper) { - /* - - Here, a Function is used because referring to a static field in this enum for the game instance, - as it was before, wouldn't be possible in an Enum constructor unless the static field was in an - interface that this class implemented. (Helper acted as this interface) I didn't feel like making - an interface with a game instance field just to not have to do this. - - */ - this.keyBinding = keyBindingMapper.apply(Minecraft.getMinecraft().gameSettings); - } - - /** - * @return The actual game {@link KeyBinding} being forced. - */ - public final KeyBinding getKeyBinding() { - return this.keyBinding; - } - - /** - * Finds the {@link Input} constant that is associated with the specified {@link KeyBinding}. - * - * @param binding The {@link KeyBinding} to find the associated {@link Input} for - * @return The {@link Input} associated with the specified {@link KeyBinding} - */ - public static Input getInputForBind(KeyBinding binding) { - return bindToInputMap.computeIfAbsent(binding, b -> Arrays.stream(values()).filter(input -> input.keyBinding == b).findFirst().orElse(null)); - } + SPRINT } From 866408aece4d663061bfcc00ba2b6547cc4042ec Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 19:17:50 -0700 Subject: [PATCH 34/41] rename --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- .../java/baritone/utils/{GuiClickMeme.java => GuiClick.java} | 2 +- src/main/java/baritone/utils/PathRenderer.java | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) rename src/main/java/baritone/utils/{GuiClickMeme.java => GuiClick.java} (99%) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index 8777a3a99..fcd07101c 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -483,7 +483,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { new Thread(() -> { try { Thread.sleep(100); - mc.addScheduledTask(() -> mc.displayGuiScreen(new GuiClickMeme())); + mc.addScheduledTask(() -> mc.displayGuiScreen(new GuiClick())); } catch (Exception ignored) {} }).start(); logDirect("aight dude"); diff --git a/src/main/java/baritone/utils/GuiClickMeme.java b/src/main/java/baritone/utils/GuiClick.java similarity index 99% rename from src/main/java/baritone/utils/GuiClickMeme.java rename to src/main/java/baritone/utils/GuiClick.java index 50a2d2457..cd10ee17f 100644 --- a/src/main/java/baritone/utils/GuiClickMeme.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -40,7 +40,7 @@ import java.util.Collections; import static org.lwjgl.opengl.GL11.*; -public class GuiClickMeme extends GuiScreen { +public class GuiClick extends GuiScreen { // My name is Brady and I grant leijurv permission to use this pasted code private final FloatBuffer MODELVIEW = BufferUtils.createFloatBuffer(16); diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index a9cb4ce24..7ea201220 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -59,8 +59,8 @@ public final class PathRenderer implements Helper { public static void render(RenderEvent event, PathingBehavior behavior) { float partialTicks = event.getPartialTicks(); Goal goal = behavior.getGoal(); - if (mc.currentScreen instanceof GuiClickMeme) { - ((GuiClickMeme) mc.currentScreen).onRender(partialTicks); + if (mc.currentScreen instanceof GuiClick) { + ((GuiClick) mc.currentScreen).onRender(partialTicks); } int thisPlayerDimension = behavior.baritone.getPlayerContext().world().provider.getDimensionType().getId(); From 909ab553eb19d6a034e3080eda33235479ff7d95 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 22:08:17 -0700 Subject: [PATCH 35/41] small cleanup --- src/main/java/baritone/utils/GuiClick.java | 11 +---------- src/main/java/baritone/utils/PathRenderer.java | 2 +- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/src/main/java/baritone/utils/GuiClick.java b/src/main/java/baritone/utils/GuiClick.java index cd10ee17f..c928d1f1a 100644 --- a/src/main/java/baritone/utils/GuiClick.java +++ b/src/main/java/baritone/utils/GuiClick.java @@ -74,14 +74,11 @@ public class GuiClick extends GuiScreen { @Override protected void mouseReleased(int mouseX, int mouseY, int mouseButton) { - System.out.println("Mouse released"); if (mouseButton == 0) { if (clickStart != null && !clickStart.equals(currentMouseOver)) { ((Baritone) BaritoneAPI.getProvider().getPrimaryBaritone()).getBuilderProcess().clearArea(clickStart, currentMouseOver); clickStart = null; } else { - - BaritoneAPI.getProvider().getPrimaryBaritone().getCustomGoalProcess().setGoalAndPath(new GoalTwoBlocks(currentMouseOver)); } } else if (mouseButton == 1) { @@ -93,16 +90,10 @@ public class GuiClick extends GuiScreen { @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) { - System.out.println("Mouse clicked"); clickStart = currentMouseOver; } - @Override - protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { - System.out.println("Click move"); - } - - public void onRender(float partialTicks) { + public void onRender() { GlStateManager.getFloat(GL_MODELVIEW_MATRIX, (FloatBuffer) MODELVIEW.clear()); GlStateManager.getFloat(GL_PROJECTION_MATRIX, (FloatBuffer) PROJECTION.clear()); GlStateManager.glGetInteger(GL_VIEWPORT, (IntBuffer) VIEWPORT.clear()); diff --git a/src/main/java/baritone/utils/PathRenderer.java b/src/main/java/baritone/utils/PathRenderer.java index 7ea201220..9840e76ec 100644 --- a/src/main/java/baritone/utils/PathRenderer.java +++ b/src/main/java/baritone/utils/PathRenderer.java @@ -60,7 +60,7 @@ public final class PathRenderer implements Helper { float partialTicks = event.getPartialTicks(); Goal goal = behavior.getGoal(); if (mc.currentScreen instanceof GuiClick) { - ((GuiClick) mc.currentScreen).onRender(partialTicks); + ((GuiClick) mc.currentScreen).onRender(); } int thisPlayerDimension = behavior.baritone.getPlayerContext().world().provider.getDimensionType().getId(); From 74e0552be09428b7b9e6f4f35cad27739678d303 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 23:08:06 -0700 Subject: [PATCH 36/41] unscuff water, thanks wwe --- .../pathing/movement/movements/MovementDescend.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java index a0f701e6d..a73ed4fb6 100644 --- a/src/main/java/baritone/pathing/movement/movements/MovementDescend.java +++ b/src/main/java/baritone/pathing/movement/movements/MovementDescend.java @@ -122,7 +122,7 @@ public class MovementDescend extends Movement { // and potentially replace the water we're going to fall into return false; } - if (!MovementHelper.canWalkThrough(context.bsi, destX, y - 2, destZ, below) && below.getBlock() != Blocks.WATER) { + if (!MovementHelper.canWalkThrough(context.bsi, destX, y - 2, destZ, below)) { return false; } double costSoFar = 0; @@ -137,9 +137,10 @@ public class MovementDescend extends Movement { IBlockState ontoBlock = context.get(destX, newY, destZ); int unprotectedFallHeight = fallHeight - (y - effectiveStartHeight); // equal to fallHeight - y + effectiveFallHeight, which is equal to -newY + effectiveFallHeight, which is equal to effectiveFallHeight - newY double tentativeCost = WALK_OFF_BLOCK_COST + FALL_N_BLOCKS_COST[unprotectedFallHeight] + frontBreak + costSoFar; - if ((ontoBlock.getBlock() == Blocks.WATER || ontoBlock.getBlock() == Blocks.FLOWING_WATER) && context.getBlock(destX, newY + 1, destZ) != Blocks.WATERLILY) { - // lilypads are canWalkThrough, but we can't end a fall that should be broken by water if it's covered by a lilypad - // however, don't return impossible in the lilypad scenario, because we could still jump right on it (water that's below a lilypad is canWalkOn so it works) + if (MovementHelper.isWater(ontoBlock.getBlock())) { + if (!MovementHelper.canWalkThrough(context.bsi, destX, newY, destZ, ontoBlock)) { + return false; + } if (context.assumeWalkOnWater) { return false; // TODO fix } From e09541151f9c9a4913af3992b144c5f2bd800a12 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Tue, 12 Mar 2019 23:29:08 -0700 Subject: [PATCH 37/41] update clients --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index a971cad0b..f292bc644 100644 --- a/README.md +++ b/README.md @@ -18,9 +18,8 @@ [![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.3-brightgreen.svg)](https://impactdevelopment.github.io/) -[![Asuna integration](https://img.shields.io/badge/Asuna%20integration-builder%20branch-brightgreen.svg)](https://github.com/EmotionalLove/Asuna/) +[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-master%3F-green.svg)](https://wweclient.com/) [![KAMI integration](https://img.shields.io/badge/KAMI%20integration-v1.0.0-red.svg)](https://github.com/zeroeightysix/KAMI/) -[![WWE integration](https://img.shields.io/badge/WWE%20%22integration%22-v1.0.0%3F%3F%20smh%20license%20violations-red.svg)](https://wweclient.com/) [![Future integration](https://img.shields.io/badge/Future%20integration-Soonâ„¢%3F%3F%3F-red.svg)](https://futureclient.net/) [![ForgeHax integration](https://img.shields.io/badge/ForgeHax%20integration-Soonâ„¢-red.svg)](https://github.com/fr1kin/ForgeHax) From ee6df270ce97653232d7b72021fd80cc472048b5 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Mar 2019 08:50:04 -0700 Subject: [PATCH 38/41] relative coordinates --- src/main/java/baritone/utils/ExampleBaritoneControl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/baritone/utils/ExampleBaritoneControl.java b/src/main/java/baritone/utils/ExampleBaritoneControl.java index fcd07101c..04d1606b1 100644 --- a/src/main/java/baritone/utils/ExampleBaritoneControl.java +++ b/src/main/java/baritone/utils/ExampleBaritoneControl.java @@ -634,7 +634,7 @@ public class ExampleBaritoneControl extends Behavior implements Helper { } private int parseOrDefault(String str, int i) { - return str.equals("~") ? i : Integer.parseInt(str); + return str.equals("~") ? i : str.startsWith("~") ? Integer.parseInt(str.substring(1)) + i : Integer.parseInt(str); } private void log(List stacks) { From a75317cc2c853ce26c4aa491d5d6527b6c024f3e Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Mar 2019 09:17:25 -0700 Subject: [PATCH 39/41] workaround some scuff --- .../java/baritone/api/process/IBaritoneProcess.java | 11 ++++++++++- src/main/java/baritone/process/BuilderProcess.java | 2 +- src/main/java/baritone/process/CustomGoalProcess.java | 2 +- src/main/java/baritone/process/ExploreProcess.java | 2 +- src/main/java/baritone/process/FollowProcess.java | 2 +- src/main/java/baritone/process/GetToBlockProcess.java | 4 ++-- src/main/java/baritone/process/MineProcess.java | 2 +- 7 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/api/java/baritone/api/process/IBaritoneProcess.java b/src/api/java/baritone/api/process/IBaritoneProcess.java index 0339179ca..726260d82 100644 --- a/src/api/java/baritone/api/process/IBaritoneProcess.java +++ b/src/api/java/baritone/api/process/IBaritoneProcess.java @@ -101,5 +101,14 @@ public interface IBaritoneProcess { * * @return A display name that's suitable for a HUD */ - String displayName(); + default String displayName() { + if (!isActive()) { + // i love it when impcat's scuffed HUD calls displayName for inactive processes for 1 tick too long + // causing NPEs when the displayname relies on fields that become null when inactive + return "INACTIVE"; + } + return displayName0(); + } + + String displayName0(); } diff --git a/src/main/java/baritone/process/BuilderProcess.java b/src/main/java/baritone/process/BuilderProcess.java index 09ca34607..9dd6fc922 100644 --- a/src/main/java/baritone/process/BuilderProcess.java +++ b/src/main/java/baritone/process/BuilderProcess.java @@ -543,7 +543,7 @@ public class BuilderProcess extends BaritoneProcessHelper implements IBuilderPro } @Override - public String displayName() { + public String displayName0() { return "Building " + name; } diff --git a/src/main/java/baritone/process/CustomGoalProcess.java b/src/main/java/baritone/process/CustomGoalProcess.java index fe1de0286..fe361ad6a 100644 --- a/src/main/java/baritone/process/CustomGoalProcess.java +++ b/src/main/java/baritone/process/CustomGoalProcess.java @@ -105,7 +105,7 @@ public class CustomGoalProcess extends BaritoneProcessHelper implements ICustomG } @Override - public String displayName() { + public String displayName0() { return "Custom Goal " + this.goal; } diff --git a/src/main/java/baritone/process/ExploreProcess.java b/src/main/java/baritone/process/ExploreProcess.java index 3343d8829..eb98cbde7 100644 --- a/src/main/java/baritone/process/ExploreProcess.java +++ b/src/main/java/baritone/process/ExploreProcess.java @@ -94,7 +94,7 @@ public class ExploreProcess extends BaritoneProcessHelper { } @Override - public String displayName() { + public String displayName0() { return "Exploring around " + explorationOrigin + ", currently going to " + closestUncachedChunk(explorationOrigin); } } diff --git a/src/main/java/baritone/process/FollowProcess.java b/src/main/java/baritone/process/FollowProcess.java index 04e80e03c..6004ac2fd 100644 --- a/src/main/java/baritone/process/FollowProcess.java +++ b/src/main/java/baritone/process/FollowProcess.java @@ -101,7 +101,7 @@ public final class FollowProcess extends BaritoneProcessHelper implements IFollo } @Override - public String displayName() { + public String displayName0() { return "Follow " + cache; } diff --git a/src/main/java/baritone/process/GetToBlockProcess.java b/src/main/java/baritone/process/GetToBlockProcess.java index 092e9ce4e..2dbefd505 100644 --- a/src/main/java/baritone/process/GetToBlockProcess.java +++ b/src/main/java/baritone/process/GetToBlockProcess.java @@ -160,11 +160,11 @@ public class GetToBlockProcess extends BaritoneProcessHelper implements IGetToBl } @Override - public String displayName() { + public String displayName0() { if (knownLocations.isEmpty()) { return "Exploring randomly to find " + gettingTo + ", no known locations"; } - return "Get To Block " + gettingTo + ", " + knownLocations.size() + " known locations"; + return "Get To " + gettingTo + ", " + knownLocations.size() + " known locations"; } private synchronized void rescan(List known, CalculationContext context) { diff --git a/src/main/java/baritone/process/MineProcess.java b/src/main/java/baritone/process/MineProcess.java index 322a966e2..af06556b1 100644 --- a/src/main/java/baritone/process/MineProcess.java +++ b/src/main/java/baritone/process/MineProcess.java @@ -117,7 +117,7 @@ public final class MineProcess extends BaritoneProcessHelper implements IMinePro } @Override - public String displayName() { + public String displayName0() { return "Mine " + mining; } From 89fb5cecd5a3200ed81f75e1bd2721b5824c3f89 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Mar 2019 18:15:21 -0700 Subject: [PATCH 40/41] v1.2.4 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index e52cc3704..a49bfd767 100755 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ */ group 'baritone' -version '1.2.3' +version '1.2.4' buildscript { repositories { From 226ede7ba2c2db2c6ee6fbd494c7aa982377de01 Mon Sep 17 00:00:00 2001 From: Leijurv Date: Wed, 13 Mar 2019 19:23:28 -0700 Subject: [PATCH 41/41] crucial --- src/main/java/baritone/cache/ChunkPacker.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/baritone/cache/ChunkPacker.java b/src/main/java/baritone/cache/ChunkPacker.java index 7f447f87b..66a11fe79 100644 --- a/src/main/java/baritone/cache/ChunkPacker.java +++ b/src/main/java/baritone/cache/ChunkPacker.java @@ -90,8 +90,7 @@ public final class ChunkPacker { IBlockState[] blocks = new IBlockState[256]; for (int z = 0; z < 16; z++) { - https: -//www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html + https://www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html for (int x = 0; x < 16; x++) { for (int y = 255; y >= 0; y--) { int index = CachedChunk.getPositionIndex(x, y, z);