init commit

This commit is contained in:
cantyonion committed 2026-11-24 12:43:25 +08:00
commit 1497f114e6
47 files changed
+8358

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
#pragma once
#include <memory>
#include "botcraft/AI/Status.hpp"
#include "botcraft/Game/Enums.hpp"
namespace Botcraft
{
class Window;
}
namespace ProtocolCraft
{
class ServerboundContainerClickPacket;
class Slot;
}
namespace Bilicraft
{
class BilicraftClient;
struct ActionCommand;
// Call only from the cooperative action runner (or a Botcraft behaviour leaf).
// std::exception failures gain source:line context; Botcraft's non-standard
// interruption exceptions are intentionally allowed to unwind unchanged.
Botcraft::Status ExecuteAction(BilicraftClient &client, const ActionCommand &command);
// The runner must call this at each Yield while executing an action. Botcraft
// clears player inputs every physics tick, so a scoped shift needs refreshing.
void MaintainActionInputs(BilicraftClient &client);
// Validated, zero-based protocol indices. GUI rows refer ONLY to the container
// area, never to the player inventory appended below it.
short ActionGuiSlot(Botcraft::InventoryType type, int row, int col);
short ActionBackpackSlot(int row, int col);
short ActionHotbarIndex(int slot);
void ValidateActionPosition(int x, int y, int z);
enum class FrameAttackIntent { None, TakeItem, RemoveFrame };
// Ordinary left click never intentionally attacks a known-empty frame. Creative
// attacks break filled frames too, so item-only clicks must reject that mode.
FrameAttackIntent PlanFrameAttack(bool destroy, bool hasItem, bool creative);
void ValidateFrameAttack(FrameAttackIntent expected, bool destroy, bool hasItem, bool creative);
// Empty-cursor player-inventory number-key SWAP. No local prediction; the
// deliberately stale state id requests authoritative server synchronization.
std::shared_ptr<ProtocolCraft::ServerboundContainerClickPacket> MakeBackpackSwapPacket(int row, int col, int slot);
// Resolve a drop target to 1..9; requested slot 0 uses the current zero-based selection.
// THROW (mode 4) targets a slot directly without changing the selected hotbar.
short ActionDropSlot(int requestedSlot, int selectedHotbarIndex);
std::shared_ptr<ProtocolCraft::ServerboundContainerClickPacket> MakeHotbarDropPacket(int slot, bool all);
ProtocolCraft::Slot RemainingAfterDrop(const ProtocolCraft::Slot &before, bool all);
// Unlike Window::GetSlot, missing/reset inventory data is an error, not an empty slot.
ProtocolCraft::Slot ReadDropSlot(const Botcraft::Window &window, short slot);
} // namespace Bilicraft
+80
View File
@@ -0,0 +1,80 @@
#pragma once
#include <chrono>
#include <cstddef>
#include <filesystem>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Bilicraft
{
enum class ActionKind
{
Goto,
RightClick,
LeftClick,
GuiRightClick,
GuiLeftClick,
SelectHotbar,
SwapBackpack,
Drop,
SendCommand,
SendMessage,
Wait
};
enum class EntityFace
{
Any,
Top,
Bottom,
South,
North,
West,
East
};
struct ActionCommand
{
ActionKind kind;
int x = 0, y = 0, z = 0, row = 0, col = 0, slot = 0;
bool shift = false, destroy = false;
// Drop: slot == 0 means the current main-hand hotbar slot; all drops the stack.
bool all = false;
std::string text, recipient;
std::filesystem::path source;
std::size_t line = 0;
// Wait: exact milliseconds, from zero (yield) through 365 days inclusive.
std::chrono::milliseconds waitDuration{0};
// Click entry: target an item frame; Any searches all six block faces.
bool entity = false;
EntityFace entityFace = EntityFace::Any;
};
struct ActionProgram
{
std::string name;
std::vector<ActionCommand> commands;
};
// Load UTF-8 .act text and expand imports in place. Coordinates/slots are 1-based
// where applicable; block coordinates remain signed integers. Errors throw
// std::runtime_error with source:line context (including import-site context).
// The entry file must have a .act extension. Action/import names omit .act and
// must be simple names resolving to same-directory name.act files whose action
// headers match. Cycles and symlink escapes are rejected. Limits: 32 active
// files, 100000 expanded commands, 4096 file loads, 1 MiB/file and 16 MiB total.
// Wait syntax: wait digits[.digits] [s|ms|min|h|d], default s. The duration
// must be an exact whole number of milliseconds and may not exceed 365 days.
// Clicks optionally accept entry [t|b|s|n|w|e] (or full face names), with
// the face immediately after entry. Existing shift and left-click destroy flags
// may appear before or after entry; omitted entry retains block-click behavior.
ActionProgram LoadActionFile(const std::filesystem::path &path);
// Parse one console game instruction using the .act grammar, without file I/O.
// Blank/comment lines return nullopt. Wait/import require `run file.act` instead.
// CR, LF and NUL are rejected; errors throw with <console>:1 context.
std::optional<ActionCommand> ParseInteractiveCommand(std::string_view text);
} // namespace Bilicraft
+72
View File
@@ -0,0 +1,72 @@
#pragma once
#include "ActionFile.h"
#include <chrono>
#include <cstdint>
#include <map>
#include <optional>
#include <string>
#include <vector>
namespace Bilicraft
{
// Single-threaded cooperative scheduler. Only the owner may execute commands;
// enqueue/submit are safe from that owner's Yield callback, never other threads.
class ActionScheduler
{
public:
using Clock = std::chrono::steady_clock;
using TaskId = std::uint64_t;
enum class State { Ready, Running, Blocked };
struct TaskInfo
{
TaskId id;
std::string name;
State state;
std::size_t nextCommand;
std::size_t commandCount;
Clock::time_point wakeAt;
};
struct Work
{
ActionCommand command;
TaskId taskId; // 0 for an interactive command
bool interactive;
};
TaskId Enqueue(ActionProgram program, Clock::time_point now = Clock::now());
void WakeReady(Clock::time_point now);
void SubmitInteractive(ActionCommand command);
// Call only when no command is outstanding. Wait is handled here, never
// passed to the game executor. Timers don't preempt a running action.
std::optional<Work> Next(Clock::time_point now);
void Finish(bool success);
bool InteractivePending() const;
bool HasWork() const;
std::optional<Clock::time_point> NextWake() const;
std::vector<TaskInfo> Tasks() const;
std::vector<std::string> DrainEvents();
private:
struct Task
{
TaskId id;
ActionProgram program;
std::size_t pc = 0;
State state = State::Ready;
Clock::time_point wakeAt{};
std::uint64_t readyOrder = 0;
};
void RemoveActive(bool success);
std::map<TaskId, Task> tasks;
std::optional<TaskId> active;
std::optional<ActionCommand> interactive;
bool inFlight = false;
bool interactiveInFlight = false;
TaskId nextId = 1;
std::uint64_t nextOrder = 1;
std::size_t storedCommands = 0;
std::vector<std::string> events;
};
} // namespace Bilicraft
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include <span>
#include <string>
#include <string_view>
namespace Bilicraft
{
inline constexpr std::string_view kGameVersion = BILICRAFT_BOT_GAME_VERSION;
inline constexpr std::string_view kDefaultServer = "mc.bilicraft.com:25577";
struct AppConfig
{
std::string server{kDefaultServer};
// Microsoft credential-cache key, NOT an offline player name or password.
std::string account;
std::string actionFile;
bool checkAction = false;
bool help = false;
};
// Arguments exclude argv[0]. Invalid or incomplete options throw invalid_argument.
AppConfig ParseArguments(std::span<const std::string_view> arguments);
std::string Usage();
} // namespace Bilicraft
+39
View File
@@ -0,0 +1,39 @@
#pragma once
#include <atomic>
#include <functional>
#include "botcraft/AI/TemplatedBehaviourClient.hpp"
namespace Bilicraft
{
// CRTP keeps future behaviour-tree leaves typed as BilicraftClient, with access
// to its custom fields as well as Botcraft's world/inventory/physics managers.
class BilicraftClient : public Botcraft::TemplatedBehaviourClient<BilicraftClient>
{
public:
~BilicraftClient() override;
bool WasDisconnected() const;
bool HasEnteredPlay() const;
// Synchronous .act execution: tasks yield to a main-thread cancellation/
// pacing hook instead of starting the upstream behaviour worker. Never use
// this mode concurrently with StartBehaviour/BehaviourStep/SyncAction.
void SetActionYieldHandler(std::function<void()> handler);
void Yield() override;
protected:
using Botcraft::TemplatedBehaviourClient<BilicraftClient>::Handle;
void Handle(ProtocolCraft::ClientboundLoginPacket &packet) override;
void Handle(ProtocolCraft::ClientboundLoginDisconnectPacket &packet) override;
void Handle(ProtocolCraft::ClientboundDisconnectConfigurationPacket &packet) override;
void Handle(ProtocolCraft::ClientboundDisconnectPacket &packet) override;
private:
// Main-thread-only hook; it is never called by network/physics handlers.
std::function<void()> actionYieldHandler;
// Do not use upstream's non-atomic should_be_closed as our cross-thread signal.
std::atomic<bool> disconnected{false};
std::atomic<bool> enteredPlay{false};
};
} // namespace Bilicraft
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include "ActionFile.h"
#include <optional>
#include <string>
#include <string_view>
namespace Bilicraft
{
enum class ConsoleKind { Empty, Action, Run, Tasks, Help, Quit };
struct ConsoleCommand
{
ConsoleKind kind = ConsoleKind::Empty;
std::string path;
std::optional<ActionCommand> action;
};
ConsoleCommand ParseConsoleCommand(std::string_view line);
std::string ConsoleHelp();
} // namespace Bilicraft
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include <memory>
#include <string>
#include "ActionFile.h"
#include "botcraft/Game/Vector3.hpp"
namespace Botcraft
{
class EntityManager;
class ItemFrameEntity;
}
namespace ProtocolCraft
{
class ServerboundInteractPacket;
}
namespace Bilicraft
{
// Protocol 774: the command names the SUPPORT block; the frame's network
// spawn position is an integer attachment cell (support + outward face normal),
// but absolute movement/sync can replace it with the actual frame center.
// Invalid commands throw. Malformed frame positions/directions do not match.
bool MatchesItemFrame(const Botcraft::ItemFrameEntity &frame, const ActionCommand &command);
// Only ordinary/glow item frames qualify. Zero matches returns nullptr;
// multiple matches (including on one explicit face) throw instead of guessing.
// The manager lock is released before this returns; callers must revalidate
// identity/position immediately before sending, particularly after yielding.
std::shared_ptr<Botcraft::ItemFrameEntity> FindItemFrame(Botcraft::EntityManager &manager,
const ActionCommand &command);
// Visual/collision center, NOT the spawn position. Throws for invalid state.
// Suitable for LookAt and conservative eye-to-center reach checks.
Botcraft::Vector3<double> ItemFrameCenter(const Botcraft::ItemFrameEntity &frame);
// Read-only, bounded diagnostic: loaded count and at most eight nearby frames
// with raw position, direction and decoded support. Never selects a fallback.
std::string DescribeItemFrameTargets(Botcraft::EntityManager &manager, const ActionCommand &command);
// Action 0 + main hand for ordinary right-click, Action 1 without a hand for
// attack; never interact-at (Action 2). Secondary is the actual sneaking state.
std::shared_ptr<ProtocolCraft::ServerboundInteractPacket> MakeEntityInteractionPacket(int entityId, bool attack,
bool secondary);
} // namespace Bilicraft
+70
View File
@@ -0,0 +1,70 @@
#pragma once
#include <cstddef>
#include <optional>
#include <string>
#include <vector>
namespace Bilicraft
{
// Pure in-memory, byte-at-a-time terminal editor. No terminal I/O or threads.
// Only complete, valid UTF-8 codepoints are inserted; incomplete codepoints stay
// buffered until complete or interrupted, and malformed input is discarded.
// Cursor() is a byte offset, always on a codepoint boundary. History is local to
// this instance, excludes blank/consecutive duplicate lines, and is never saved.
class LineEditor
{
public:
static constexpr std::size_t MaxLineBytes = 64 * 1024;
static constexpr std::size_t MaxHistoryEntries = 200;
// CR or LF returns the line and resets the editor. One LF immediately after
// CR is swallowed, even across calls. Stop reading as soon as a line returns.
// Ctrl-D on an empty line latches EOF; subsequent Feed calls do nothing.
// Exceeding MaxLineBytes throws std::length_error without changing the line;
// the caller can continue editing (e.g. backspace) and try again.
std::optional<std::string> Feed(char byte);
const std::string &Text() const;
std::size_t Cursor() const;
bool IsEof() const;
private:
enum class EscapeState
{
None,
Start,
Intermediate,
Csi,
Ss3,
String,
StringEscape
};
void FeedEscape(unsigned char byte);
void FinishControlSequence(char finalByte);
void ResetEscape();
void InsertByte(unsigned char byte);
void InsertCodepoint(const std::string &codepoint);
void HistoryUp();
void HistoryDown();
void DeleteAtCursor();
std::size_t PreviousBoundary() const;
std::size_t NextBoundary() const;
std::string Submit();
std::string text;
std::size_t cursor = 0;
bool eof = false;
bool swallowLf = false;
std::vector<std::string> history;
std::size_t historyIndex = 0;
std::string draft;
std::size_t draftCursor = 0;
std::string utf8Pending;
std::size_t utf8Expected = 0;
EscapeState escapeState = EscapeState::None;
std::string escapeParameters;
std::size_t escapeLength = 0;
bool escapeTooLong = false;
};
} // namespace Bilicraft
+40
View File
@@ -0,0 +1,40 @@
#pragma once
#include <memory>
#include <optional>
#include <ostream>
#include <string>
#include <string_view>
namespace Bilicraft
{
// Owns terminal state, never the supplied descriptors. The caller must be the
// sole input reader and keep all descriptors open until destruction. Stop logger
// callbacks before destruction. Control/input methods belong to the main thread;
// WriteLog is safe from other threads. Do not write directly to the terminal
// while split mode is active: use Out(), Err(), or WriteLog().
class TerminalConsole
{
public:
explicit TerminalConsole(int inputFd = 0, int outputFd = 1, int errorFd = 2);
~TerminalConsole() noexcept;
TerminalConsole(const TerminalConsole &) = delete;
TerminalConsole &operator=(const TerminalConsole &) = delete;
// Call after login. Idempotent; unsupported terminals retain plain line
// input (including prompts), with no terminal control sequences generated.
void Start();
bool IsSplit() const;
std::optional<std::string> PollLine();
bool IsEof() const;
void SetInputEnabled(bool enabled);
void Tick();
std::ostream &Out();
std::ostream &Err();
void WriteLog(std::string_view text, bool error = false) noexcept;
private:
struct Impl;
std::unique_ptr<Impl> impl;
};
} // namespace Bilicraft
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include <cstddef>
#include <optional>
#include <string>
namespace Bilicraft
{
// Incremental input with no wait for a user, a writer, or a complete line.
// The caller must be the sole reader of fd (including its duplicated descriptors)
// and must keep it open. This class never closes fd or changes its flags/mode.
// Do not mix it with std::cin/getline: their buffering can read ahead.
//
// POSIX supports canonical terminals, pipes and ordinary files. Windows supports
// redirected pipes and ordinary files; native consoles/other handle types fail
// explicitly rather than falling back to a potentially blocking cooked read.
class TerminalInput
{
public:
static constexpr std::size_t MaxLineBytes = 64 * 1024;
TerminalInput();
explicit TerminalInput(int fd);
TerminalInput(const TerminalInput &) = delete;
TerminalInput &operator=(const TerminalInput &) = delete;
// Consumes at most one line, stopping at its LF without reading the next
// byte. nullopt means not ready, a partial line, or EOF (see IsEof()). Work
// per call is bounded, so long lines may need several calls even from files.
// A final nonempty line without LF is returned once, with IsEof() == true.
// CR immediately before LF is removed; other CR bytes are preserved.
// Up to MaxLineBytes bytes before LF are accepted (including any CR).
// I/O/unsupported errors throw std::runtime_error once; overlong lines throw
// std::length_error once. Both discard the partial line and latch EOF.
std::optional<std::string> PollLine();
bool IsEof() const;
bool IsInteractive() const;
private:
enum class ReadResult
{
NotReady,
Byte,
End
};
ReadResult ReadByte(char &byte);
[[noreturn]] void Fail(const std::string &message);
std::string TakeLine(bool removeCr);
int fd;
bool interactive;
bool eof = false;
std::string partial;
};
} // namespace Bilicraft