azalea_world/chunk/
storage.rs1use 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
16pub struct ChunkStorage(pub Box<dyn ChunkStorageTrait>);
20
21pub trait ChunkStorageTrait: Send + Sync + Any {
22 fn min_y(&self) -> i32;
24 fn height(&self) -> u32;
26 #[must_use]
28 fn get(&self, pos: &ChunkPos) -> Option<Arc<RwLock<Chunk>>>;
29 #[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 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 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 pub fn new(height: u32, min_y: i32) -> Self {
76 Self(Box::new(WeakChunkStorage::new(height, min_y)))
77 }
78
79 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#[derive(Clone, Debug)]
112pub struct WeakChunkStorage {
113 pub height: u32,
118 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}