ghast-client 0.5.6

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
//! Modern versions: the movement recording (setup, vehicle packets, riding ticks, hands) and
//! the hands that steer a mount.

use super::*;

impl ModernSim {
    /// [`Sim::hand_items`] after the item ids in the hands changed (out of the plain tick).
    #[cold]
    #[inline(never)]
    pub(super) fn hands_changed(&mut self, hands: [Option<i32>; 2]) {
        self.own.hands = hands;
        if self.rec.is_some() {
            self.record_hands();
        }
        let [main, off] = hands;
        // Player.isHolding of the sticks a pig / strider follows.
        static STICKS: std::sync::OnceLock<[Option<i32>; 2]> = std::sync::OnceLock::new();
        let [carrot, fungus] = *STICKS.get_or_init(|| {
            ["carrot_on_a_stick", "warped_fungus_on_a_stick"]
                .map(|n| super::data::Item::from_name(n).map(|i| i32::from(i.id())))
        });
        let holds = |s: Option<i32>| s.is_some() && (main == s || off == s);
        let sticks = (holds(carrot), holds(fungus));
        if sticks == self.own.sticks {
            return;
        }
        self.own.sticks = sticks;
        if let Some(Riding::Mount { mount, .. }) = &mut self.riding {
            mount.set_rider_sticks(sticks.0, sticks.1);
        }
    }
}

impl ModernSim {
    /// Recording: a clientbound entity packet of a vehicle (a mount or boat whose spawn the
    /// recording has) as an `entity_packet` event, with our entity id and the oracle's (1)
    /// swapped; `move_vehicle` while riding.
    #[cold]
    #[inline(never)]
    pub(super) fn record_vehicle_packet(&mut self, raw: &RawPacket) {
        use super::proto::play::clientbound as cb;
        let Some(r) = self.rec.as_deref_mut() else {
            return;
        };
        let name = match raw.id {
            cb::id::SPAWN_ENTITY => "add_entity",
            cb::id::ENTITY_VELOCITY => "set_entity_motion",
            cb::id::REL_ENTITY_MOVE => "move_entity_pos",
            cb::id::ENTITY_MOVE_LOOK => "move_entity_pos_rot",
            cb::id::ENTITY_LOOK => "move_entity_rot",
            cb::id::SYNC_ENTITY_POSITION => "entity_position_sync",
            cb::id::ENTITY_TELEPORT => "teleport_entity",
            cb::id::ENTITY_HEAD_ROTATION => "rotate_head",
            cb::id::ENTITY_METADATA => "set_entity_data",
            cb::id::ENTITY_EQUIPMENT => "set_equipment",
            cb::id::ENTITY_UPDATE_ATTRIBUTES => "update_attributes",
            cb::id::ENTITY_DESTROY => "remove_entities",
            cb::id::SET_PASSENGERS => "set_passengers",
            cb::id::VEHICLE_MOVE => "move_vehicle",
            cb::id::UPDATE_TIME => {
                if let Ok(p) = raw.decode_as::<cb::UpdateTime>() {
                    r.game_time(p.age);
                }
                return;
            }
            _ => return,
        };
        let own = self.own.id;
        let swap = |id: i32| match id {
            _ if id == own => 1,
            1 => own,
            _ => id,
        };
        let mut rd = ghast_protocol::Reader::new(&raw.body);
        let mut out = bytes::BytesMut::new();
        use ghast_protocol::codec::McWrite as _;
        match raw.id {
            cb::id::VEHICLE_MOVE => {
                if self.riding.is_none() {
                    return;
                }
                r.entity_packet(name, &raw.body);
                return;
            }
            cb::id::ENTITY_DESTROY | cb::id::SET_PASSENGERS => {
                // A vehicle id first (set_passengers), then a varint list of ids.
                let mut ids = Vec::new();
                let head = if raw.id == cb::id::SET_PASSENGERS {
                    let Ok(v) = rd.read_varint() else { return };
                    Some(v)
                } else {
                    None
                };
                let Ok(n) = rd.read_varint() else { return };
                for _ in 0..n.clamp(0, 1024) {
                    let Ok(id) = rd.read_varint() else { return };
                    ids.push(id);
                }
                let known = match head {
                    Some(v) => r.vehicles.contains(&v),
                    None => ids.iter().any(|i| r.vehicles.contains(i)),
                };
                if !known {
                    return;
                }
                if head.is_none() {
                    r.vehicles.retain(|v| !ids.contains(v));
                }
                if let Some(v) = head {
                    out.put_varint(swap(v));
                }
                out.put_varint(n);
                for id in ids {
                    out.put_varint(swap(id));
                }
            }
            _ => {
                let Ok(id) = rd.read_varint() else { return };
                let rest = &raw.body[raw.body.len() - rd.remaining()..];
                if raw.id == cb::id::SPAWN_ENTITY {
                    // A vehicle type (uuid, then the type).
                    let rest_bytes = raw.body.slice(raw.body.len() - rest.len()..);
                    let mut t = ghast_protocol::Reader::new(&rest_bytes);
                    let ty = t.skip(16).ok().and_then(|()| t.read_varint().ok());
                    let vehicle = ty
                        .and_then(|t| u16::try_from(t).ok())
                        .and_then(super::data::entity_type)
                        .and_then(|t| vehicle_kind(t.name))
                        .is_some_and(|k| matches!(k, VehicleKind::Boat(_) | VehicleKind::Mount(_)));
                    if !vehicle {
                        return;
                    }
                    if !r.vehicles.contains(&id) {
                        r.vehicles.push(id);
                    }
                } else if !r.vehicles.contains(&id) {
                    return;
                }
                out.put_varint(swap(id));
                out.extend_from_slice(rest);
            }
        }
        r.entity_packet(name, &out);
        if raw.id == cb::id::SPAWN_ENTITY {
            self.record_hands();
        }
    }

