ghast-client 0.5.3

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
//! The crosshair: which entities the pick can hit (`Entity.collides`, the 1.8 – 1.16.5
//! targeting margin), the per-tick list of pickable entities in vanilla's search order, the
//! pick's rotation and eye height, and the post-look check that holds a turn which would take
//! the crosshair off a block dug or placed this tick.

use super::*;

/// Whether rays hit the entity (`Entity.collides`): living entities, players,
/// paintings and the solid objects (boats, minecarts, TNT, falling blocks, item frames, armor
/// stands, leash knots, end crystals); not items, orbs, projectiles.
fn collidable(e: &ghast_entity::Entity) -> bool {
    use ghast_entity::{EntityClass, EntityType};
    match e.class() {
        EntityClass::Player | EntityClass::Mob | EntityClass::Painting => true,
        EntityClass::Item | EntityClass::ExperienceOrb => false,
        EntityClass::Object => match e.entity_type() {
            // 63: the large fireball (`EntityFireball.canBeCollidedWith`; small fireballs and
            // wither skulls are not).
            EntityType::LegacyObject(t) => {
                matches!(t, 1 | 10 | 50 | 51 | 63 | 70 | 71 | 77 | 78)
            }
            #[cfg(feature = "v1_16_5")]
            EntityType::Registry(_) => {
                ghast_entity::v1_16_5::info(e.entity_type()).is_some_and(|i| {
                    matches!(
                        i.name,
                        "boat"
                            | "fireball"
                            | "tnt"
                            | "end_crystal"
                            | "falling_block"
                            | "item_frame"
                            | "leash_knot"
                            | "armor_stand"
                            | "shulker_bullet"
                    ) || i.name.contains("minecart")
                })
            }
            _ => false,
        },
        // A class added for a newer version: not targetable until it is classified here.
        _ => false,
    }
}

/// 1.8 – 1.16.5: whether the crosshair pick can hit `e` (rays hit it, not a spectator) and its
/// targeting margin from the type's size table.
pub(crate) fn legacy_pick_margin(
    ents: &ghast_entity::Entities,
    e: &ghast_entity::Entity,
) -> Option<f32> {
    let spectator = e.is_player()
        && ents
            .player_info(&e.uuid())
            .is_some_and(|p| p.game_mode == 3);
    (collidable(e) && !spectator).then(|| e.targeting_margin())
}

/// The pickable entities near the eyes as the oracle-proven crosshair pick takes them, with
/// each one's id and position alongside (empty without an entity tracker).
#[derive(Debug, Default)]
pub(super) struct PickList {
    pub(super) entities: Vec<ghast_physics::pick::PickEntity>,
    pub(super) ids: Vec<(i32, Vec3)>,
    /// 1.8 / 1.12: each entry's `Entity::search_order` (the pick visits them in that order).
    pub(super) order: Vec<(i32, i32, i32, u32)>,
}

impl PickList {
    /// Fills the list: tracked entities within 16 blocks of `eyes` (vanilla's search box only
    /// drops entities the ray cannot hit, so this radius loses none) that the version's pick can
    /// hit ([`Sim::pick_margin`]), not ourselves.
    pub(super) fn fill(&mut self, w: &(impl Sim + ?Sized), caps: &Capabilities, eyes: Vec3) {
        self.entities.clear();
        self.ids.clear();
        self.order.clear();
        if let Some(ents) = w.entities() {
            self.fill_from(w, ents, caps, eyes);
        }
    }

