Skip to main content

azalea_world/palette/
container.rs

1use std::{
2    fmt::Debug,
3    io::{self, Cursor, Write},
4};
5
6use azalea_block::BlockState;
7use azalea_buf::{AzBuf, BufReadError};
8use azalea_core::position::{ChunkSectionBiomePos, ChunkSectionBlockPos};
9use tracing::{debug, warn};
10
11use super::{Palette, PaletteKind};
12use crate::{BitStorage, biome_id::BiomeId};
13
14#[derive(Clone, Debug, PartialEq)]
15pub struct PalettedContainer<S: PalletedContainerKind> {
16    pub bits_per_entry: u8,
17    /// This is usually a list of unique values that appear in the container so
18    /// they can be indexed by the bit storage.
19    ///
20    /// Sometimes it doesn't contain anything if there's too many unique items
21    /// in the bit storage, though.
22    pub palette: Palette<S>,
23    /// Compacted list of indices pointing to entry IDs in the Palette.
24    pub storage: BitStorage,
25}
26
27pub trait PalletedContainerKind: Copy + Clone + Debug + Default + TryFrom<u32> + Into<u32> {
28    type SectionPos: SectionPos;
29
30    fn size_bits() -> usize;
31
32    fn size() -> usize {
33        1 << (Self::size_bits() * 3)
34    }
35
36    fn bits_per_entry_to_palette_kind(bits_per_entry: u8) -> PaletteKind;
37}
38impl PalletedContainerKind for BlockState {
39    type SectionPos = ChunkSectionBlockPos;
40
41    fn size_bits() -> usize {
42        4
43    }
44
45    fn bits_per_entry_to_palette_kind(bits_per_entry: u8) -> PaletteKind {
46        match bits_per_entry {
47            0 => PaletteKind::SingleValue,
48            1..=4 => PaletteKind::Linear,
49            5..=8 => PaletteKind::Hashmap,
50            _ => PaletteKind::Global,
51        }
52    }
53}
54
55impl PalletedContainerKind for BiomeId {
56    type SectionPos = ChunkSectionBiomePos;
57    fn size_bits() -> usize {
58        2
59    }
60    fn bits_per_entry_to_palette_kind(bits_per_entry: u8) -> PaletteKind {
61        match bits_per_entry {
62            0 => PaletteKind::SingleValue,
63            1..=3 => PaletteKind::Linear,
64            _ => PaletteKind::Global,
65        }
66    }
67}
68
69/// A trait for position types that are sometimes valid ways to index into a
70/// chunk section.
71pub trait SectionPos {
72    fn coords(&self) -> (usize, usize, usize);
73    fn new(x: usize, y: usize, z: usize) -> Self;
74}
75impl SectionPos for ChunkSectionBlockPos {
76    fn coords(&self) -> (usize, usize, usize) {
77        (self.x as usize, self.y as usize, self.z as usize)
78    }
79
80    fn new(x: usize, y: usize, z: usize) -> Self {
81        ChunkSectionBlockPos {
82            x: x as u8,
83            y: y as u8,
84            z: z as u8,
85        }
86    }
87}
88impl SectionPos for ChunkSectionBiomePos {
89    fn coords(&self) -> (usize, usize, usize) {
90        (self.x as usize, self.y as usize, self.z as usize)
91    }
92
93    fn new(x: usize, y: usize, z: usize) -> Self {
94        ChunkSectionBiomePos {
95            x: x as u8,
96            y: y as u8,
97            z: z as u8,
98        }
99    }
100}
101
102impl<S: PalletedContainerKind> PalettedContainer<S> {
103    pub fn new() -> Self {
104        let palette = Palette::SingleValue(S::default());
105        let size = S::size();
106        let storage = BitStorage::new(0, size, Some(Box::new([]))).unwrap();
107
108        PalettedContainer {
109            bits_per_entry: 0,
110            palette,
111            storage,
112        }
113    }
114
115    pub fn read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
116        let bits_per_entry = u8::azalea_read(ctx, buf)?;
117        let palette_type = S::bits_per_entry_to_palette_kind(bits_per_entry);
118        let palette = palette_type.read(ctx, buf)?;
119        let size = S::size();
120
121        let mut storage = match BitStorage::new(
122            bits_per_entry as usize,
123            size,
124            if bits_per_entry == 0 {
125                Some(Box::new([]))
126            } else {
127                // we're going to update the data after creating the bitstorage
128                None
129            },
130        ) {
131            Ok(storage) => storage,
132            Err(e) => {
133                warn!("Failed to create bit storage: {:?}", e);
134                return Err(BufReadError::custom("Failed to create bit storage"));
135            }
136        };
137
138        // now read the data
139        for i in 0..storage.data.len() {
140            storage.data[i] = u64::azalea_read(ctx, buf)?;
141        }
142
143        Ok(PalettedContainer {
144            bits_per_entry,
145            palette,
146            storage,
147        })
148    }
149
150    /// Calculates the index of the given position.
151    pub fn index_from_pos(&self, pos: S::SectionPos) -> usize {
152        let size_bits = S::size_bits();
153        let (x, y, z) = pos.coords();
154        (((y << size_bits) | z) << size_bits) | x
155    }
156
157    pub fn pos_from_index(&self, index: usize) -> S::SectionPos {
158        let size_bits = S::size_bits();
159        let mask = (1 << size_bits) - 1;
160        S::SectionPos::new(
161            index & mask,
162            (index >> size_bits >> size_bits) & mask,
163            (index >> size_bits) & mask,
164        )
165    }
166
167    /// Returns the value at the given index.
168    ///
169    /// # Panics
170    ///
171    /// This function panics if the index is greater than or equal to the number
172    /// of things in the storage. For example, for block states, it must be less
173    /// than 4096.
174    #[inline]
175    pub fn get_at_index(&self, index: usize) -> S {
176        // first get the palette id
177        let paletted_value = self.storage.get(index);
178        // and then get the value from that id
179        self.palette.value_for(paletted_value as usize)
180    }
181
182    /// Returns the value at the given position.
183    pub fn get(&self, pos: S::SectionPos) -> S {
184        self.get_at_index(self.index_from_pos(pos))
185    }
186
187    /// Sets the ID at the given position and return the previous ID.
188    pub fn get_and_set(&mut self, pos: S::SectionPos, value: S) -> S {
189        let paletted_value = self.id_for(value);
190        let old_paletted_value = self
191            .storage
192            .get_and_set(self.index_from_pos(pos), paletted_value as u64);
193        self.palette.value_for(old_paletted_value as usize)
194    }
195
196    /// Sets the ID at the given index and return the previous ID. You probably
197    /// want `.set` instead.
198    pub fn set_at_index(&mut self, index: usize, value: S) {
199        let paletted_value = self.id_for(value);
200        self.storage.set(index, paletted_value as u64);
201    }
202
203    /// Sets the ID at the given position and return the previous ID.
204    pub fn set(&mut self, pos: S::SectionPos, value: S) {
205        self.set_at_index(self.index_from_pos(pos), value);
206    }
207
208    fn create_or_reuse_data(&self, bits_per_entry: u8) -> PalettedContainer<S> {
209        let new_palette_type = S::bits_per_entry_to_palette_kind(bits_per_entry);
210
211        let old_palette_type = (&self.palette).into();
212        if bits_per_entry == self.bits_per_entry && new_palette_type == old_palette_type {
213            return self.clone();
214        }
215        let storage = BitStorage::new(bits_per_entry as usize, S::size(), None).unwrap();
216
217        // sanity check
218        debug_assert_eq!(storage.size(), S::size());
219
220        // let palette = new_palette_type.as_empty_palette(1usize <<
221        // (bits_per_entry as usize));
222        let palette = new_palette_type.as_empty_palette();
223        PalettedContainer {
224            bits_per_entry,
225            palette,
226            storage,
227        }
228    }
229
230    fn on_resize(&mut self, bits_per_entry: u8, value: S) -> usize {
231        debug!(
232            "Resizing PalettedContainer from {} bpe to {bits_per_entry} for {value:?} with palette={:?}",
233            self.bits_per_entry, self.palette
234        );
235        // in vanilla this is always true, but it's sometimes false in purpur
236        // servers
237        // ```
238        // assert!(bits_per_entry <= 5, "bits_per_entry must be <= 5");
239        // ```
240        let mut new_data = self.create_or_reuse_data(bits_per_entry);
241        new_data.copy_from(&self.palette, &self.storage);
242        *self = new_data;
243        self.id_for(value)
244    }
245
246    fn copy_from(&mut self, palette: &Palette<S>, storage: &BitStorage) {
247        for i in 0..storage.size() {
248            let value = palette.value_for(storage.get(i) as usize);
249            let id = self.id_for(value) as u64;
250            self.storage.set(i, id);
251        }
252    }
253
254    pub fn id_for(&mut self, value: S) -> usize {
255        match &mut self.palette {
256            Palette::SingleValue(v) => {
257                if (*v).into() != value.into() {
258                    self.on_resize(1, value)
259                } else {
260                    0
261                }
262            }
263            Palette::Linear(palette) => {
264                if let Some(index) = palette.iter().position(|&v| v.into() == value.into()) {
265                    return index;
266                }
267                let capacity = 2usize.pow(self.bits_per_entry.into());
268                if capacity > palette.len() {
269                    palette.push(value);
270                    palette.len() - 1
271                } else {
272                    self.on_resize(self.bits_per_entry + 1, value)
273                }
274            }
275            Palette::Hashmap(palette) => {
276                // TODO? vanilla keeps this in memory as a hashmap, but it
277                // should be benchmarked before changing it
278                if let Some(index) = palette.iter().position(|v| (*v).into() == value.into()) {
279                    return index;
280                }
281                let capacity = 2usize.pow(self.bits_per_entry.into());
282                if capacity > palette.len() {
283                    palette.push(value);
284                    palette.len() - 1
285                } else {
286                    self.on_resize(self.bits_per_entry + 1, value)
287                }
288            }
289            Palette::Global => value.into() as usize,
290        }
291    }
292}
293
294impl<S: PalletedContainerKind> PalettedContainer<S> {
295    pub fn write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
296        self.bits_per_entry.azalea_write(ctx, buf)?;
297        self.palette.write(ctx, buf)?;
298        for word in &self.storage.data {
299            word.azalea_write(ctx, buf)?;
300        }
301
302        Ok(())
303    }
304}
305
306impl<S: PalletedContainerKind> Default for PalettedContainer<S> {
307    fn default() -> Self {
308        Self::new()
309    }
310}