Fix bucket pickup with scale-aware aiming and build-local Botcraft patches

This commit is contained in:
cantyonion committed 2026-11-24 15:31:16 +08:00
1 parent 0a6193f68e
commit 12c7332337
10 files changed
+415 -39

No files matched your search

+3 -3
View File
@@ -26,7 +26,7 @@ if(MINGW)
set(BOTCRAFT_WINDOWS_BETTER_SLEEP OFF CACHE BOOL "" FORCE) set(BOTCRAFT_WINDOWS_BETTER_SLEEP OFF CACHE BOOL "" FORCE)
endif() endif()
include(cmake/ApplyBotcraftPatches.cmake) include(cmake/ApplyBotcraftPatches.cmake)
add_subdirectory(3rd/Botcraft EXCLUDE_FROM_ALL) add_subdirectory("${BILICRAFT_BOTCRAFT_SOURCE_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/_deps/Botcraft-build" EXCLUDE_FROM_ALL)
# Botcraft's public DLL interfaces exchange STL objects: match its MSVC CRT. # Botcraft's public DLL interfaces exchange STL objects: match its MSVC CRT.
if(MSVC) if(MSVC)
@@ -43,7 +43,7 @@ target_include_directories(bilicraft_bot_actions PUBLIC "${CMAKE_CURRENT_SOURCE_
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
target_link_libraries(bilicraft_bot_actions PUBLIC Threads::Threads) target_link_libraries(bilicraft_bot_actions PUBLIC Threads::Threads)
add_library(bilicraft_bot_client STATIC src/BilicraftClient.cpp src/ActionExecutor.cpp src/EntityInteraction.cpp) add_library(bilicraft_bot_client STATIC src/BilicraftClient.cpp src/ActionExecutor.cpp src/EntityInteraction.cpp src/BucketAim.cpp)
target_link_libraries(bilicraft_bot_client PUBLIC bilicraft_bot_config bilicraft_bot_actions botcraft) target_link_libraries(bilicraft_bot_client PUBLIC bilicraft_bot_config bilicraft_bot_actions botcraft)
add_executable(bilicraft-bot main.cpp) add_executable(bilicraft-bot main.cpp)
@@ -73,7 +73,7 @@ if(BUILD_TESTING)
else() else()
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
endif() endif()
add_subdirectory(3rd/googletest EXCLUDE_FROM_ALL) add_subdirectory(3rd/googletest "${CMAKE_CURRENT_BINARY_DIR}/_deps/googletest-build" EXCLUDE_FROM_ALL)
include(GoogleTest) include(GoogleTest)
add_executable(app_config_tests tests/AppConfigTests.cpp) add_executable(app_config_tests tests/AppConfigTests.cpp)
target_link_libraries(app_config_tests PRIVATE bilicraft_bot_config GTest::gtest_main) target_link_libraries(app_config_tests PRIVATE bilicraft_bot_config GTest::gtest_main)
+6 -2
View File
@@ -42,7 +42,7 @@ cmake --build build-custom --config Debug --parallel 2
ctest --test-dir build-custom -C Debug --output-on-failure ctest --test-dir build-custom -C Debug --output-on-failure
``` ```
Botcraft 和 GoogleTest 通过 `3rd/` 中的 Git 子模块固定版本。CMake 配置时自动应用 `patches/` 下的背包同步与展示框生成修复;已应用的补丁会跳过,遇到冲突则停止配置。应用补丁后 Botcraft 子模块显示本地修改属于预期行为,请保留这些修改。 Botcraft 和 GoogleTest 的版本由 `3rd/` 中的 Git 子模块固定。CMake 在构建目录的 `_deps/` 下创建 Botcraft 副本,背包同步、展示框生成和人物眼高补丁都在副本中应用。构建只需读取已初始化的子模块。
测试覆盖参数解析、脚本导入、任务调度、终端输入与编辑、客户端生命周期、背包同步和展示框定位。测试不连接服务器,也不进行 Microsoft 授权;实际服务器及插件行为仍需在线验证。 测试覆盖参数解析、脚本导入、任务调度、终端输入与编辑、客户端生命周期、背包同步和展示框定位。测试不连接服务器,也不进行 Microsoft 授权;实际服务器及插件行为仍需在线验证。
@@ -210,7 +210,11 @@ home
| `sendmsg @to msg` | 发送私信,等价于 `/msg to msg` | | `sendmsg @to msg` | 发送私信,等价于 `/msg to msg` |
| `import action` | 执行同目录的 `action.act`,完成后继续当前文件,仅操作文件可用 | | `import action` | 执行同目录的 `action.act`,完成后继续当前文件,仅操作文件可用 |
点击命令不会自动寻路,请先用 `goto` 移到交互距离内。普通方块右击选择上表面;方块与实体点击均未实现完整视线遮挡检测。 点击命令不会自动寻路,请先用 `goto` 移到交互距离内。机器人根据服务器同步的人物体型倍率和当前姿势计算眼高,并以此瞄准方块、物品展示框和检查交互距离。
主手拿空桶且目标是含水方块或普通水源(水位 `level=0`)时,`rclick x y z` 会瞄准目标并使用空桶取水。服务器按视线判定取水目标,请确保中间没有遮挡。目标是流水或主手拿其他物品时,按普通方式右击方块上表面。
取含水台阶里的水时,请使用台阶自身的方块坐标。调试画面中的“目标液体”可能位于上方或前方的另一格。取水日志会显示实际坐标、方块状态、主手物品和交互类型。生存模式下,机器人等待服务器同步背包中新增的水桶;创造模式下也接受目标已排水的回传。5 秒内未确认时报告错误,不重复发送取水请求。
### 容器与背包 ### 容器与背包
+41 -20
View File
@@ -1,23 +1,44 @@
# Keep the pinned upstream revision reproducible while carrying targeted fixes. # Botcraft downloads assets into its source directory. Give each version and
# Never reset/checkout the submodule: refuse conflicting local edits instead. # patch set its own build-local checkout, including for out-of-tree builds.
find_package(Git REQUIRED) find_package(Git REQUIRED)
set(_botcraft "${CMAKE_CURRENT_SOURCE_DIR}/3rd/Botcraft") set(_upstream "${CMAKE_CURRENT_SOURCE_DIR}/3rd/Botcraft")
foreach(_patch_name Botcraft-inventory-sync.patch Botcraft-item-frame-spawn.patch) execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse HEAD WORKING_DIRECTORY "${_upstream}"
set(_patch "${CMAKE_CURRENT_SOURCE_DIR}/patches/${_patch_name}") OUTPUT_VARIABLE _revision OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
set(_inputs "${_revision}")
set(_patches)
foreach(_name inventory-sync item-frame-spawn player-eye-height)
set(_patch "${CMAKE_CURRENT_SOURCE_DIR}/patches/Botcraft-${_name}.patch")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_patch}") set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_patch}")
execute_process(COMMAND "${GIT_EXECUTABLE}" apply --reverse --check "${_patch}" file(SHA256 "${_patch}" _digest)
WORKING_DIRECTORY "${_botcraft}" RESULT_VARIABLE _already_applied OUTPUT_QUIET ERROR_QUIET) string(APPEND _inputs " ${_digest}")
if(NOT _already_applied EQUAL 0) list(APPEND _patches "${_patch}")
execute_process(COMMAND "${GIT_EXECUTABLE}" apply --check "${_patch}"
WORKING_DIRECTORY "${_botcraft}" RESULT_VARIABLE _can_apply OUTPUT_QUIET ERROR_VARIABLE _error)
if(NOT _can_apply EQUAL 0)
message(FATAL_ERROR "Botcraft patch ${_patch_name} conflicts with the checkout; preserve local changes and inspect it manually.\n${_error}")
endif()
execute_process(COMMAND "${GIT_EXECUTABLE}" apply "${_patch}"
WORKING_DIRECTORY "${_botcraft}" RESULT_VARIABLE _applied ERROR_VARIABLE _error)
if(NOT _applied EQUAL 0)
message(FATAL_ERROR "Could not apply Botcraft patch ${_patch_name}: ${_error}")
endif()
message(STATUS "Applied Botcraft patch ${_patch_name}")
endif()
endforeach() endforeach()
string(SHA256 _key "${_inputs}")
string(SUBSTRING "${_key}" 0 16 _key)
set(BILICRAFT_BOTCRAFT_SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/_deps/Botcraft-${_key}")
set(_copy "${BILICRAFT_BOTCRAFT_SOURCE_DIR}")
if(NOT EXISTS "${_copy}/.git")
execute_process(COMMAND "${GIT_EXECUTABLE}" clone --no-checkout --no-hardlinks
"${_upstream}" "${_copy}" COMMAND_ERROR_IS_FATAL ANY)
endif()
if(NOT EXISTS "${_copy}/.git/bilicraft-patched")
execute_process(COMMAND "${GIT_EXECUTABLE}" checkout --detach "${_revision}"
WORKING_DIRECTORY "${_copy}" COMMAND_ERROR_IS_FATAL ANY)
execute_process(COMMAND "${GIT_EXECUTABLE}" apply ${_patches}
WORKING_DIRECTORY "${_copy}" COMMAND_ERROR_IS_FATAL ANY)
file(TOUCH "${_copy}/.git/bilicraft-patched")
endif()
# Reuse an initialized Asio checkout and downloaded game assets when available.
# On a fresh machine Botcraft fetches them in its build-local checkout.
if(EXISTS "${_upstream}/3rdparty/asio/.git" AND NOT EXISTS "${_copy}/3rdparty/asio/.git")
execute_process(COMMAND "${GIT_EXECUTABLE}" -c protocol.file.allow=always
-c "submodule.3rdparty/asio.url=${_upstream}/3rdparty/asio"
submodule update --init -- 3rdparty/asio
WORKING_DIRECTORY "${_copy}" COMMAND_ERROR_IS_FATAL ANY)
endif()
set(_assets "Assets/${BOTCRAFT_GAME_VERSION}/minecraft")
if(IS_DIRECTORY "${_upstream}/${_assets}" AND NOT EXISTS "${_copy}/${_assets}")
file(COPY "${_upstream}/${_assets}" DESTINATION "${_copy}/Assets/${BOTCRAFT_GAME_VERSION}")
endif()
+5
View File
@@ -8,10 +8,12 @@
namespace Botcraft namespace Botcraft
{ {
class Window; class Window;
class Blockstate;
} }
namespace ProtocolCraft namespace ProtocolCraft
{ {
class Packet;
class ServerboundContainerClickPacket; class ServerboundContainerClickPacket;
class Slot; class Slot;
} }
@@ -35,6 +37,9 @@ void MaintainActionInputs(BilicraftClient &client);
short ActionGuiSlot(Botcraft::InventoryType type, int row, int col); short ActionGuiSlot(Botcraft::InventoryType type, int row, int col);
short ActionBackpackSlot(int row, int col); short ActionBackpackSlot(int row, int col);
short ActionHotbarIndex(int slot); short ActionHotbarIndex(int slot);
int CountWaterBuckets(const Botcraft::Window &window);
std::shared_ptr<ProtocolCraft::Packet> MakeBlockRightClickPacket(const ActionCommand &command,
const Botcraft::Blockstate &block, const ProtocolCraft::Slot &mainHand, float yaw, float pitch, int sequence);
void ValidateActionPosition(int x, int y, int z); void ValidateActionPosition(int x, int y, int z);
enum class FrameAttackIntent { None, TakeItem, RemoveFrame }; enum class FrameAttackIntent { None, TakeItem, RemoveFrame };
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include "botcraft/Game/Vector3.hpp"
#include <optional>
namespace Botcraft { class World; }
namespace Bilicraft
{
std::optional<Botcraft::Vector3<double>> FindBucketAim(const Botcraft::World &world,
const Botcraft::Vector3<double> &eyes, const Botcraft::Position &target, double reach);
}
+29
View File
@@ -0,0 +1,29 @@
diff --git a/botcraft/src/Game/Entities/entities/player/PlayerEntity.cpp b/botcraft/src/Game/Entities/entities/player/PlayerEntity.cpp
index c62026d6..f7f4760a 100644
--- a/botcraft/src/Game/Entities/entities/player/PlayerEntity.cpp
+++ b/botcraft/src/Game/Entities/entities/player/PlayerEntity.cpp
@@ -376,16 +376,21 @@ namespace Botcraft
double PlayerEntity::GetEyeHeightImpl() const
{
#if PROTOCOL_VERSION > 404 /* > 1.13.2 */
+#if PROTOCOL_VERSION > 765 /* > 1.20.4 */
+ const double scale = attributes.at(EntityAttribute::Type::Scale).GetValue();
+#else
+ constexpr double scale = 1.0;
+#endif
switch (GetDataPoseImpl())
{
case Pose::Swimming:
case Pose::FallFlying:
case Pose::SpinAttack:
- return 0.4;
+ return 0.4 * scale;
case Pose::Crouching:
- return 1.27;
+ return 1.27 * scale;
default:
- return 1.62;
+ return 1.62 * scale;
}
#else
return 1.62;
+119 -14
View File
@@ -2,6 +2,7 @@
#include "ActionFile.h" #include "ActionFile.h"
#include "BilicraftClient.h" #include "BilicraftClient.h"
#include "BucketAim.h"
#include "EntityInteraction.h" #include "EntityInteraction.h"
#include <chrono> #include <chrono>
@@ -14,6 +15,7 @@
#include "botcraft/AI/Tasks/DigTask.hpp" #include "botcraft/AI/Tasks/DigTask.hpp"
#include "botcraft/AI/Tasks/InventoryTasks.hpp" #include "botcraft/AI/Tasks/InventoryTasks.hpp"
#include "botcraft/AI/Tasks/PathfindingTask.hpp" #include "botcraft/AI/Tasks/PathfindingTask.hpp"
#include "botcraft/Game/AssetsManager.hpp"
#include "botcraft/Game/Entities/LocalPlayer.hpp" #include "botcraft/Game/Entities/LocalPlayer.hpp"
#include "botcraft/Game/Entities/EntityManager.hpp" #include "botcraft/Game/Entities/EntityManager.hpp"
#include "botcraft/Game/Entities/entities/decoration/ItemFrameEntity.hpp" #include "botcraft/Game/Entities/entities/decoration/ItemFrameEntity.hpp"
@@ -159,7 +161,7 @@ Botcraft::Vector3<double> BlockCenter(const ActionCommand &command)
return Botcraft::Vector3<double>(command.x + 0.5, command.y + 0.5, command.z + 0.5); return Botcraft::Vector3<double>(command.x + 0.5, command.y + 0.5, command.z + 0.5);
} }
void CheckTarget(BilicraftClient &client, const ActionCommand &command) const Botcraft::Blockstate &CheckTarget(BilicraftClient &client, const ActionCommand &command)
{ {
const Botcraft::Position pos(command.x, command.y, command.z); const Botcraft::Position pos(command.x, command.y, command.z);
Await(client, [&] { return client.GetWorld()->GetBlock(pos) != nullptr; }, 5s, "target chunk to load"); Await(client, [&] { return client.GetWorld()->GetBlock(pos) != nullptr; }, 5s, "target chunk to load");
@@ -172,6 +174,7 @@ void CheckTarget(BilicraftClient &client, const ActionCommand &command)
// reach boundaries. This does not claim to implement server line of sight. // reach boundaries. This does not claim to implement server line of sight.
Require(range > 0 && eyes.SqrDist(BlockCenter(command)) < range * range, Require(range > 0 && eyes.SqrDist(BlockCenter(command)) < range * range,
"target is outside block interaction reach; use goto explicitly"); "target is outside block interaction reach; use goto explicitly");
return *block;
} }
void Swing(BilicraftClient &client) void Swing(BilicraftClient &client)
@@ -181,12 +184,32 @@ void Swing(BilicraftClient &client)
client.GetNetworkManager()->Send(packet); client.GetNetworkManager()->Send(packet);
} }
bool IsWaterSource(const Botcraft::Blockstate &block)
{
return block.GetName() == "minecraft:water" && block.GetVariableValue("level") == "0";
}
bool HoldsEmptyBucket(const ProtocolCraft::Slot &hand)
{
static const auto bucket = Botcraft::AssetsManager::getInstance().GetItemID("minecraft:bucket");
return !hand.IsEmptySlot() && hand.GetItemId() == bucket;
}
std::string DescribeBlock(const Botcraft::Blockstate *block)
{
if (!block) return "unloaded";
std::string description = block->GetName();
for (const auto &[key, value] : block->GetVariables())
description += " " + key + "=" + value;
return description;
}
Status ClickBlock(BilicraftClient &client, const ActionCommand &command) Status ClickBlock(BilicraftClient &client, const ActionCommand &command)
{ {
CheckTarget(client, command); CheckTarget(client, command);
if (Botcraft::LookAt(client, BlockCenter(command), true, true) != Status::Success) if (Botcraft::LookAt(client, BlockCenter(command), true, true) != Status::Success)
return Status::Failure; return Status::Failure;
CheckTarget(client, command); // The world/player may have changed during Yield. const auto &block = CheckTarget(client, command); // The world/player may have changed during Yield.
ScopedSneak sneak(client, command.shift); ScopedSneak sneak(client, command.shift);
const Botcraft::Position pos(command.x, command.y, command.z); const Botcraft::Position pos(command.x, command.y, command.z);
if (command.kind == ActionKind::LeftClick) if (command.kind == ActionKind::LeftClick)
@@ -199,20 +222,60 @@ Status ClickBlock(BilicraftClient &client, const ActionCommand &command)
return Status::Success; return Status::Success;
} }
// InteractWithBlock unconditionally pathfinds when its own range check const auto player = client.GetLocalPlayer();
// fails. Use its verified packet layout directly to guarantee no movement. const auto inventory = client.GetInventoryManager();
auto packet = std::make_shared<ProtocolCraft::ServerboundUseItemOnPacket>(); const auto window = inventory->GetPlayerInventory();
packet->SetLocation(pos.ToNetworkPosition()); const auto slot = Botcraft::Window::INVENTORY_HOTBAR_START + inventory->GetIndexHotbarSelected();
packet->SetDirection(static_cast<int>(Botcraft::PlayerDiggingFace::Up)); const auto hand = window->GetSlot(slot);
packet->SetCursorPositionX(0.5f); const bool emptyBucket = HoldsEmptyBucket(hand);
packet->SetCursorPositionY(1.0f); const bool pickup = emptyBucket && (block.IsWaterlogged() || IsWaterSource(block));
packet->SetCursorPositionZ(0.5f); const int waterBucketsBefore = pickup ? CountWaterBuckets(*window) : 0;
packet->SetInside(false); const auto world = client.GetWorld();
packet->SetWorldBorderHit(false); if (pickup)
packet->SetHand(static_cast<int>(Botcraft::Hand::Main)); {
packet->SetSequence(client.GetWorld()->GetNextWorldInteractionSequenceId()); const auto eyes = player->GetPosition() + Botcraft::Vector3<double>(0, player->GetEyeHeight(), 0);
const auto aim = FindBucketAim(*world, eyes, pos, player->GetAttributePlayerBlockInteractionRangeValue());
Require(aim.has_value(), "no visible point for bucket pickup at (" + std::to_string(pos.x) + "," +
std::to_string(pos.y) + "," + std::to_string(pos.z) + "); change standing position");
if (Botcraft::LookAt(client, *aim, true, true) != Status::Success) return Status::Failure;
Require(&CheckTarget(client, command) == &block && inventory->GetIndexHotbarSelected() ==
slot - Botcraft::Window::INVENTORY_HOTBAR_START && HoldsEmptyBucket(window->GetSlot(slot)),
"target or main hand changed while aiming for bucket pickup");
}
const auto yaw = player->GetYaw();
const auto pitch = player->GetPitch();
auto packet = MakeBlockRightClickPacket(command, block, hand, yaw, pitch, world->GetNextWorldInteractionSequenceId());
if (emptyBucket || block.IsWaterlogged() || IsWaterSource(block))
{
const auto *item = hand.IsEmptySlot() ? nullptr : Botcraft::AssetsManager::getInstance().GetItem(hand.GetItemId());
LOG_INFO("rclick (" << pos.x << "," << pos.y << "," << pos.z << ") " << DescribeBlock(&block)
<< "; main hand=" << (hand.IsEmptySlot() ? "empty" :
(item ? item->GetName() : std::to_string(hand.GetItemId())))
<< "; " << (pickup ? "bucket pickup" : "block interaction"));
}
client.GetNetworkManager()->Send(packet); client.GetNetworkManager()->Send(packet);
Swing(client); Swing(client);
if (pickup)
{
try
{
Await(client, [&] {
Require(client.GetWorld() == world && inventory->GetPlayerInventory() == window,
"world or inventory changed during bucket pickup");
if (CountWaterBuckets(*window) > waterBucketsBefore) return true;
// Creative may keep an empty bucket even after successfully draining a block.
const auto *now = world->GetBlock(pos);
return player->GetInstabuild() && now && !now->IsWaterlogged() && !IsWaterSource(*now);
}, 5s, "server confirmation of bucket pickup (not retried)");
}
catch (const std::exception &error)
{
throw std::runtime_error(std::string(error.what()) + "; target=(" + std::to_string(pos.x) + "," +
std::to_string(pos.y) + "," + std::to_string(pos.z) + ") " + DescribeBlock(world->GetBlock(pos)) +
"; water buckets before=" + std::to_string(waterBucketsBefore) +
", now=" + std::to_string(CountWaterBuckets(*window)));
}
}
return Status::Success; return Status::Success;
} }
@@ -438,6 +501,48 @@ Status DropHotbar(BilicraftClient &client, const ActionCommand &command)
} }
} // namespace } // namespace
int CountWaterBuckets(const Botcraft::Window &window)
{
static const auto waterBucket = Botcraft::AssetsManager::getInstance().GetItemID("minecraft:water_bucket");
int count = 0;
const auto slots = window.GetLockedSlots();
for (const auto &[index, stack] : *slots)
if (index >= Botcraft::Window::INVENTORY_STORAGE_START && index <= Botcraft::Window::INVENTORY_OFFHAND_INDEX &&
!stack.IsEmptySlot() && stack.GetItemId() == waterBucket)
count += stack.GetItemCount();
return count;
}
std::shared_ptr<ProtocolCraft::Packet> MakeBlockRightClickPacket(const ActionCommand &command,
const Botcraft::Blockstate &block, const ProtocolCraft::Slot &mainHand, float yaw, float pitch, int sequence)
{
if ((block.IsWaterlogged() || IsWaterSource(block)) && HoldsEmptyBucket(mainHand))
{
// The server raycasts from the player's eyes along this rotation.
auto packet = std::make_shared<ProtocolCraft::ServerboundUseItemPacket>();
packet->SetHand(static_cast<int>(Botcraft::Hand::Main));
packet->SetSequence(sequence);
packet->SetYRot(yaw);
packet->SetXRot(pitch);
return packet;
}
const Botcraft::Position pos(command.x, command.y, command.z);
// InteractWithBlock unconditionally pathfinds when its own range check
// fails. Use its verified packet layout directly to guarantee no movement.
auto packet = std::make_shared<ProtocolCraft::ServerboundUseItemOnPacket>();
packet->SetLocation(pos.ToNetworkPosition());
packet->SetDirection(static_cast<int>(Botcraft::PlayerDiggingFace::Up));
packet->SetCursorPositionX(0.5f);
packet->SetCursorPositionY(1.0f);
packet->SetCursorPositionZ(0.5f);
packet->SetInside(false);
packet->SetWorldBorderHit(false);
packet->SetHand(static_cast<int>(Botcraft::Hand::Main));
packet->SetSequence(sequence);
return packet;
}
void ValidateActionPosition(int x, int y, int z) void ValidateActionPosition(int x, int y, int z)
{ {
// NetworkPosition packs signed 26/12/26-bit coordinates. Restrict X/Z to // NetworkPosition packs signed 26/12/26-bit coordinates. Restrict X/Z to
+81
View File
@@ -0,0 +1,81 @@
#include "BucketAim.h"
#include "botcraft/Game/World/World.hpp"
#include "botcraft/Game/World/Blockstate.hpp"
#include <algorithm>
#include <cmath>
#include <vector>
namespace Bilicraft
{
namespace
{
using namespace Botcraft;
bool IntersectsSegment(const AABB &box, const Vector3<double> &start, const Vector3<double> &end)
{
const auto lo = box.GetMin(), hi = box.GetMax();
double enter = 0, leave = 1;
for (int axis = 0; axis < 3; ++axis)
{
const double delta = end[axis] - start[axis];
if (delta == 0)
{
if (start[axis] < lo[axis] || start[axis] > hi[axis]) return false;
continue;
}
const double a = (lo[axis] - start[axis]) / delta;
const double b = (hi[axis] - start[axis]) / delta;
enter = std::max(enter, std::min(a, b));
leave = std::min(leave, std::max(a, b));
if (enter > leave) return false;
}
return true;
}
}
std::optional<Botcraft::Vector3<double>> FindBucketAim(const Botcraft::World &world,
const Botcraft::Vector3<double> &eyes, const Botcraft::Position &target, double reach)
{
// Include the row below the rays because fences and walls can extend above their cell.
const Position eyeCell(std::floor(eyes.x), std::floor(eyes.y), std::floor(eyes.z));
std::vector<AABB> obstacles;
for (int x = std::min(eyeCell.x, target.x); x <= std::max(eyeCell.x, target.x); ++x)
for (int y = std::min(eyeCell.y, target.y) - 1; y <= std::max(eyeCell.y, target.y); ++y)
for (int z = std::min(eyeCell.z, target.z); z <= std::max(eyeCell.z, target.z); ++z)
{
const Position cell(x, y, z);
if (cell == target) continue;
const auto *state = world.GetBlock(cell);
if (!state)
{
obstacles.emplace_back(Vector3<double>(x + 0.5, y + 0.5, z + 0.5), Vector3<double>(0.5));
continue;
}
if (state->IsAir()) continue;
const auto boxes = state->GetCollidersAtPos(cell);
obstacles.insert(obstacles.end(), boxes.begin(), boxes.end());
// Bubble columns also contain source water and have no level property.
if (state->IsWaterlogged() || state->GetName() == "minecraft:bubble_column" ||
(state->IsFluid() && state->GetVariableValue("level") == "0"))
{
const auto *above = world.GetBlock(cell + Position(0, 1, 0));
const bool continuous = above && ((state->IsWaterOrWaterlogged() && above->IsWaterOrWaterlogged()) ||
(state->IsLava() && above->IsLava()));
const double halfHeight = (continuous ? 1.0 : state->GetFluidHeight()) / 2;
obstacles.emplace_back(Vector3<double>(x + 0.5, y + halfHeight, z + 0.5),
Vector3<double>(0.5, halfHeight, 0.5));
}
}
// Try the center first, then points below source-fluid height inside the target cell.
for (double x : {0.5, 0.25, 0.75, 0.1, 0.9})
for (double y : {0.5, 0.25, 0.75, 0.1, 0.85})
for (double z : {0.5, 0.25, 0.75, 0.1, 0.9})
{
const Vector3<double> point(target.x + x, target.y + y, target.z + z);
if (eyes.SqrDist(point) < reach * reach && std::none_of(obstacles.begin(), obstacles.end(),
[&](const AABB &box) { return IntersectsSegment(box, eyes, point); })) return point;
}
return std::nullopt;
}
}
+96
View File
@@ -1,6 +1,9 @@
#include "ActionExecutor.h" #include "ActionExecutor.h"
#include "ActionFile.h" #include "ActionFile.h"
#include "BilicraftClient.h" #include "BilicraftClient.h"
#include "BucketAim.h"
#include "botcraft/Game/Entities/LocalPlayer.hpp"
#include "botcraft/Game/World/World.hpp"
#include <climits> #include <climits>
#include <stdexcept> #include <stdexcept>
@@ -10,12 +13,105 @@
#include "protocolCraft/Packets/Game/Serverbound/ServerboundContainerClickPacket.hpp" #include "protocolCraft/Packets/Game/Serverbound/ServerboundContainerClickPacket.hpp"
#include "botcraft/Game/Inventory/Window.hpp" #include "botcraft/Game/Inventory/Window.hpp"
#include "botcraft/Game/AssetsManager.hpp"
namespace namespace
{ {
using namespace Bilicraft; using namespace Bilicraft;
using Botcraft::InventoryType; using Botcraft::InventoryType;
TEST(ActionExecutor, EmptyBucketUsesAimedMainHandOnWaterloggedBlocksAndWaterSources)
{
auto &assets = Botcraft::AssetsManager::getInstance();
const Botcraft::Blockstate *wet = nullptr, *dry = nullptr;
for (const auto *state : assets.GetBlockstates("minecraft:oak_slab"))
(state->IsWaterlogged() ? wet : dry) = state;
ASSERT_NE(wet, nullptr);
ASSERT_NE(dry, nullptr);
const auto command = ParseInteractiveCommand("rclick 1 1 1").value();
ProtocolCraft::Slot hand;
hand.SetItemCount(1);
hand.SetItemId(assets.GetItemID("minecraft:bucket"));
const auto click = [&](const Botcraft::Blockstate &state) {
return MakeBlockRightClickPacket(command, state, hand, 73.0f, -18.0f, 42);
};
const auto pickup = std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemPacket>(click(*wet));
ASSERT_TRUE(pickup);
EXPECT_EQ(pickup->GetHand(), static_cast<int>(Botcraft::Hand::Main));
EXPECT_EQ(pickup->GetYRot(), 73.0f);
EXPECT_EQ(pickup->GetXRot(), -18.0f);
EXPECT_EQ(pickup->GetSequence(), 42);
EXPECT_TRUE(std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemOnPacket>(click(*dry)));
const auto waterStates = assets.GetBlockstates("minecraft:water");
ASSERT_EQ(waterStates.size(), 16u);
for (const auto *water : waterStates)
{
const auto &level = water->GetVariableValue("level");
SCOPED_TRACE(level);
if (level == "0")
EXPECT_TRUE(std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemPacket>(click(*water)));
else
EXPECT_TRUE(std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemOnPacket>(click(*water)));
}
hand.SetItemId(assets.GetItemID("minecraft:water_bucket"));
for (const auto *water : waterStates)
EXPECT_TRUE(std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemOnPacket>(click(*water)));
EXPECT_TRUE(std::dynamic_pointer_cast<ProtocolCraft::ServerboundUseItemOnPacket>(click(*wet)));
}
TEST(ActionExecutor, BucketCanReachSourceThroughGapBelowUpperSlab)
{
auto &assets = Botcraft::AssetsManager::getInstance();
Botcraft::World world(false);
const std::string dimension = "minecraft:overworld";
world.SetDimensionMinY(dimension, 0);
world.SetDimensionHeight(dimension, 256);
world.LoadChunk(0, 0, dimension);
const Botcraft::Position target(5, 93, 5);
world.SetBlock({5, 93, 4}, assets.GetBlockstate("minecraft:oak_planks")->GetId());
for (const auto *slab : assets.GetBlockstates("minecraft:oak_slab"))
if (slab->GetVariableValue("type") == "top")
world.SetBlock({5, slab->IsWaterlogged() ? 92 : 94, 5}, slab->GetId());
for (const auto *water : assets.GetBlockstates("minecraft:water"))
if (water->GetVariableValue("level") == "0") world.SetBlock(target, water->GetId());
Botcraft::LocalPlayer player;
player.SetPosition({5.438707, 94, 4.368732});
for (const double scale : {1.0, 0.58522856})
{
SCOPED_TRACE(scale);
player.SetAttributeBaseValue(Botcraft::EntityAttribute::Type::Scale, scale);
const auto eyes = player.GetPosition() + Botcraft::Vector3<double>(0, player.GetEyeHeight(), 0);
const auto aim = FindBucketAim(world, eyes, target, 4.5);
ASSERT_TRUE(aim);
player.LookAt(*aim, true);
const auto direction = player.GetFrontVector();
const double frontY = 94 + 1.62 * scale + direction.y * (5 - eyes.z) / direction.z;
EXPECT_GT(frontY, 94.0);
EXPECT_LT(frontY, 94.5);
EXPECT_FALSE(FindBucketAim(world, eyes, {5, 92, 5}, 4.5));
}
}
TEST(ActionExecutor, EyeHeightAndLookAtFollowChangesToScaleAndPose)
{
Botcraft::LocalPlayer player;
player.SetPosition({0, 10, 0});
for (const double scale : {0.58522856, 2.0, 1.0})
{
SCOPED_TRACE(scale);
player.SetAttributeBaseValue(Botcraft::EntityAttribute::Type::Scale, scale);
for (const auto [pose, height] : {std::pair{Botcraft::Pose::Standing, 1.62},
std::pair{Botcraft::Pose::Crouching, 1.27},
std::pair{Botcraft::Pose::Swimming, 0.4}})
{
player.SetDataPose(pose);
EXPECT_DOUBLE_EQ(player.GetEyeHeight(), height * scale);
player.LookAt({0, 10 + height * scale, 2}, true);
EXPECT_NEAR(player.GetPitch(), 0, 1e-5);
}
}
}
TEST(ActionExecutor, MapsEveryGenericContainerSize) TEST(ActionExecutor, MapsEveryGenericContainerSize)
{ {
const InventoryType types[] = {InventoryType::Generic9x1, InventoryType::Generic9x2, InventoryType::Generic9x3, const InventoryType types[] = {InventoryType::Generic9x1, InventoryType::Generic9x2, InventoryType::Generic9x3,
+23
View File
@@ -2,6 +2,7 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include "botcraft/Game/AssetsManager.hpp"
#include "botcraft/Game/Inventory/InventoryManager.hpp" #include "botcraft/Game/Inventory/InventoryManager.hpp"
#include "botcraft/Game/Inventory/Window.hpp" #include "botcraft/Game/Inventory/Window.hpp"
@@ -44,6 +45,28 @@ class InventorySync : public testing::Test
} }
}; };
TEST_F(InventorySync, FilledBucketConfirmationCountsServerUpdatesAcrossInventory)
{
Full();
auto &assets = Botcraft::AssetsManager::getInstance();
auto emptyBuckets = Item(2);
emptyBuckets.SetItemId(assets.GetItemID("minecraft:bucket"));
auto filled = Item(1);
filled.SetItemId(assets.GetItemID("minecraft:water_bucket"));
PlayerSlot(0, emptyBuckets);
PlayerSlot(1, filled);
const auto window = inventory.GetPlayerInventory();
const auto before = Bilicraft::CountWaterBuckets(*window);
ASSERT_EQ(before, 1);
emptyBuckets.SetItemCount(1);
PlayerSlot(0, emptyBuckets);
EXPECT_EQ(Bilicraft::CountWaterBuckets(*window), before);
PlayerSlot(9, filled);
EXPECT_EQ(Bilicraft::CountWaterBuckets(*window), before + 1);
PlayerSlot(0, filled);
EXPECT_EQ(Bilicraft::CountWaterBuckets(*window), before + 2);
}
TEST_F(InventorySync, EmptyHotbarUpdateClearsHeldItemInsteadOfCraftingOutput) TEST_F(InventorySync, EmptyHotbarUpdateClearsHeldItemInsteadOfCraftingOutput)
{ {
Full(); Full();