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 client's own block predictions — level facts, verified block updates,
//! the server's acknowledgements and the plain placements known exactly.

use super::*;

impl ModernSim {
    /// The level facts movement reads, from the world's dimension.
    pub(super) fn sync_level(&mut self) {
        if let Some(d) = self.world.dimension() {
            self.player.level = modern::LevelInfo {
                min_y: d.kind.min_y,
                height: d.kind.height,
                fast_lava: d.kind.fast_lava,
            };
        }
    }

    pub(super) fn state(&self, x: i32, y: i32, z: i32) -> Option<BlockState> {
        self.world.block_state(x, y, z)
    }

    /// `block_update` / `section_blocks_update` while predictions wait
    /// (`ClientLevel.setServerVerifiedBlockState`): a predicted position only remembers the
    /// server's state; the others change at once. The block-update buffer gets every change
    /// the server sent.
    #[cold]
    #[inline(never)]
    pub(super) fn verified_block_updates(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use super::proto::play::clientbound as cb;
        if raw.id == cb::id::BLOCK_CHANGE {
            let p: cb::BlockChange = raw.decode_as()?;
            self.updates.push(p.location, p.r#type as u32);
            let s = state_from_wire(i64::from(p.r#type));
            if self.predictions.update(p.location, s) {
                log::debug!(
                    "block update {s} for predicted {:?} waits for the ack",
                    p.location
                );
            } else {
                self.world.apply_block_change(&p);
            }
            return Ok(());
        }
        let mut p: cb::MultiBlockChange = raw.decode_as()?;
        let (cx, cy, cz) = (
            p.chunk_coordinates.x,
            p.chunk_coordinates.y,
            p.chunk_coordinates.z,
        );
        let sy = (cy << 12) >> 12;
        let (updates, predictions) = (&mut self.updates, &mut self.predictions);
        p.records.retain(|&r| {
            let local = (r & 0xFFF) as i32;
            let pos = BlockPos::new(
                cx * 16 + ((local >> 8) & 15),
                sy.wrapping_mul(16).wrapping_add(local & 15),
                cz * 16 + ((local >> 4) & 15),
            );
            let state = ((r as u64) >> 12) as u32;
            updates.push(pos, state);
            !predictions.update(pos, state_from_wire(i64::from(state)))
        });
        self.world.apply_multi_block_change(&p);
        Ok(())
    }

    /// `block_changed_ack` (`BlockStatePredictionHandler.endPredictionsUpTo`): every prediction
    /// up to `ack` ends; `ClientLevel.syncBlockState` puts the server's state back and moves the
    /// player to where it was at the prediction when the restored block would hold it.
    #[cold]
    #[inline(never)]
    pub(super) fn end_predictions(&mut self, ack: i32) {
        let (world, player) = (&mut self.world, &mut self.player);
        let mut snap = None;
        self.predictions.end_up_to(ack, |pos, state, at| {
            // getBlockState of a column that is not loaded is air.
            let now = world
                .block_state(pos.x, pos.y, pos.z)
                .unwrap_or(BlockState::AIR);
            if now == state {
                log::debug!("block_changed_ack {ack}: {pos:?} stays {now}");
                return;
            }
            log::debug!("block_changed_ack {ack}: {pos:?} {now} back to the server's {state}");
            world.set_block_state(pos.x, pos.y, pos.z, state);
            if let Some(at) = at
                && holds_player(state, pos, player)
            {
                // Entity.absSnapTo: the position and the old position, velocity kept.
                player.set_pos(at[0], at[1], at[2]);
                snap = Some(at);
            }
        });
        if let Some(at) = snap {
            self.old_pos = at;
            self.snapped = true;
        }
    }
}

impl ModernSim {
    /// `MultiPlayerGameMode.performUseItemOn` → `BlockItem.place` on the client, when its result
    /// is known exactly ([`crate::sim::predict::PlaceSent`]): the position and the state placed.
    /// `None` when nothing is predicted (also when vanilla places nothing: the player's box is in
    /// the way).
    pub(super) fn plain_placement(
        &self,
        p: &crate::sim::predict::PlaceSent<'_>,
    ) -> Option<(BlockPos, BlockState)> {
        let at = p.face.offset(p.pos);
        let state = plain_placement_rule(
            p,
            |q| self.world.block_state(q.x, q.y, q.z),
            self.world
                .dimension()
                .map(|d| (d.kind.min_y, d.kind.height))?,
            &ghast_physics::BlockView::world_border(&self.world),
        )?;
        if holds_player(state, at, &self.player) {
            // BlockItem.canPlace: Level.isUnobstructed fails, nothing is placed.
            return None;
        }
        Some((at, state))
    }
}

/// The block part of [`ModernSim::plain_placement`] (without the player's box): the state
/// placed.
fn plain_placement_rule(
    p: &crate::sim::predict::PlaceSent<'_>,
    block_at: impl Fn(BlockPos) -> Option<BlockState>,
    (min_y, height): (i32, i32),
    border: &ghast_physics::WorldBorder,
) -> Option<BlockState> {
    use super::data::{Block, Item};
    use crate::common::GameMode;
    use ghast_data::modern::state_flags as sf;
    // ItemStack.useOn: adventure needs can_place_on; spectators never place.
    if !matches!(p.game_mode, GameMode::Survival | GameMode::Creative) {
        return None;
    }
    let stack = p.held?;
    // A component patch may carry block_state / block_entity_data (BlockItem.updateBlockStateFromTag).
    if stack.components().is_some() {
        return None;
    }
    let block = Item::from_id(u16::try_from(stack.id()).ok()?)?.block()?;
    let state = if block.layout().state_count == 1 {
        block.default_state()
    } else if is_pillar(block) {
        // RotatedPillarBlock.getStateForPlacement: the axis of the clicked face.
        use crate::common::Face;
        let axis = match p.face {
            Face::Down | Face::Up => "y",
            Face::North | Face::South => "z",
            Face::West | Face::East => "x",
        };
        block
            .default_state()
            .with(super::data::Property::Axis, axis)?
    } else {
        return None;
    };
    if !state.phys().has(sf::FULL_CUBE) || not_plain_placement(block.name()) {
        return None;
    }
    // useItemOn: the clicked position inside the world border.
    if !crate::sim::predict::border_contains(border, p.pos) {
        return None;
    }
    // A full collision cube is never replaceable (BlockPlaceContext.replaceClicked is false):
    // the block goes next to it.
    let clicked = block_at(p.pos)?;
    if !clicked.phys().has(sf::FULL_CUBE) {
        return None;
    }
    // useItemOn / useWithoutItem of the clicked block, unless sneaking with an item.
    if !(p.sneaking && p.any_item) && activated_full_cube(clicked.block().name()) {
        return None;
    }
    let at = p.face.offset(p.pos);
    if at.y < min_y || at.y >= min_y + height {
        return None;
    }
    // BlockPlaceContext.canPlace: air and fluids are replaceable by any block item.
    let there = block_at(at)?;
    if !(there.is_air() || matches!(there.block(), Block::WATER | Block::LAVA)) {
        return None;
    }
    Some(state)
}

/// A block whose only property is `axis` (x, y, z): logs, wood, stems, pillars, basalt, hay
/// (vanilla `RotatedPillarBlock`, placed along the clicked face's axis).
fn is_pillar(block: super::data::Block) -> bool {
    let mut props = block.properties();
    props.len() == 1
        && props
            .next()
            .is_some_and(|d| d.property == super::data::Property::Axis && d.values.len() == 3)
}

/// Single-state full-cube blocks whose item places them with logic of its own
/// (oracle: `tests/golden/<version>/place.jsonl.gz`): concrete powder hardens next to water,
/// the game-master block needs operator rights.
fn not_plain_placement(name: &str) -> bool {
    name.ends_with("_concrete_powder") || name == "test_instance_block"
}

/// Full-cube blocks a right click may activate (`useItemOn` / `useWithoutItem` consume the click
/// for a block item, then the item is not used). The menus, note blocks, crafters, respawn
/// anchors and vaults are oracle-proven (`place.jsonl.gz`: every full-cube state clicked on its
/// top and a side); blocks whose answer depends on their block entity (which the oracle's level
/// does not have: jukebox records, chiseled bookshelf books, spawners, beehives, operator
/// blocks) are listed without proof and never predicted.
fn activated_full_cube(name: &str) -> bool {
    const LIST: &[&str] = &[
        // Oracle-proven.
        "barrel",
        "beacon",
        "blast_furnace",
        "cartography_table",
        "chiseled_bookshelf",
        "crafter",
        "crafting_table",
        "dispenser",
        "dropper",
        "furnace",
        "loom",
        "note_block",
        "respawn_anchor",
        "smithing_table",
        "smoker",
        "vault",
        // Block entities the answer may read.
        "bee_nest",
        "beehive",
        "chain_command_block",
        "command_block",
        "creaking_heart",
        "jigsaw",
        "jukebox",
        "repeating_command_block",
        "sculk_catalyst",
        "spawner",
        "structure_block",
        "test_block",
        "test_instance_block",
        "trial_spawner",
    ];
    name.ends_with("shulker_box") || LIST.contains(&name)
}

/// What a broken block leaves (`FluidState.createLegacyBlock` of its fluid): a waterlogged
/// block (and kelp, seagrass, bubble columns) leaves a water source, anything else air.
pub(super) fn fluid_left_behind(old: BlockState) -> BlockState {
    use super::data::Block;
    // The fluid byte's kind bits: 1 water, 2 lava. A block that holds a fluid holds a source.
    match old.phys().fluid() >> 6 {
        1 => Block::WATER.default_state(),
        2 => Block::LAVA.default_state(),
        _ => BlockState::AIR,
    }
}

/// A wire block state id as the world stores it (unknown ids read as air).
fn state_from_wire(v: i64) -> BlockState {
    u16::try_from(v)
        .ok()
        .and_then(BlockState::from_id)
        .unwrap_or(BlockState::AIR)
}

/// `Entity.isColliding(pos, state)`: the state's collision shape at `pos` for the player's
/// context (model offsets, scaffolding, powder snow) overlaps the player's box.
fn holds_player(state: BlockState, pos: BlockPos, p: &modern::PlayerState) -> bool {
    let b = &p.bb;
    modern::state_collides::<Rules>(
        state,
        [pos.x, pos.y, pos.z],
        [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
        &modern::CollisionContext {
            feet_y: p.pos[1],
            descending: p.shift(),
            fall_distance: p.fall_distance,
            walks_on_powder_snow: p.leather_boots,
        },
    )
}

/// The union of a shape's boxes as a ray box (block-local).
pub(super) fn outline_box(s: BlockState) -> Option<[f64; 6]> {
    let shape = s.outline_shape();
    if shape.empty {
        return None;
    }
    union(shape.boxes)
}