    #[inline(never)]
    fn fill_from(
        &mut self,
        w: &(impl Sim + ?Sized),
        ents: &ghast_entity::Entities,
        caps: &Capabilities,
        eyes: Vec3,
    ) {
        use ghast_entity::Entity;
        let me = ents.self_id();
        let root = |mut id: i32| {
            for _ in 0..16 {
                match ents.get(id).and_then(Entity::vehicle) {
                    Some(v) => id = v,
                    None => break,
                }
            }
            id
        };
        let riding = ents.me().and_then(Entity::vehicle);
        let my_root = me.map(root);
        for e in ents.iter() {
            // The drawn position and box: what vanilla's pick tests (interpolated with the
            // tracker's client view, else the server position).
            let p = e.drawn_position();
            let d = [p[0] - eyes.x, p[1] - eyes.y, p[2] - eyes.z];
            if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 16.0 * 16.0 {
                continue;
            }
            let Some(pick_radius) = w.pick_margin(e) else {
                continue;
            };
            let Some(b) = e.drawn_bounding_box() else {
                continue;
            };
            // 1.8: the vehicle we sit on; 1.9+: anything with our root vehicle.
            let same_root_vehicle = if caps.entity_pick_root_vehicle {
                my_root.is_some_and(|r| root(e.id()) == r)
            } else {
                riding == Some(e.id())
            };
            self.entities.push(ghast_physics::pick::PickEntity {
                bb: ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]),
                pick_radius,
                same_root_vehicle,
            });
            self.ids.push((e.id(), Vec3::new(p[0], p[1], p[2])));
            if let Some(o) = w.search_order(e) {
                self.order.push(o);
            }
        }
        // The vanilla search order (chunks, sections, list order), not the store's: an eye
        // inside one box and a ray through another pick by it.
        if self.entities.len() > 1 && self.order.len() == self.entities.len() {
            self.sort();
        }
    }

    #[cold]
    #[inline(never)]
    fn sort(&mut self) {
        let mut idx: Vec<usize> = (0..self.entities.len()).collect();
        idx.sort_unstable_by_key(|&i| self.order[i]);
        self.entities = idx.iter().map(|&i| self.entities[i]).collect();
        self.ids = idx.iter().map(|&i| self.ids[i]).collect();
    }

    /// The pick result as the hands take it: the block (none when an entity is in front or
    /// beyond the 3-block limit) and the entity.
    pub(super) fn split(
        &self,
        t: Crosshair,
        eyes: Vec3,
    ) -> (Option<BlockHit>, Option<hands::EntityHit>) {
        match t {
            Crosshair::Block(b) => (b, None),
            Crosshair::Entity { index, hit } => {
                let (id, entity_pos) = self.ids[index];
                let d = [hit.x - eyes.x, hit.y - eyes.y, hit.z - eyes.z];
                let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
                (
                    None,
                    Some(hands::EntityHit {
                        id,
                        hit,
                        entity_pos,
                        distance,
                        interact: [(hands::Interact::NotHandled, hands::InteractEffect::None); 2],
                    }),
                )
            }
        }
    }
}

/// The player's box at `pos` for the pick's entity search (standing 0.6 x 1.8: the search
/// box only filters out entities the ray cannot reach, so the pose's exact box is not needed).
pub(super) fn pick_box(pos: Vec3) -> ghast_physics::math::Aabb {
    let h = f64::from(0.6f32 / 2.0);
    ghast_physics::math::Aabb::new(
        pos.x - h,
        pos.y,
        pos.z - h,
        pos.x + h,
        pos.y + f64::from(1.8f32),
        pos.z + h,
    )
}

/// Whether the look `yaw`/`pitch` still points at every block dug or placed this tick (its
/// full cube, from the sent and the current feet, standing or sneaking eyes, with the old or the
/// new yaw) — the post-look check that keeps Grim's RotationPlace check satisfied — and is the
/// current look when the behaviour attacked or interacted with an entity this tick.
/// The scan for this tick's actions is inline (most ticks have none), the check itself out of
/// line ([`held_look_ok`]).
#[inline]
pub(super) fn post_look_ok(c: &Core, world: &(impl Sim + ?Sized), yaw: f32, pitch: f32) -> bool {
    // Most ticks have no action: nothing to hold for.
    let (mut action, mut use_item) = (false, false);
    for o in &c.out {
        match o {
            // An attack or interact: the movement packet after it carries the pick's look.
            Outbound::UseEntity { .. } => return (yaw, pitch) == (c.pose.yaw, c.pose.pitch),
            Outbound::Dig {
                status: crate::common::DigStatus::Start | crate::common::DigStatus::Finish,
                ..
            }
            | Outbound::Place { .. }
            | Outbound::PlaceInside { .. } => action = true,
            Outbound::UseItem { .. } => use_item = true,
            _ => {}
        }
    }
    if !action && !use_item {
        return true;
    }
    held_look_ok(c, world, yaw, pitch, use_item)
}

