Skip to main content

ghast_protocol/types/
chunk.rs

1//! Chunk section data of the modern chunk packet (`map_chunk.chunkData`), as sent by
2//! protocol 775 (26.1 – 26.1.2).
3//!
4//! The packet carries the sections as one byte array; this module walks it without
5//! copying. Per section, bottom to top:
6//!
7//! - `i16` non-empty block count, `i16` fluid count;
8//! - block states: a paletted container of 16³ entries;
9//! - biomes: a paletted container of 4³ entries.
10//!
11//! A paletted container is a `u8` bit count, the palette and a long array whose length is
12//! implied by the bit count (no length prefix since 1.21.5):
13//!
14//! | bits (blocks / biomes) | palette | entries |
15//! |---|---|---|
16//! | 0 | one VarInt id | no longs |
17//! | 1–8 / 1–3 | VarInt count + ids | indices into the palette |
18//! | larger | none | global ids |
19//!
20//! Block containers with 1–3 bits are stored with 4 bits (vanilla never sends fewer than
21//! 4 for an indirect block palette). Entries are packed little-end first into each long and
22//! do not span longs. The number of sections depends on the dimension's height
23//! (`dimension_type` registry); [`Sections`] simply reads until the data ends.
24
25use bytes::Bytes;
26
27use crate::codec::{DecodeResult, Reader};
28use crate::error::DecodeError;
29
30/// What a paletted container holds.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32pub enum ContainerKind {
33    /// 4096 block states.
34    Blocks,
35    /// 64 biomes.
36    Biomes,
37}
38
39impl ContainerKind {
40    /// Number of entries.
41    pub const fn entries(self) -> usize {
42        match self {
43            ContainerKind::Blocks => 4096,
44            ContainerKind::Biomes => 64,
45        }
46    }
47
48    /// Largest bit count that still uses an indirect palette.
49    const fn max_indirect(self) -> u8 {
50        match self {
51            ContainerKind::Blocks => 8,
52            ContainerKind::Biomes => 3,
53        }
54    }
55
56    /// Bits per entry in the long array for a wire bit count.
57    const fn storage_bits(self, bits: u8) -> u8 {
58        match self {
59            ContainerKind::Blocks if bits >= 1 && bits <= 4 => 4,
60            _ => bits,
61        }
62    }
63}
64
65/// The palette of a container.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub enum Palette {
68    /// Every entry has this id.
69    Single(i32),
70    /// Entries are indices into this list of ids.
71    Indirect(Vec<i32>),
72    /// Entries are global ids.
73    Direct,
74}
75
76/// One paletted container; the long array stays a zero-copy slice of the packet.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct PalettedContainer {
79    /// Kind (entry count).
80    pub kind: ContainerKind,
81    /// Bit count as sent.
82    pub bits: u8,
83    /// The palette.
84    pub palette: Palette,
85    /// The packed big-endian longs.
86    pub data: Bytes,
87}
88
89impl PalettedContainer {
90    /// Reads one container.
91    pub fn read(r: &mut Reader<'_>, kind: ContainerKind) -> DecodeResult<Self> {
92        let bits = r.read_u8()?;
93        let palette = if bits == 0 {
94            Palette::Single(r.read_varint()?)
95        } else if bits <= kind.max_indirect() {
96            let n = r.read_varint()?;
97            let n = r.check_count(i64::from(n), 1)?;
98            let mut ids = Vec::with_capacity(n.min(256));
99            for _ in 0..n {
100                ids.push(r.read_varint()?);
101            }
102            Palette::Indirect(ids)
103        } else {
104            Palette::Direct
105        };
106        let longs = Self::long_count(kind, bits).ok_or(DecodeError::Invalid("palette bits"))?;
107        let data = r.read_bytes(longs * 8)?;
108        Ok(PalettedContainer {
109            kind,
110            bits,
111            palette,
112            data,
113        })
114    }
115
116    /// Number of longs for a wire bit count (`None` if the bit count is invalid).
117    pub fn long_count(kind: ContainerKind, bits: u8) -> Option<usize> {
118        if bits == 0 {
119            return Some(0);
120        }
121        let b = kind.storage_bits(bits);
122        if b > 32 {
123            return None;
124        }
125        let per_long = 64 / usize::from(b);
126        Some(kind.entries().div_ceil(per_long))
127    }
128
129    /// The id at entry `index` (`y << 8 | z << 4 | x` for blocks, `y << 4 | z << 2 | x`
130    /// for biomes). `None` if the index or a palette index is out of range.
131    pub fn get(&self, index: usize) -> Option<i32> {
132        if index >= self.kind.entries() {
133            return None;
134        }
135        let raw = match &self.palette {
136            Palette::Single(id) => return Some(*id),
137            _ => {
138                let b = usize::from(self.kind.storage_bits(self.bits));
139                let per_long = 64 / b;
140                let (li, slot) = (index / per_long, index % per_long);
141                let at = li * 8;
142                let long = u64::from_be_bytes(self.data.get(at..at + 8)?.try_into().ok()?);
143                ((long >> (slot * b)) & ((1u64 << b) - 1)) as usize
144            }
145        };
146        match &self.palette {
147            Palette::Indirect(ids) => ids.get(raw).copied(),
148            _ => i32::try_from(raw).ok(),
149        }
150    }
151}
152
153/// One chunk section.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct ChunkSection {
156    /// Blocks that are not air.
157    pub block_count: i16,
158    /// Blocks with a fluid.
159    pub fluid_count: i16,
160    /// Block states.
161    pub blocks: PalettedContainer,
162    /// Biomes.
163    pub biomes: PalettedContainer,
164}
165
166impl ChunkSection {
167    /// Reads one section.
168    pub fn read(r: &mut Reader<'_>) -> DecodeResult<Self> {
169        Ok(ChunkSection {
170            block_count: r.read_i16()?,
171            fluid_count: r.read_i16()?,
172            blocks: PalettedContainer::read(r, ContainerKind::Blocks)?,
173            biomes: PalettedContainer::read(r, ContainerKind::Biomes)?,
174        })
175    }
176}
177
178/// Iterator over the sections of `map_chunk.chunkData`, bottom to top.
179#[derive(Debug, Clone)]
180pub struct Sections<'a> {
181    r: Reader<'a>,
182    failed: bool,
183}
184
185impl<'a> Sections<'a> {
186    /// Walks `data`.
187    pub fn new(data: &'a Bytes) -> Self {
188        Sections {
189            r: Reader::new(data),
190            failed: false,
191        }
192    }
193}
194
195impl Iterator for Sections<'_> {
196    type Item = DecodeResult<ChunkSection>;
197
198    fn next(&mut self) -> Option<Self::Item> {
199        if self.failed || self.r.remaining() == 0 {
200            return None;
201        }
202        let s = ChunkSection::read(&mut self.r);
203        self.failed = s.is_err();
204        Some(s)
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211    use crate::codec::McWrite;
212    use bytes::{BufMut, BytesMut};
213
214    #[test]
215    fn single_and_indirect() {
216        let mut w = BytesMut::new();
217        // Section 1: all stone (id 1), plains biome (id 0).
218        w.put_i16(4096);
219        w.put_i16(0);
220        w.put_u8(0);
221        w.put_varint(1);
222        w.put_u8(0);
223        w.put_varint(0);
224        // Section 2: indirect palette [air, grass] with 4 bits, entry 0 = grass.
225        w.put_i16(1);
226        w.put_i16(0);
227        w.put_u8(4);
228        w.put_varint(2);
229        w.put_varint(0);
230        w.put_varint(9);
231        for i in 0..256 {
232            w.put_u64(if i == 0 { 1 } else { 0 });
233        }
234        w.put_u8(0);
235        w.put_varint(3);
236        let data = w.freeze();
237        let s: Vec<ChunkSection> = Sections::new(&data).map(Result::unwrap).collect();
238        assert_eq!(s.len(), 2);
239        assert_eq!(s[0].blocks.get(123), Some(1));
240        assert_eq!(s[1].blocks.get(0), Some(9));
241        assert_eq!(s[1].blocks.get(1), Some(0));
242        assert_eq!(s[1].biomes.get(5), Some(3));
243        assert_eq!(s[1].blocks.get(4096), None);
244        assert_eq!(
245            PalettedContainer::long_count(ContainerKind::Blocks, 15),
246            Some(1024)
247        );
248        assert_eq!(
249            PalettedContainer::long_count(ContainerKind::Biomes, 7),
250            Some(8)
251        );
252    }
253}