ghast v0.5.6

Core concepts

The tick model

Every ghast bot runs on a fixed 50 ms client tick that follows the vanilla client's own tick order. This page explains what happens in a tick, what your Behavior may read and do in it, which packets a bot receives, and what happens when a tick runs late.

One tick, step by step

A session is a tokio task with a timer that fires every 50 ms. It works like the vanilla client:

  1. Inbound packets are applied on arrival. Keep-alives, teleports and window confirms are answered at once, as vanilla does per frame. Before a tick, the loop drains whatever the socket already holds.
  2. Your behaviour runs. Behavior::start on the first tick, then Behavior::tick.
  3. The client's own tick runs. Held-slot sync, key handling (digging, placing, using, attacking with the held buttons), the rotation step toward your aim, the movement step in the vanilla physics, sprint and sneak state, and then exactly one movement packet.

So the server judges a tick's actions against the pose it already has: ctx.sent(). ctx.pose() is the client's pose at the start of the tick.

The behaviour only starts once the player has its first position from the server and its chunk column is loaded. On 26.x the client also waits for the level to load, as vanilla does.

What a behaviour reads and sets

The TickContext is your view of the client during one tick. Reading is free: pose(), sent(), events() (what happened since the previous tick: chat, teleports, death, health, inventory and block updates), world(), entities(), inventory(), health(), target() and more (see World and entities and Inventory).

Two kinds of call change the game. Intents are applied by the client's own tick steps, like a player's keyboard and mouse:

  • set_controls(Controls { .. }): the movement keys. They stay held until you change them.
  • set_aim(yaw, pitch): a rotation target. The client turns toward it in whole mouse counts, at most turn_rate() degrees per tick (14 of yaw and 10.5 of pitch by default), and only on ticks you call it.
  • set_buttons(Buttons { left, right }): held mouse buttons (dig, place, use, attack).
  • set_flying(bool): start or stop flying where the server allows it.

Actions (chat, select_slot, dig, place, attack, inventory clicks, swing, respawn, disconnect) are queued in call order and sent before this tick's movement packet.

A behaviour that walks for 60 ticks, logs block changes meanwhile, and finishes:

use ghast::{Behavior, Controls, Interests, TickContext};

/// Walks forward for 60 ticks, logs block changes, then stands still and finishes.
struct Walk {
    ticks_left: u32,
    watch_blocks: bool,
}

impl Behavior for Walk {
    fn interests(&self) -> Interests {
        // Read every tick: a change rebuilds the packet filter.
        if self.watch_blocks {
            Interests::CHAT | Interests::BLOCK_UPDATES
        } else {
            Interests::CHAT
        }
    }

    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        let ev = ctx.events();
        if ev.teleported {
            println!("the server moved us");
        }
        for (pos, state) in &ev.block_updates {
            println!("block {pos:?} is now state {state}");
        }

        self.ticks_left -= 1;
        if self.ticks_left > 0 {
            // Keys stay held until changed.
            ctx.set_controls(Controls { forward: true, sprint: true, ..Controls::NONE });
        } else {
            // The last tick: release the keys, or they stay held after the behaviour ends.
            ctx.set_controls(Controls::NONE);
            let sent = ctx.sent().pos;
            println!("the server has us at {:.2} {:.2} {:.2}", sent.x, sent.y, sent.z);
            self.watch_blocks = false;
        }
    }

    fn running(&self) -> bool {
        self.ticks_left > 0
    }

    fn stop(&mut self, reason: &str) {
        println!("session over: {reason}");
    }
}

Once running() returns false the behaviour is not ticked again; the player keeps standing and stop still runs when the session ends. Observers (recorders, viewers) implement after_tick, which gets a read-only TickView after every movement step.

Packets a bot does not ask for

The client always receives what its core needs: keep-alives, teleports, health, windows, chunks, block changes and a few more. Everything else (tab list, teams, scoreboards, particles, sounds, entities, ...) is dropped by the frame decoder before it is decoded; with compression on, only the bytes that hold the packet id are inflated. A busy server's tab list and entity movement cost a bot almost nothing unless it asks for them.

A behaviour opts in with Behavior::interests, which returns a set of Interests:

InterestWhat it adds
CHATchat messages in events().chat
ENTITIES, ENTITY_TRACKINGentity tracking (full, or without the metadata store)
PLAYER_LIST, PLAYER_SKINSthe tab list, and skins on top of it
ENTITY_EVENTS, ENTITY_PHYSICSentity events, physics of thrown and dropped things
BLOCK_UPDATESa copy of block changes in events().block_updates
HUD, TEAMS, DIALOGS, RECIPESHUD, teams, 26.x dialogs, 1.16.5 recipes

interests is read every tick and a change rebuilds the filter, so a bot can switch entity tracking on only when it needs it. Without ENTITIES or ENTITY_TRACKING the crosshair sees blocks only and nothing pushes the bot. Behavior::raw_packets names extra packet ids to copy undecoded into events().raw.

When a tick runs late

After a stall the timer skips the missed ticks instead of catching up, because a burst of catch-up movement packets is what anticheat timer checks flag. tick is a plain synchronous function called from the session's task, so a slow tick delays the session; keep blocking work out of it.

If the server goes quiet for 1.5 s (Client::silent_hold), the behaviour is frozen: keys are released, the vanilla movement packet continues, and the behaviour resumes when data arrives. After 30 s without data (Client::read_timeout, vanilla's value) the session fails with ClientError::Timeout.

How this differs from an event-callback library

In an event-callback library such as mineflayer, you register handlers (bot.on('chat', ...)) and call actions whenever a handler runs, so when packets go out depends on when your code happens to run.

In ghast, events are collected and handed to you once per tick, and actions are only taken inside tick. Every action lands in a known place, before the tick's one movement packet, in the order the vanilla client sends it. The engine has no I/O and no clock, so the same inputs give the same packets; that is what lets ghast replay oracle recordings packet for packet.

The cost is that a multi-step job becomes an explicit state machine. The ext feature gives it back its straight-line shape with async helpers that still run inside the tick: see Async helpers (ext).