ghast-client 0.5.5

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
//! 1.8.9: vehicles and mounts the player rides (boats, minecarts, living mounts): the watched
//! mounts, boarding, their packets and the ride's tick.

use super::*;

impl Sim18 {
    /// The server's packets about the horses and pigs the client watches (not the one we ride):
    /// a mob spawn of a mount type starts watching it (spawn position, angle bytes, entity data
    /// index 16); moves, looks, head yaw and entity data follow; a removal ends it.
    #[cold]
    #[inline(never)]
    pub(super) fn watched_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::defs::p47::types::EntityMetadataValue as V;
        use ghast_protocol::v1_8::play::clientbound as cb;
        let flags =
            |m: &mut ghast_physics::v1_8::Mount,
             list: &[ghast_protocol::defs::p47::types::EntityMetadataEntry]| {
                for e in list {
                    match (e.key, &e.value) {
                        (16, V::Int(f)) => m.set_flags(*f),
                        (16, V::Byte(b)) => m.set_flags(i32::from(*b)),
                        _ => {}
                    }
                }
            };
        if raw.id == cb::id::ENTITY_DESTROY {
            let p: cb::EntityDestroy = raw.decode_as()?;
            self.watched.retain(|w| !p.entity_ids.contains(&w.0));
            return Ok(());
        }
        if raw.id == cb::id::SPAWN_ENTITY_LIVING {
            let p: cb::SpawnEntityLiving = raw.decode_as()?;
            self.watched.retain(|w| w.0 != p.entity_id);
            if let Some(kind) = ghast_physics::v1_8::MountKind::of_mob_type(p.r#type) {
                let mut m = ghast_physics::v1_8::Mount::spawned(
                    kind,
                    [p.x, p.y, p.z],
                    p.yaw,
                    p.pitch,
                    p.head_pitch,
                );
                flags(&mut m, &p.metadata);
                self.watched.push((p.entity_id, m));
            }
            return Ok(());
        }
        let id = ghast_protocol::Reader::new(&raw.body).read_varint()?;
        if self.ride.as_ref().is_some_and(|r| r.id == id) {
            return Ok(());
        }
        let Some((_, m)) = self.watched.iter_mut().find(|w| w.0 == id) else {
            return Ok(());
        };
        match raw.id {
            cb::id::ENTITY_TELEPORT => {
                let p: cb::EntityTeleport = raw.decode_as()?;
                m.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch, p.on_ground);
            }
            cb::id::REL_ENTITY_MOVE => {
                let p: cb::RelEntityMove = raw.decode_as()?;
                m.server_update([p.d_x, p.d_y, p.d_z], None, p.on_ground);
            }
            cb::id::ENTITY_MOVE_LOOK => {
                let p: cb::EntityMoveLook = raw.decode_as()?;
                m.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)), p.on_ground);
            }
            cb::id::ENTITY_LOOK => {
                let p: cb::EntityLook = raw.decode_as()?;
                m.server_update([0; 3], Some((p.yaw, p.pitch)), p.on_ground);
            }
            cb::id::ENTITY => m.server_update([0; 3], None, false),
            cb::id::ENTITY_HEAD_ROTATION => {
                let p: cb::EntityHeadRotation = raw.decode_as()?;
                m.server_head_yaw(p.head_yaw);
            }
            cb::id::ENTITY_METADATA => {
                let p: cb::EntityMetadata = raw.decode_as()?;
                flags(m, &p.metadata);
            }
            _ => {}
        }
        Ok(())
    }

    /// The boat packets (with entity tracking): `attach_entity` naming us (boarding a tracked
    /// boat, or leaving it with vehicle -1), and while riding the server's teleport, relative
    /// moves, looks and velocity of that boat and its destruction (vanilla's
    /// `World.removeEntity` takes the rider off).
    #[cold]
    #[inline(never)]
    pub(super) fn vehicle_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_8::play::clientbound as cb;
        let Some(t) = &self.entities else {
            return Ok(());
        };
        if raw.id == cb::id::ATTACH_ENTITY {
            let p: cb::AttachEntity = raw.decode_as()?;
            if p.leash {
                return Ok(());
            }
            if t.self_id() != Some(p.entity_id) {
                // Another entity boards a boat: vanilla sets its empty flag again.
                self.boarded.retain(|&b| b != p.vehicle_id);
                return Ok(());
            }
            if p.vehicle_id == -1 {
                if let Some(r) = self.ride.take() {
                    log::debug!("left boat {}", r.id);
                    // A living mount: the client watches it again from where it is.
                    if let Seat18::Mount(m) = r.seat {
                        self.watched.retain(|w| w.0 != r.id);
                        self.watched.push((r.id, m));
                    }
                }
                return Ok(());
            }
            // onEntityAttach: a boat the client knows starts its physics; a minecart follows
            // the server. The client's interpolation of either at rest ends at the server's
            // last position.
            let shadow = self
                .watched
                .iter()
                .position(|w| w.0 == p.vehicle_id)
                .map(|k| self.watched.swap_remove(k).1);
            let seat = t.get(p.vehicle_id).and_then(|e| {
                let fixed = e.position().map(|v| (v * 32.0).round() as i32);
                let yaw = (e.yaw() * 256.0 / 360.0).round() as i32 as i8;
                let pitch = (e.pitch() * 256.0 / 360.0).round() as i32 as i8;
                match e.entity_type() {
                    ghast_entity::EntityType::LegacyObject(1) => Some(Seat18::Boat(
                        ghast_physics::v1_8::Boat::spawned(fixed, yaw, pitch),
                    )),
                    ghast_entity::EntityType::LegacyObject(10) => Some(Seat18::Cart(
                        ghast_physics::v1_8::Minecart::spawned(fixed, yaw, pitch),
                    )),
                    ghast_entity::EntityType::LegacyMob(id) => {
                        ghast_physics::v1_8::MountKind::of_mob_type(id).map(|k| match shadow {
                            // What the client held while it watched the mob: its
                            // interpolation, body clock, rearing animation and entity data.
                            Some(m) if m.kind == k => Seat18::Mount(m),
                            _ => mount_of(e, k),
                        })
                    }
                    _ => None,
                }
            });
            if matches!(seat, Some(Seat18::Boat(_))) && !self.boarded.contains(&p.vehicle_id) {
                // Vanilla clears the boat's empty flag ([`Sim18::bounds_movers`]).
                self.boarded.push(p.vehicle_id);
            }
            match seat {
                Some(seat) => {
                    log::debug!("riding {}", p.vehicle_id);
                    self.ride = Some(Box::new(Ride18 {
                        id: p.vehicle_id,
                        seat,
                    }));
                }
                None => {
                    self.ride = None;
                    log::debug!(
                        "riding {} (not simulated: not a boat, minecart, horse or pig)",
                        p.vehicle_id
                    );
                }
            }
            return Ok(());
        }
        let Some(r) = self.ride.as_deref_mut() else {
            return Ok(());
        };
        if let Seat18::Mount(m) = &mut r.seat {
            let id = r.id;
            match raw.id {
                cb::id::ENTITY_TELEPORT => {
                    let p: cb::EntityTeleport = raw.decode_as()?;
                    if p.entity_id == id {
                        m.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch, p.on_ground);
                    }
                }
                cb::id::REL_ENTITY_MOVE => {
                    let p: cb::RelEntityMove = raw.decode_as()?;
                    if p.entity_id == id {
                        m.server_update([p.d_x, p.d_y, p.d_z], None, p.on_ground);
                    }
                }
                cb::id::ENTITY_MOVE_LOOK => {
                    let p: cb::EntityMoveLook = raw.decode_as()?;
                    if p.entity_id == id {
                        m.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)), p.on_ground);
                    }
                }
                cb::id::ENTITY_LOOK => {
                    let p: cb::EntityLook = raw.decode_as()?;
                    if p.entity_id == id {
                        m.server_update([0; 3], Some((p.yaw, p.pitch)), p.on_ground);
                    }
                }
                cb::id::ENTITY => {
                    // The bare entity packet: no move, its ground flag is false.
                    let p: cb::Entity = raw.decode_as()?;
                    if p.entity_id == id {
                        m.server_update([0; 3], None, false);
                    }
                }
                cb::id::ENTITY_HEAD_ROTATION => {
                    let p: cb::EntityHeadRotation = raw.decode_as()?;
                    if p.entity_id == id {
                        m.server_head_yaw(p.head_yaw);
                    }
                }
                cb::id::ENTITY_DESTROY => {
                    let p: cb::EntityDestroy = raw.decode_as()?;
                    if p.entity_ids.contains(&id) {
                        log::debug!("mount {id} destroyed");
                        self.ride = None;
                    }
                }
                // A living mob's client motion does not move it.
                _ => {}
            }
            return Ok(());
        }
        if let Seat18::Cart(c) = &mut r.seat {
            let id = r.id;
            match raw.id {
                cb::id::ENTITY_TELEPORT => {
                    let p: cb::EntityTeleport = raw.decode_as()?;
                    if p.entity_id == id {
                        c.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch);
                    }
                }
                cb::id::REL_ENTITY_MOVE => {
                    let p: cb::RelEntityMove = raw.decode_as()?;
                    if p.entity_id == id {
                        c.server_update([p.d_x, p.d_y, p.d_z], None);
                    }
                }
                cb::id::ENTITY_MOVE_LOOK => {
                    let p: cb::EntityMoveLook = raw.decode_as()?;
                    if p.entity_id == id {
                        c.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)));
                    }
                }
                cb::id::ENTITY_LOOK => {
                    let p: cb::EntityLook = raw.decode_as()?;
                    if p.entity_id == id {
                        c.server_update([0; 3], Some((p.yaw, p.pitch)));
                    }
                }
                cb::id::ENTITY => {
                    let p: cb::Entity = raw.decode_as()?;
                    if p.entity_id == id {
                        c.server_update([0; 3], None);
                    }
                }
                cb::id::ENTITY_DESTROY => {
                    let p: cb::EntityDestroy = raw.decode_as()?;
                    if p.entity_ids.contains(&id) {
                        log::debug!("minecart {id} destroyed");
                        self.ride = None;
                    }
                }
                // A minecart's client motion does not move it.
                _ => {}
            }
            return Ok(());
        }
        let Seat18::Boat(b) = &mut r.seat else {
            return Ok(());
        };
        match raw.id {
            cb::id::ENTITY_TELEPORT => {
                let p: cb::EntityTeleport = raw.decode_as()?;
                if p.entity_id == r.id {
                    b.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch, p.on_ground);
                }
            }
            cb::id::REL_ENTITY_MOVE => {
                let p: cb::RelEntityMove = raw.decode_as()?;
                if p.entity_id == r.id {
                    b.server_move([p.d_x, p.d_y, p.d_z], p.on_ground);
                }
            }
            cb::id::ENTITY_MOVE_LOOK => {
                let p: cb::EntityMoveLook = raw.decode_as()?;
                if p.entity_id == r.id {
                    b.server_move([p.d_x, p.d_y, p.d_z], p.on_ground);
                }
            }
            cb::id::ENTITY_LOOK => {
                let p: cb::EntityLook = raw.decode_as()?;
                if p.entity_id == r.id {
                    b.server_move([0; 3], p.on_ground);
                }
            }
            cb::id::ENTITY => {
                // The bare entity packet: no move, its ground flag is false.
                let p: cb::Entity = raw.decode_as()?;
                if p.entity_id == r.id {
                    b.server_move([0; 3], false);
                }
            }
            cb::id::ENTITY_VELOCITY => {
                let p: cb::EntityVelocity = raw.decode_as()?;
                if p.entity_id == r.id {
                    let v = p.velocity;
                    let c = |x: i16| f64::from(x) / 8000.0;
                    b.server_velocity([c(v.x), c(v.y), c(v.z)]);
                }
            }
            cb::id::ENTITY_DESTROY => {
                let p: cb::EntityDestroy = raw.decode_as()?;
                if p.entity_ids.contains(&r.id) {
                    log::debug!("boat {} destroyed", r.id);
                    self.ride = None;
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// A tick in the boat the 1.8 client simulates (`ghast_physics::v1_8::tick_boat`).
    #[cold]
    #[inline(never)]
    pub(super) fn step_ride(&mut self, input: &ghast_physics::TickInput) {
        // The ride's ticks follow neither the ray nor the queries that set shared bounds.
        self.pistons.forget_shared_bounds();
        // The ride's ticks do not trace the crosshair ray.
        if self.head_watch && self.heads_near() {
            self.ray_missed = true;
        }
        // Other entities' queries and rays meet the loaded heads too.
        if self.head_watch && self.bounds_movers() {
            self.pistons.forget_head_bounds(0x3f);
        }
        let Some(r) = self.ride.as_deref_mut() else {
            return;
        };
        let id = r.id;
        let boat = match &mut r.seat {
            Seat18::Boat(b) => b,
            Seat18::Mount(m) => {
                // The living mount the server moves (`ghast_physics::v1_8::tick_mount`).
                ghast_physics::v1_8::tick_mount(
                    &mut self.player,
                    m,
                    &mut self.jump_bar,
                    input,
                    &self.world,
                    &ghast_physics::v1_8::Options::default(),
                    &mut self.packets,
                );
                return;
            }
            Seat18::Cart(c) => {
                self.jump_bar.idle();
                // The minecart the server moves (`ghast_physics::v1_8::tick_minecart`).
                ghast_physics::v1_8::tick_minecart(
                    &mut self.player,
                    c,
                    input,
                    &self.world,
                    &ghast_physics::v1_8::Options::default(),
                    &mut self.packets,
                );
                return;
            }
        };
        self.jump_bar.idle();
        #[cfg(test)]
        let still = ghast_physics::v1_8::tick_boat_with(
            &mut self.player,
            boat,
            input,
            &self.world,
            &ghast_physics::v1_8::Options::default(),
            &TableTrig(&self.trig),
            &mut self.packets,
        );
        #[cfg(not(test))]
        let still = ghast_physics::v1_8::tick_boat(
            &mut self.player,
            boat,
            input,
            &self.world,
            &ghast_physics::v1_8::Options::default(),
            &mut self.packets,
        );
        for &[x, y, z] in boat.broken_blocks() {
            self.world
                .set_block_state(x, y, z, ghast_data::v1_8::BlockState::AIR);
        }
        if !still {
            log::debug!("boat {id} fell out of the world");
            self.ride = None;
        }
    }
}