/// [`post_look_ok`] on a tick with a dig, a place or an item use.
#[inline(never)]
fn held_look_ok(
    c: &Core,
    world: &(impl Sim + ?Sized),
    yaw: f32,
    pitch: f32,
    use_item: bool,
) -> bool {
    let looks = [
        hands::look_vector(c.pose.yaw, pitch),
        hands::look_vector(yaw, pitch),
    ];
    let heights = [c.opts.caps.eye_height, c.opts.caps.sneak_eye_height];
    // A plain item use (no block) must not pick a block with the new look either: Grim
    // re-checks it like a place.
    if use_item && (yaw, pitch) != (c.pose.yaw, c.pose.pitch) {
        let rotations = [(c.pose.yaw, pitch), (yaw, pitch)];
        let picks = [c.sent.pos, c.pose.pos].iter().any(|o| {
            heights.iter().any(|h| {
                let eyes = Vec3::new(o.x, o.y + *h, o.z);
                rotations.iter().zip(&looks).any(|(r, l)| {
                    let t = world.crosshair_target(&PickQuery {
                        eyes,
                        rotation: *r,
                        look: *l,
                        held: None,
                        now: false,
                        creative: c.game_mode == GameMode::Creative,
                        player_bb: pick_box(*o),
                        entities: &[],
                    });
                    matches!(t, Crosshair::Block(Some(_)))
                })
            })
        });
        if picks {
            return false;
        }
    }
    c.out
        .iter()
        .filter_map(|o| match o {
            Outbound::Dig {
                status: crate::common::DigStatus::Start | crate::common::DigStatus::Finish,
                pos,
                ..
            }
            | Outbound::Place { pos, .. }
            | Outbound::PlaceInside { pos, .. } => Some(*pos),
            _ => None,
        })
        .all(|t| {
            [c.sent.pos, c.pose.pos].iter().all(|o| {
                heights.iter().any(|h| {
                    let eyes = Vec3::new(o.x, o.y + *h, o.z);
                    looks
                        .iter()
                        .any(|l| hands::ray_hits_cube(eyes, *l, t, ACTION_LOOK_REACH))
                })
            })
        })
}

/// The rotation of the key handling's crosshair pick: this tick's look, on 1.8 with the head
/// yaw of the last movement step ([`Capabilities::pick_head_yaw`]).
#[inline]
pub(super) fn pick_rotation(c: &Core) -> (f32, f32) {
    match c.head_yaw {
        Some(y) if c.opts.caps.pick_head_yaw => (y, c.pose.pitch),
        _ => (c.pose.yaw, c.pose.pitch),
    }
}

/// The eye height of the crosshair pick: the pose's (1.12: gliding 0.4; 1.16.5: swimming,
/// gliding or a riptide spin 0.4, crouching 1.27) when the version's sim knows it, else the
/// standing / sneaking height.
#[inline]
pub(super) fn pick_eye_height(
    sim: &(impl Sim + ?Sized),
    caps: &Capabilities,
    sneaking: bool,
) -> f64 {
    sim.eye_height().unwrap_or(if sneaking {
        caps.sneak_eye_height
    } else {
        caps.eye_height
    })
}

/// [`pick_eye_height`] of a player known to be awake ([`Sim::awake_eye_height`]): the tick's
/// key handling outside [`super::Core::rare`].
#[inline]
pub(super) fn awake_eye_height(
    sim: &(impl Sim + ?Sized),
    caps: &Capabilities,
    sneaking: bool,
) -> f64 {
    sim.awake_eye_height().unwrap_or(if sneaking {
        caps.sneak_eye_height
    } else {
        caps.eye_height
    })
}

/// Reach of the post-look check (6 blocks).
pub(super) const ACTION_LOOK_REACH: f64 = 6.0;