Skip to main content

ghast_world/
section.rs

1//! One 16×16×16 chunk section of raw block states.
2//!
3//! Block states are stored as raw `u16` values (1.8: `id << 4 | meta`, 1.16.5: global palette
4//! id), already mapped the way vanilla reads them (unknown values are air), so a lookup never
5//! needs to validate anything.
6//!
7//! Three representations, chosen per section when it is decoded and changed on demand:
8//!
9//! | variant | memory | lookup |
10//! |---|---|---|
11//! | [`Section::Uniform`] (all blocks the same non-air state) | 0 heap bytes | 1 match |
12//! | indexed (≤ 256 distinct states): `u8` index per block + 256-entry palette | 4.5 KiB | 2 loads |
13//! | direct (> 256 distinct states): `u16` per block | 8 KiB | 1 load |
14//!
15//! All-air sections are not stored at all (the column keeps `None`), which is what vanilla does
16//! for sections the server did not send.
17
18/// Number of blocks in a section.
19pub const SECTION_VOLUME: usize = 4096;
20
21/// Index of a block inside its section: `y << 8 | z << 4 | x` on the low four bits of each
22/// coordinate (vanilla's order in both 1.8 and 1.16).
23#[inline]
24#[must_use]
25pub const fn block_index(x: i32, y: i32, z: i32) -> usize {
26    (((y & 15) << 8) | ((z & 15) << 4) | (x & 15)) as usize
27}
28
29/// Indexed storage: one byte per block into a palette of at most 256 states.
30#[derive(Clone)]
31pub struct Indexed {
32    /// Palette index per block (always `< len`).
33    idx: [u8; SECTION_VOLUME],
34    /// Palette. Entries `len..` are unused (0).
35    palette: [u16; 256],
36    /// Used palette length (`1..=256`).
37    len: u16,
38    /// Number of blocks whose state is not raw 0.
39    non_air: u16,
40}
41
42/// Direct storage: the raw state of every block.
43#[derive(Clone)]
44pub struct Direct {
45    states: [u16; SECTION_VOLUME],
46    /// Number of blocks whose state is not raw 0.
47    non_air: u16,
48}
49
50/// A non-empty chunk section (see the module docs).
51#[derive(Clone)]
52pub enum Section {
53    /// Every block has this state (never raw 0: an all-air section is not stored).
54    Uniform(u16),
55    /// At most 256 distinct states.
56    Indexed(Box<Indexed>),
57    /// More than 256 distinct states.
58    Direct(Box<Direct>),
59}
60
61impl std::fmt::Debug for Section {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        match self {
64            Section::Uniform(s) => f.debug_tuple("Uniform").field(s).finish(),
65            Section::Indexed(b) => f
66                .debug_struct("Indexed")
67                .field("palette", &&b.palette[..usize::from(b.len)])
68                .field("non_air", &b.non_air)
69                .finish(),
70            Section::Direct(b) => f
71                .debug_struct("Direct")
72                .field("non_air", &b.non_air)
73                .finish(),
74        }
75    }
76}
77
78impl Section {
79    /// Raw state of the block at section index `i` (see [`block_index`]).
80    #[inline]
81    #[must_use]
82    pub fn get(&self, i: usize) -> u16 {
83        let i = i & (SECTION_VOLUME - 1);
84        match self {
85            Section::Uniform(s) => *s,
86            Section::Indexed(b) => b.palette[usize::from(b.idx[i])],
87            Section::Direct(b) => b.states[i],
88        }
89    }
90
91    /// Number of blocks that are not raw state 0.
92    #[must_use]
93    pub fn non_air(&self) -> u16 {
94        match self {
95            Section::Uniform(_) => SECTION_VOLUME as u16,
96            Section::Indexed(b) => b.non_air,
97            Section::Direct(b) => b.non_air,
98        }
99    }
100
101    /// Heap bytes owned by this section.
102    #[must_use]
103    pub fn heap_bytes(&self) -> usize {
104        match self {
105            Section::Uniform(_) => 0,
106            Section::Indexed(_) => size_of::<Indexed>(),
107            Section::Direct(_) => size_of::<Direct>(),
108        }
109    }
110
111    /// `true` when `f` holds for a raw state this section may hold: the uniform state, a
112    /// palette entry (an entry no block uses any more counts too) or a direct block. Cheap for
113    /// paletted sections (at most 256 entries).
114    pub fn any_state(&self, f: impl Fn(u16) -> bool) -> bool {
115        match self {
116            Section::Uniform(s) => f(*s),
117            Section::Indexed(b) => b.palette[..usize::from(b.len)].iter().any(|&s| f(s)),
118            Section::Direct(b) => b.states.iter().any(|&s| f(s)),
119        }
120    }
121
122    /// Calls `f(index, raw_state)` for every block, in index order.
123    pub fn for_each(&self, mut f: impl FnMut(usize, u16)) {
124        match self {
125            Section::Uniform(s) => (0..SECTION_VOLUME).for_each(|i| f(i, *s)),
126            Section::Indexed(b) => {
127                for (i, &p) in b.idx.iter().enumerate() {
128                    f(i, b.palette[usize::from(p)]);
129                }
130            }
131            Section::Direct(b) => {
132                for (i, &s) in b.states.iter().enumerate() {
133                    f(i, s);
134                }
135            }
136        }
137    }
138
139    /// Sets the block at index `i` to `state`. Returns `false` when the section became all air
140    /// (the caller then drops it).
141    pub fn set(&mut self, i: usize, state: u16) -> bool {
142        let i = i & (SECTION_VOLUME - 1);
143        match self {
144            Section::Uniform(u) => {
145                if *u == state {
146                    return true;
147                }
148                let mut b = Box::new(Indexed {
149                    idx: [0; SECTION_VOLUME],
150                    palette: [0; 256],
151                    len: 2,
152                    non_air: SECTION_VOLUME as u16,
153                });
154                b.palette[0] = *u;
155                b.palette[1] = state;
156                b.idx[i] = 1;
157                if state == 0 {
158                    b.non_air -= 1;
159                }
160                *self = Section::Indexed(b);
161                true
162            }
163            Section::Indexed(b) => {
164                let old = b.palette[usize::from(b.idx[i])];
165                if old == state {
166                    return true;
167                }
168                let p = match b.find_or_insert(state) {
169                    Some(p) => p,
170                    None => {
171                        // Palette full: go direct.
172                        let mut d = Box::new(Direct {
173                            states: [0; SECTION_VOLUME],
174                            non_air: b.non_air,
175                        });
176                        for (dst, &p) in d.states.iter_mut().zip(b.idx.iter()) {
177                            *dst = b.palette[usize::from(p)];
178                        }
179                        *self = Section::Direct(d);
180                        return self.set(i, state);
181                    }
182                };
183                b.idx[i] = p;
184                adjust(&mut b.non_air, old, state);
185                b.non_air != 0
186            }
187            Section::Direct(b) => {
188                let old = b.states[i];
189                b.states[i] = state;
190                adjust(&mut b.non_air, old, state);
191                b.non_air != 0
192            }
193        }
194    }
195
196    /// A section with every block air except `state` at index `i`; `None` if `state` is air.
197    #[must_use]
198    pub fn single(i: usize, state: u16) -> Option<Section> {
199        if state == 0 {
200            return None;
201        }
202        let mut b = Box::new(Indexed {
203            idx: [0; SECTION_VOLUME],
204            palette: [0; 256],
205            len: 2,
206            non_air: 1,
207        });
208        b.palette[1] = state;
209        b.idx[i & (SECTION_VOLUME - 1)] = 1;
210        Some(Section::Indexed(b))
211    }
212}
213
214#[inline]
215fn adjust(non_air: &mut u16, old: u16, new: u16) {
216    match (old == 0, new == 0) {
217        (true, false) => *non_air += 1,
218        (false, true) => *non_air -= 1,
219        _ => {}
220    }
221}
222
223impl Indexed {
224    /// Palette index of `state`, appending it if needed. When the palette is full, unused
225    /// entries are compacted away first; `None` if it is still full.
226    fn find_or_insert(&mut self, state: u16) -> Option<u8> {
227        let len = usize::from(self.len);
228        if let Some(p) = self.palette[..len].iter().position(|&s| s == state) {
229            return Some(p as u8);
230        }
231        if len == 256 {
232            self.compact();
233        }
234        let len = usize::from(self.len);
235        if len == 256 {
236            return None;
237        }
238        self.palette[len] = state;
239        self.len += 1;
240        Some(len as u8)
241    }
242
243    /// Drops palette entries no block uses.
244    fn compact(&mut self) {
245        let mut used = [false; 256];
246        for &p in &self.idx {
247            used[usize::from(p)] = true;
248        }
249        let mut remap = [0u8; 256];
250        let mut palette = [0u16; 256];
251        let mut n = 0usize;
252        for p in 0..usize::from(self.len) {
253            if used[p] {
254                remap[p] = n as u8;
255                palette[n] = self.palette[p];
256                n += 1;
257            }
258        }
259        for p in &mut self.idx {
260            *p = remap[usize::from(*p)];
261        }
262        self.palette = palette;
263        self.len = n as u16;
264    }
265}
266
267/// Builds sections from decoded raw states (shared by every chunk format).
268///
269/// The builder keeps a reusable scratch table so decoding allocates only the section itself.
270#[cfg_attr(
271    not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
272    allow(dead_code)
273)]
274pub(crate) struct SectionBuilder {
275    /// `state -> palette index + 1` (0 = not in the palette yet), sized for the largest state
276    /// space handed to [`SectionBuilder::push_states`].
277    lookup: Vec<u16>,
278}
279
280#[cfg_attr(
281    not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
282    allow(dead_code)
283)]
284impl SectionBuilder {
285    pub(crate) fn new(state_space: usize) -> Self {
286        SectionBuilder {
287            lookup: vec![0; state_space],
288        }
289    }
290
291    /// Builds a section from 4096 raw states (already mapped the way vanilla reads them;
292    /// values outside the state space are treated as air).
293    pub(crate) fn build(&mut self, states: &[u16; SECTION_VOLUME]) -> Option<Section> {
294        let space = self.lookup.len();
295        let mut non_air = 0u16;
296        for &s in states {
297            non_air += u16::from(s != 0);
298        }
299        if non_air == 0 {
300            return None;
301        }
302        let mut ix = Box::new(Indexed {
303            idx: [0; SECTION_VOLUME],
304            palette: [0; 256],
305            len: 0,
306            non_air,
307        });
308        let mut len = 0usize;
309        let mut overflow = false;
310        for (dst, &s) in ix.idx.iter_mut().zip(states.iter()) {
311            let s = if usize::from(s) < space { s } else { 0 };
312            let slot = &mut self.lookup[usize::from(s)];
313            if *slot == 0 {
314                if len == 256 {
315                    overflow = true;
316                    break;
317                }
318                ix.palette[len] = s;
319                len += 1;
320                *slot = len as u16;
321            }
322            *dst = (*slot - 1) as u8;
323        }
324        self.reset(&ix.palette[..len]);
325        if overflow {
326            let mut d = Box::new(Direct {
327                states: *states,
328                non_air: 0,
329            });
330            let mut n = 0u16;
331            for s in &mut d.states {
332                if usize::from(*s) >= space {
333                    *s = 0;
334                }
335                n += u16::from(*s != 0);
336            }
337            d.non_air = n;
338            return (n != 0).then_some(Section::Direct(d));
339        }
340        if len == 1 {
341            return Some(Section::Uniform(ix.palette[0]));
342        }
343        // Out-of-space values were mapped to air: recount.
344        if ix.palette[..len].contains(&0) {
345            let air = ix.palette[..len].iter().position(|&s| s == 0).unwrap_or(0) as u8;
346            ix.non_air = ix.idx.iter().filter(|&&p| p != air).count() as u16;
347            if ix.non_air == 0 {
348                return None;
349            }
350        }
351        ix.len = len as u16;
352        Some(Section::Indexed(ix))
353    }
354
355    /// Builds a section from 1.16-style packed palette indices: `bits` (`4..=8`) per value in
356    /// big-endian words `data` (at least `words_needed(bits, 4096)` words), and `remap` = the
357    /// wire palette already mapped to raw states. Indices past the palette read as air.
358    #[cfg_attr(not(feature = "v1_16_5"), allow(dead_code))]
359    pub(crate) fn build_packed(
360        &mut self,
361        remap: &[u16],
362        bits: u32,
363        data: &[u8],
364    ) -> Option<Section> {
365        self.build_packed_layout(remap, bits, data, false)
366    }
367
368    /// [`SectionBuilder::build_packed`] with the word layout chosen: `spanning` = the 1.9 – 1.15
369    /// layout where values may span two words.
370    #[cfg_attr(not(any(feature = "v1_12", feature = "v1_16_5")), allow(dead_code))]
371    pub(crate) fn build_packed_layout(
372        &mut self,
373        remap: &[u16],
374        bits: u32,
375        data: &[u8],
376        spanning: bool,
377    ) -> Option<Section> {
378        debug_assert!((4..=8).contains(&bits));
379        let reachable = 1usize << bits;
380        // Deduplicate the reachable palette entries (plus air for indices past the palette).
381        let mut palette = [0u16; 256];
382        let mut len = 0usize;
383        let mut to_palette = [0u8; 256];
384        let space = self.lookup.len();
385        for (w, slot_out) in to_palette.iter_mut().enumerate().take(reachable) {
386            let s = remap.get(w).copied().unwrap_or(0);
387            let s = if usize::from(s) < space { s } else { 0 };
388            let slot = &mut self.lookup[usize::from(s)];
389            if *slot == 0 {
390                palette[len] = s;
391                len += 1;
392                *slot = len as u16;
393            }
394            *slot_out = (*slot - 1) as u8;
395            if w >= remap.len() {
396                // Every further index maps to air too.
397                let air = *slot_out;
398                to_palette[w..reachable].fill(air);
399                break;
400            }
401        }
402        self.reset(&palette[..len]);
403
404        let mut ix = Box::new(Indexed {
405            idx: [0; SECTION_VOLUME],
406            palette: [0; 256],
407            len: 0,
408            non_air: 0,
409        });
410        let mut hist = [0u16; 256];
411        let mut put = |i: usize, v: u32| {
412            let p = to_palette[(v & 255) as usize];
413            ix.idx[i] = p;
414            hist[usize::from(p)] += 1;
415        };
416        if spanning {
417            crate::packed::unpack_spanning_be(bits, data, SECTION_VOLUME, &mut put);
418        } else {
419            crate::packed::unpack_be(bits, data, SECTION_VOLUME, &mut put);
420        }
421        // Keep only used palette entries.
422        let mut remap2 = [0u8; 256];
423        let mut n = 0usize;
424        let mut non_air = 0u16;
425        for p in 0..len {
426            if hist[p] != 0 {
427                remap2[p] = n as u8;
428                ix.palette[n] = palette[p];
429                if palette[p] != 0 {
430                    non_air += hist[p];
431                }
432                n += 1;
433            }
434        }
435        if non_air == 0 {
436            return None;
437        }
438        if n == 1 {
439            return Some(Section::Uniform(ix.palette[0]));
440        }
441        if n != len {
442            for p in &mut ix.idx {
443                *p = remap2[usize::from(*p)];
444            }
445        }
446        ix.len = n as u16;
447        ix.non_air = non_air;
448        Some(Section::Indexed(ix))
449    }
450
451    fn reset(&mut self, palette: &[u16]) {
452        for &s in palette {
453            self.lookup[usize::from(s)] = 0;
454        }
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    fn check_eq(s: &Option<Section>, expect: &[u16]) {
463        for (i, &e) in expect.iter().enumerate() {
464            let got = s.as_ref().map_or(0, |s| s.get(i));
465            assert_eq!(got, e, "index {i}");
466        }
467        let non_air = expect.iter().filter(|&&v| v != 0).count();
468        assert_eq!(s.as_ref().map_or(0, |s| usize::from(s.non_air())), non_air);
469    }
470
471    #[test]
472    fn build_variants() {
473        let mut b = SectionBuilder::new(4096);
474        assert!(b.build(&[0; 4096]).is_none());
475        assert!(matches!(b.build(&[16; 4096]), Some(Section::Uniform(16))));
476        let v: Vec<u16> = (0..4096).map(|i| (i % 7) as u16 * 16).collect();
477        let s = b.build(v.as_slice().try_into().unwrap());
478        assert!(matches!(s, Some(Section::Indexed(_))));
479        check_eq(&s, &v);
480        let v: Vec<u16> = (0..4096).map(|i| (i % 300) as u16).collect();
481        let s = b.build(v.as_slice().try_into().unwrap());
482        assert!(matches!(s, Some(Section::Direct(_))));
483        check_eq(&s, &v);
484        // Scratch table is clean afterwards.
485        assert!(b.lookup.iter().all(|&x| x == 0));
486    }
487
488    #[test]
489    fn set_transitions() {
490        let mut b = SectionBuilder::new(4096);
491        let mut expect = vec![1u16; 4096];
492        let mut s = b.build(&[1; 4096]);
493        // Uniform -> indexed -> direct -> all air.
494        for (i, e) in expect.iter_mut().enumerate() {
495            let v = (i % 400) as u16;
496            *e = v;
497            let alive = s.as_mut().unwrap().set(i, v);
498            assert!(alive);
499        }
500        check_eq(&s, &expect);
501        assert!(matches!(s, Some(Section::Direct(_))));
502        for i in 0..4096usize {
503            let alive = s.as_mut().unwrap().set(i, 0);
504            assert_eq!(alive, i != 4095);
505        }
506    }
507
508    #[test]
509    fn palette_compaction_keeps_indexed() {
510        let mut b = SectionBuilder::new(4096);
511        let mut s = b.build(&[1; 4096]).unwrap();
512        // Cycle 1000 distinct states through one block: stale palette entries get compacted.
513        for v in 2..1000u16 {
514            s.set(0, v);
515        }
516        assert!(matches!(s, Section::Indexed(_)), "{s:?}");
517        assert_eq!(s.get(0), 999);
518        assert_eq!(s.get(1), 1);
519    }
520
521    #[test]
522    fn single() {
523        let s = Section::single(block_index(1, 2, 3), 5).unwrap();
524        assert_eq!(s.get(block_index(1, 2, 3)), 5);
525        assert_eq!(s.get(0), 0);
526        assert_eq!(s.non_air(), 1);
527        assert!(Section::single(0, 0).is_none());
528    }
529}