Skip to main content

azalea_world/chunk/
storage.rs

1use std::{
2    any::Any,
3    collections::hash_map::Entry,
4    fmt::{self, Debug},
5    ops::{Deref, DerefMut},
6    sync::{Arc, Weak},
7};
8
9use azalea_block::{BlockState, fluid_state::FluidState};
10use azalea_core::position::{BlockPos, ChunkBiomePos, ChunkBlockPos, ChunkPos};
11use nohash_hasher::IntMap;
12use parking_lot::RwLock;
13
14use crate::{Chunk, biome_id::BiomeId};
15
16/// An abstract chunk storage backed by a [`ChunkStorageTrait`] implementation.
17///
18/// By default, this wraps a [`WeakChunkStorage`].
19pub struct ChunkStorage(pub Box<dyn ChunkStorageTrait>);
20
21pub trait ChunkStorageTrait: Send + Sync + Any {
22    /// Return the lowest y coordinate in the world, usually `-64`.
23    fn min_y(&self) -> i32;
24    /// Return the height of the world in blocks, usually `384`.
25    fn height(&self) -> u32;
26    /// Return a reference to the chunk from the storage.
27    #[must_use]
28    fn get(&self, pos: &ChunkPos) -> Option<Arc<RwLock<Chunk>>>;
29    /// Insert the chunk into the storage and return a reference to it.
30    ///
31    /// Since the storage may be a [`WeakChunkStorage`], you must immediately
32    /// put the returned `Arc<RwLock<Chunk>>` somewhere (probably a
33    /// [`PartialChunkStorage`](crate::PartialChunkStorage)).
34    #[must_use]
35    fn upsert(&mut self, pos: ChunkPos, chunk: Chunk) -> Arc<RwLock<Chunk>>;
36    fn chunks(&self) -> Box<[&ChunkPos]>;
37    fn clone_box(&self) -> Box<dyn ChunkStorageTrait>;
38
39    // these impls are here instead of in the `impl ChunkStorage` so rust is
40    // able to inline more and thus optimize them a lot better.
41
42    /// Returns the [`BlockState`] at the given position.
43    ///
44    /// If the block is outside of the world, then `None` is returned.
45    fn get_block_state(&self, pos: BlockPos) -> Option<BlockState> {
46        let chunk = self.get(&ChunkPos::from(pos))?;
47        let chunk = chunk.read();
48        chunk.get_block_state(&ChunkBlockPos::from(pos), self.min_y())
49    }
50    /// Set a [`BlockState`] at the given position.
51    ///
52    /// Returns the block that was previously there, or `None` if the position
53    /// is outside of the world.
54    fn set_block_state(&self, pos: BlockPos, state: BlockState) -> Option<BlockState> {
55        if pos.y < self.min_y() || pos.y >= (self.min_y() + self.height() as i32) {
56            return None;
57        }
58        let chunk = self.get(&ChunkPos::from(pos))?;
59        let mut chunk = chunk.write();
60        Some(chunk.get_and_set_block_state(&ChunkBlockPos::from(pos), state, self.min_y()))
61    }
62    fn get_fluid_state(&self, pos: BlockPos) -> Option<FluidState> {
63        let block_state = self.get_block_state(pos)?;
64        Some(FluidState::from(block_state))
65    }
66    fn get_biome_id(&self, pos: BlockPos) -> Option<BiomeId> {
67        let chunk = self.get(&ChunkPos::from(pos))?;
68        let chunk = chunk.read();
69        chunk.get_biome_id(ChunkBiomePos::from(pos), self.min_y())
70    }
71}
72impl ChunkStorage {
73    /// Create a storage backed by a [`WeakChunkStorage`] with the given world
74    /// dimensions.
75    pub fn new(height: u32, min_y: i32) -> Self {
76        Self(Box::new(WeakChunkStorage::new(height, min_y)))
77    }
78
79    /// Create a storage backed by a custom [`ChunkStorageTrait`]
80    /// implementation.
81    pub fn new_with(inner: Box<dyn ChunkStorageTrait>) -> Self {
82        Self(inner)
83    }
84}
85
86impl Deref for ChunkStorage {
87    type Target = dyn ChunkStorageTrait;
88
89    fn deref(&self) -> &Self::Target {
90        &*self.0
91    }
92}
93impl DerefMut for ChunkStorage {
94    fn deref_mut(&mut self) -> &mut Self::Target {
95        &mut *self.0
96    }
97}
98impl Clone for ChunkStorage {
99    fn clone(&self) -> Self {
100        Self(self.0.clone_box())
101    }
102}
103
104/// A storage for chunks where they're only stored weakly, so if they're not
105/// actively being used somewhere else they'll be forgotten.
106///
107/// This is used for shared worlds.
108///
109/// This is relatively cheap to clone since it's just an `IntMap` with `Weak`
110/// pointers.
111#[derive(Clone, Debug)]
112pub struct WeakChunkStorage {
113    /// The height of the world.
114    ///
115    /// To get the maximum y position (exclusive), you have to combine this with
116    /// [`Self::min_y`].
117    pub height: u32,
118    /// The lowest y position in the world that can still have blocks placed on
119    /// it.
120    ///
121    /// This exists because in modern Minecraft versions, worlds can extend
122    /// below y=0.
123    pub min_y: i32,
124    pub map: IntMap<ChunkPos, Weak<RwLock<Chunk>>>,
125}
126
127impl WeakChunkStorage {
128    pub fn new(height: u32, min_y: i32) -> Self {
129        WeakChunkStorage {
130            height,
131            min_y,
132            map: IntMap::default(),
133        }
134    }
135}
136impl ChunkStorageTrait for WeakChunkStorage {
137    fn min_y(&self) -> i32 {
138        self.min_y
139    }
140    fn height(&self) -> u32 {
141        self.height
142    }
143    fn get(&self, pos: &ChunkPos) -> Option<Arc<RwLock<Chunk>>> {
144        self.map.get(pos).and_then(|chunk| chunk.upgrade())
145    }
146
147    fn upsert(&mut self, pos: ChunkPos, chunk: Chunk) -> Arc<RwLock<Chunk>> {
148        match self.map.entry(pos) {
149            Entry::Occupied(mut e) => {
150                if let Some(existing) = e.get_mut().upgrade() {
151                    *existing.write() = chunk;
152                    existing
153                } else {
154                    let arc = Arc::new(RwLock::new(chunk));
155                    e.insert(Arc::downgrade(&arc));
156                    arc
157                }
158            }
159            Entry::Vacant(e) => {
160                let arc = Arc::new(RwLock::new(chunk));
161                e.insert(Arc::downgrade(&arc));
162                arc
163            }
164        }
165    }
166
167    fn chunks(&self) -> Box<[&ChunkPos]> {
168        self.map.keys().collect::<Vec<_>>().into_boxed_slice()
169    }
170
171    fn clone_box(&self) -> Box<dyn ChunkStorageTrait> {
172        Box::new(self.clone())
173    }
174}
175
176impl Default for WeakChunkStorage {
177    fn default() -> Self {
178        Self::new(384, -64)
179    }
180}
181impl Default for ChunkStorage {
182    fn default() -> Self {
183        Self::new(384, -64)
184    }
185}
186
187impl Debug for ChunkStorage {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        f.debug_struct("ChunkStorage")
190            .field("min_y", &self.0.min_y())
191            .field("height", &self.0.height())
192            .field("chunk_count", &self.0.chunks().len())
193            .finish()
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use azalea_core::position::{BlockPos, ChunkPos};
200
201    use crate::{
202        Chunk,
203        chunk::{partial::PartialChunkStorage, storage::ChunkStorage},
204    };
205
206    #[test]
207    fn test_out_of_bounds_y() {
208        let mut chunk_storage = ChunkStorage::default();
209        let mut partial_chunk_storage = PartialChunkStorage::default();
210        partial_chunk_storage.set(
211            &ChunkPos { x: 0, z: 0 },
212            Some(Chunk::default()),
213            &mut chunk_storage,
214        );
215        assert!(
216            chunk_storage
217                .get_block_state(BlockPos { x: 0, y: 319, z: 0 })
218                .is_some()
219        );
220        assert!(
221            chunk_storage
222                .get_block_state(BlockPos { x: 0, y: 320, z: 0 })
223                .is_none()
224        );
225        assert!(
226            chunk_storage
227                .get_block_state(BlockPos { x: 0, y: 338, z: 0 })
228                .is_none()
229        );
230        assert!(
231            chunk_storage
232                .get_block_state(BlockPos { x: 0, y: -64, z: 0 })
233                .is_some()
234        );
235        assert!(
236            chunk_storage
237                .get_block_state(BlockPos { x: 0, y: -65, z: 0 })
238                .is_none()
239        );
240    }
241}