    /// Recording: a tick riding a mount or boat (representable when the recording has the
    /// vehicle's spawn and packets).
    #[cold]
    #[inline(never)]
    pub(super) fn record_riding_tick(&mut self, input: &ghast_physics::TickInput) {
        let id = self.riding.as_ref().map(Riding::id);
        let known = self
            .rec
            .as_deref()
            .is_some_and(|r| id.is_some_and(|i| r.vehicles.contains(&i)));
        let note =
            (!known).then_some("riding a vehicle spawned before the recording: not representable");
        self.record_tick(input, note);
    }

    /// Recording: the items in the hands (what steers a pig or strider).
    #[cold]
    #[inline(never)]
    fn record_hands(&mut self) {
        let Some(r) = self.rec.as_deref_mut() else {
            return;
        };
        let name = |id: Option<i32>| {
            id.and_then(|i| u16::try_from(i).ok())
                .and_then(super::data::Item::from_id)
                .map(super::data::Item::name)
        };
        r.hands(name(self.own.hands[0]), name(self.own.hands[1]));
    }

    /// Recording: the setup at the first movement step, then the columns around the player.
    #[cold]
    pub(super) fn record_start(&mut self) {
        let Some(r) = self.rec.as_deref_mut() else {
            return;
        };
        if !r.started() {
            r.start_modern(&self.player, super::GAME.name(), |id| {
                super::data::BlockState::from_id(u16::try_from(id).ok()?).map(|s| s.to_string())
            });
        }
        let w = &self.world;
        r.observe(self.player.pos, |x, y, z| {
            w.is_column_loaded(x >> 4, z >> 4)
                .then(|| w.block_state(x, y, z).map_or(0, |s| u32::from(s.id())))
        });
    }

    /// Recording: this movement step's input and ghast's result.
    #[cold]
    pub(super) fn record_tick(
        &mut self,
        input: &ghast_physics::TickInput,
        note: Option<&'static str>,
    ) {
        let Some(r) = self.rec.as_deref_mut() else {
            return;
        };
        if let Some(n) = note {
            r.note_once(n);
        }
        r.tick(
            input,
            &crate::record::state_modern(&self.player),
            &self.packets,
        );
    }
}