ghast-world 0.5.6

Chunk storage for the ghast Minecraft Java Edition client library: compact, O(1) block lookup, explicit loaded/unloaded columns, decoding of 1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3 chunk and block-change packets
Documentation
//! Modern chunk section decoding: block containers into paletted sections (plain and through
//! the shared store), biome containers.

use super::*;

/// How a chunk packet's section data is laid out (from the dimension and the registries).
pub(super) struct Layout {
    pub(super) sections: usize,
    pub(super) biome_bits: u32,
    pub(super) biome_count: usize,
    pub(super) keep_biomes: bool,
}

/// A column's sections and (when kept) biomes, or the first malformed section and why.
type Decoded = Result<(Arc<[Section]>, Option<Vec<BiomeSection>>), (usize, &'static str)>;

/// Decodes a chunk packet's sections, in order.
pub(super) fn decode_sections(b: &mut Builder, data: &Bytes, l: &Layout) -> Decoded {
    let mut r = Reader::new(data);
    let mut biomes = l.keep_biomes.then(|| Vec::with_capacity(l.sections));
    let mut err = None;
    // Collected straight into the array (one allocation); after an error the rest is filler.
    let sections: Arc<[Section]> = (0..l.sections)
        .map(|j| {
            if err.is_some() {
                return Section::Uniform(0);
            }
            let step = read_section(b, &mut r).and_then(|s| {
                match &mut biomes {
                    Some(v) => v.push(read_biomes(&mut r, l.biome_bits, l.biome_count)?),
                    None => skip_biomes(&mut r, l.biome_bits, l.biome_count)?,
                }
                Ok(s)
            });
            match step {
                Ok(s) => s,
                Err(reason) => {
                    err = Some((j, reason));
                    Section::Uniform(0)
                }
            }
        })
        .collect();
    match err {
        Some(e) => Err(e),
        None => Ok((sections, biomes)),
    }
}

/// [`decode_sections`] through a store. A first pass over the packet finds every section's
/// identity without decoding it (a single-value container's state, or the key of the bytes of
/// any other container). When a world already holds a column with exactly these sections, its
/// section array is taken: one lookup for the whole column. Otherwise each section is taken
/// from the store or decoded and stored, and the new array is stored too.
///
/// Errors are those of [`decode_sections`]: anything the first pass cannot read sends the
/// packet there, and a section that fails to decode in the second pass is the first malformed
/// one (the first pass read everything else).
pub(super) fn decode_sections_shared(
    b: &mut Builder,
    cache: &SharedChunks,
    data: &Bytes,
    l: &Layout,
) -> Decoded {
    let mut r = Reader::new(data);
    let mut biomes = l.keep_biomes.then(|| Vec::with_capacity(l.sections));
    // (identity, offset of the section in `data`).
    let mut wire: Vec<(Ident, usize)> = Vec::with_capacity(l.sections);
    for _ in 0..l.sections {
        let at = r.position();
        let ident = match shareable_len(&r) {
            Some(len) => {
                let key = cache.key(super::PROTOCOL, &r.rest_slice()[..len]);
                r.skip(len).ok().map(|()| Ident::Keyed(key))
            }
            None => match read_section(b, &mut r) {
                Ok(Section::Uniform(u)) => Some(Ident::Uniform(u)),
                _ => None,
            },
        };
        let biome = match &mut biomes {
            Some(v) => read_biomes(&mut r, l.biome_bits, l.biome_count).map(|b| v.push(b)),
            None => skip_biomes(&mut r, l.biome_bits, l.biome_count),
        };
        let (Some(ident), Ok(())) = (ident, biome) else {
            // Malformed: decode in order for the exact error (nothing is shared then).
            let (sections, biomes) = decode_sections(b, data, l)?;
            return Ok((cache.intern_column(sections), biomes));
        };
        wire.push((ident, at));
    }
    if let Some(sections) = cache.find_column(wire.iter().map(|w| w.0)) {
        return Ok((sections, biomes));
    }
    let mut err = None;
    let sections: Arc<[Section]> = wire
        .iter()
        .enumerate()
        .map(|(j, &(ident, at))| {
            let key = match ident {
                Ident::Uniform(u) => return Section::Uniform(u),
                Ident::Keyed(key) => key,
            };
            if err.is_some() {
                return Section::Uniform(0);
            }
            if let Some(s) = cache.get(key) {
                return s;
            }
            let mut r = Reader::new(data);
            let s = r
                .skip(at)
                .map_err(|_| "truncated")
                .and_then(|()| read_section(b, &mut r));
            match s {
                Ok(s) => cache.insert(key, s),
                Err(reason) => {
                    err = Some((j, reason));
                    Section::Uniform(0)
                }
            }
        })
        .collect();
    match err {
        Some(e) => Err(e),
        None => Ok((cache.intern_column(sections), biomes)),
    }
}

/// Block read inside a column (`ry = y - min_y`): void air outside the height. The read
/// chain (`View::block` → `View::block_state` → `read` → `Section::get`) is always inlined so
/// the physics' collision loops keep it inline (engine bench, instructions per tick).
#[inline(always)]
pub(super) fn read(sections: &[Section], x: i32, ry: i32, z: i32) -> BlockState {
    // One unsigned compare covers both ends: a negative `ry` is at least 2^31 as `u32`, so
    // its section index is at least 2^27, more sections than a dimension can have (its height
    // is an `i32`).
    match sections.get((ry as u32 >> 4) as usize) {
        Some(s) => state(s.get_at(x, ry, z)),
        None => void_air(),
    }
}

/// Reads one section's block container (and the counts before it).
fn read_section(b: &mut Builder, r: &mut Reader<'_>) -> Result<Section, &'static str> {
    const EOF: &str = "truncated";
    r.read_i16().map_err(|_| EOF)?;
    r.read_i16().map_err(|_| EOF)?;
    let bits = r.read_i8().map_err(|_| EOF)?;
    match bits {
        0 => {
            let id = r.read_varint().map_err(|_| EOF)?;
            let id = u16::try_from(id)
                .ok()
                .filter(|&v| usize::from(v) < STATE_COUNT)
                .ok_or("palette id is not a block state")?;
            Ok(Section::Uniform(id))
        }
        1..=8 => {
            let storage = if bits <= 4 { 4u32 } else { bits as u32 };
            let n = r.read_varint().map_err(|_| EOF)?;
            let n = usize::try_from(n).map_err(|_| "negative palette length")?;
            if bits <= 4 && n > 16 {
                return Err("linear palette longer than 16");
            }
            if n > r.remaining() {
                return Err(EOF);
            }
            let mut pal = [0u16; 256];
            for i in 0..n {
                let id = r.read_varint().map_err(|_| EOF)?;
                let id = u16::try_from(id)
                    .ok()
                    .filter(|&v| usize::from(v) < STATE_COUNT)
                    .ok_or("palette id is not a block state")?;
                if let Some(p) = pal.get_mut(i) {
                    *p = id;
                }
            }
            let longs = 4096usize.div_ceil((64 / storage) as usize);
            let data = r.take(longs * 8).map_err(|_| EOF)?;
            b.build(&WireBlocks {
                storage_bits: storage,
                palette: Some(&pal[..n.min(256)]),
                data,
            })
        }
        _ => {
            let longs = 4096usize.div_ceil((64 / GLOBAL_BITS) as usize);
            let data = r.take(longs * 8).map_err(|_| EOF)?;
            b.build(&WireBlocks {
                storage_bits: GLOBAL_BITS,
                palette: None,
                data,
            })
        }
    }
}

/// Length of the section at the reader (counts and block container) when it is worth sharing:
/// `None` for a single-value container (nothing on the heap) and for anything malformed (the
/// decoder then reports the error). Ids are not checked here: a store only holds sections
/// whose identical bytes decoded without error for the same protocol.
fn shareable_len(r: &Reader<'_>) -> Option<usize> {
    let mut p = r.clone();
    let start = p.position();
    p.skip(4).ok()?;
    let bits = p.read_i8().ok()?;
    let longs = match bits {
        0 => return None,
        1..=8 => {
            let n = usize::try_from(p.read_varint().ok()?).ok()?;
            if (bits <= 4 && n > 16) || n > p.remaining() {
                return None;
            }
            for _ in 0..n {
                p.read_varint().ok()?;
            }
            let storage = if bits <= 4 { 4 } else { bits as usize };
            4096usize.div_ceil(64 / storage)
        }
        _ => 4096usize.div_ceil((64 / GLOBAL_BITS) as usize),
    };
    p.skip(longs * 8).ok()?;
    Some(p.position() - start)
}

/// Reads one biome container (`count` = biome registry size, 0 = unknown: ids not checked).
pub(super) fn read_biomes(
    r: &mut Reader<'_>,
    global_bits: u32,
    count: usize,
) -> Result<BiomeSection, &'static str> {
    let mut cells = [0u16; 64];
    Ok(match read_biome_cells(r, global_bits, count, &mut cells)? {
        Some(single) => BiomeSection::Single(single),
        None => BiomeSection::Cells(Box::new(cells)),
    })
}

/// Reads and checks one biome container without keeping it (the same errors as
/// [`read_biomes`], no allocation).
fn skip_biomes(r: &mut Reader<'_>, global_bits: u32, count: usize) -> Result<(), &'static str> {
    read_biome_cells(r, global_bits, count, &mut [0u16; 64]).map(|_| ())
}

/// Reads one biome container into `cells`; `Some(biome)` when the whole section has one biome
/// (`cells` is then unspecified).
fn read_biome_cells(
    r: &mut Reader<'_>,
    global_bits: u32,
    count: usize,
    cells: &mut [u16; 64],
) -> Result<Option<u16>, &'static str> {
    const EOF: &str = "truncated";
    let check = |id: i32| -> Result<u16, &'static str> {
        u16::try_from(id)
            .ok()
            .filter(|&v| count == 0 || usize::from(v) < count)
            .ok_or("palette id is not a biome")
    };
    let bits = r.read_i8().map_err(|_| EOF)?;
    let (storage, palette) = match bits {
        0 => {
            let id = check(r.read_varint().map_err(|_| EOF)?)?;
            return Ok(Some(id));
        }
        1..=3 => {
            let n = r.read_varint().map_err(|_| EOF)?;
            let n = usize::try_from(n).map_err(|_| "negative palette length")?;
            if n > 1 << bits {
                return Err("biome palette too long");
            }
            let mut pal = [0u16; 8];
            for p in pal.iter_mut().take(n) {
                *p = check(r.read_varint().map_err(|_| EOF)?)?;
            }
            (bits as u32, Some((pal, n)))
        }
        _ => (global_bits.max(1), None),
    };
    let per = (64 / storage) as usize;
    let longs = 64usize.div_ceil(per);
    let data = r.take(longs * 8).map_err(|_| EOF)?;
    let mask = (1u64 << storage) - 1;
    let mut i = 0;
    for w in data.as_chunks::<8>().0 {
        let mut x = u64::from_be_bytes(*w);
        for _ in 0..per {
            if i == 64 {
                break;
            }
            let v = (x & mask) as usize;
            cells[i] = match &palette {
                Some((pal, n)) => {
                    if v >= *n {
                        return Err("biome index past the palette");
                    }
                    pal[v]
                }
                None => check(v as i32)?,
            };
            x >>= storage;
            i += 1;
        }
    }
    if cells.iter().all(|&c| c == cells[0]) {
        return Ok(Some(cells[0]));
    }
    Ok(None)
}