1use crate::{
2 terrain::MapSizeLg,
3 util::GridHasher,
4 vol::{BaseVol, ReadVol, RectRasterableVol, SampleVol, WriteVol},
5 volumes::dyna::DynaError,
6};
7use hashbrown::{HashMap, hash_map};
8use std::{fmt::Debug, ops::Deref, sync::Arc};
9use vek::*;
10
11#[derive(Debug, Clone)]
12pub enum VolGrid2dError<V: RectRasterableVol> {
13 NoSuchChunk,
14 ChunkError(V::Error),
15 DynaError(DynaError),
16 InvalidChunkSize,
17}
18
19#[derive(Clone)]
23pub struct VolGrid2d<V: RectRasterableVol> {
24 map_size_lg: MapSizeLg,
26 default: Arc<V>,
28 chunks: HashMap<Vec2<i32>, Arc<V>, GridHasher>,
29}
30
31impl<V: RectRasterableVol> VolGrid2d<V> {
32 #[inline(always)]
33 pub fn chunk_key<P: Into<Vec2<i32>>>(pos: P) -> Vec2<i32> {
34 pos.into()
35 .map2(V::RECT_SIZE, |e, sz: u32| e.div_euclid(sz as i32))
36 }
37
38 #[inline(always)]
39 pub fn key_chunk<K: Into<Vec2<i32>>>(key: K) -> Vec2<i32> {
40 key.into() * V::RECT_SIZE.map(|e| e as i32)
41 }
42
43 #[inline(always)]
44 pub fn par_keys(&self) -> hashbrown::hash_map::rayon::ParKeys<Vec2<i32>, Arc<V>>
45 where
46 V: Send + Sync,
47 {
48 self.chunks.par_keys()
49 }
50
51 #[inline(always)]
52 pub fn chunk_offs(pos: Vec3<i32>) -> Vec3<i32> {
53 let offs = Vec2::<i32>::from(pos).map2(V::RECT_SIZE, |e, sz| e & (sz - 1) as i32);
54 Vec3::new(offs.x, offs.y, pos.z)
55 }
56}
57
58impl<V: RectRasterableVol + Debug> BaseVol for VolGrid2d<V> {
59 type Error = VolGrid2dError<V>;
60 type Vox = V::Vox;
61}
62
63impl<V: RectRasterableVol + ReadVol + Debug> ReadVol for VolGrid2d<V> {
64 #[inline(always)]
65 fn get(&self, pos: Vec3<i32>) -> Result<&V::Vox, VolGrid2dError<V>> {
66 let ck = Self::chunk_key(pos);
67 self.get_key(ck)
68 .ok_or(VolGrid2dError::NoSuchChunk)
69 .map(|chunk| {
70 let co = Self::chunk_offs(pos);
71 chunk.get_unchecked(co)
73 })
74 }
75
76 fn for_each_in(&self, aabb: Aabb<i32>, mut f: impl FnMut(Vec3<i32>, Self::Vox))
79 where
80 Self::Vox: Copy,
81 {
82 let min_chunk_key = self.pos_key(aabb.min);
83 let max_chunk_key = self.pos_key(aabb.max);
84 for key_x in min_chunk_key.x..max_chunk_key.x + 1 {
85 for key_y in min_chunk_key.y..max_chunk_key.y + 1 {
86 let key = Vec2::new(key_x, key_y);
87 let pos = self.key_pos(key);
88 let intersection = aabb.intersection(Aabb {
93 min: pos.with_z(i32::MIN),
94 max: (pos + Self::chunk_size().map(|e| e as i32) - 1).with_z(i32::MAX),
97 });
98 let intersection = Aabb {
100 min: Self::chunk_offs(intersection.min),
101 max: Self::chunk_offs(intersection.max),
102 };
103 if let Some(chonk) = self.get_key(key) {
104 chonk.for_each_in(intersection, |pos_offset, block| f(pos_offset + pos, block));
105 }
106 }
107 }
108 }
109}
110
111impl<I: Into<Aabr<i32>>, V: RectRasterableVol + ReadVol + Debug> SampleVol<I> for VolGrid2d<V> {
114 type Sample = VolGrid2d<V>;
115
116 fn sample(&self, range: I) -> Result<Self::Sample, VolGrid2dError<V>> {
122 let range = range.into();
123
124 let mut sample = VolGrid2d::new(self.map_size_lg, Arc::clone(&self.default))?;
125 let chunk_min = Self::chunk_key(range.min);
126 let chunk_max = Self::chunk_key(range.max);
127 for x in chunk_min.x..chunk_max.x + 1 {
128 for y in chunk_min.y..chunk_max.y + 1 {
129 let chunk_key = Vec2::new(x, y);
130
131 let chunk = self.get_key_arc_real(chunk_key).cloned();
132
133 if let Some(chunk) = chunk {
134 sample.insert(chunk_key, chunk);
135 }
136 }
137 }
138
139 Ok(sample)
140 }
141}
142
143impl<V: RectRasterableVol + WriteVol + Clone + Debug> WriteVol for VolGrid2d<V> {
144 #[inline(always)]
145 fn set(&mut self, pos: Vec3<i32>, vox: V::Vox) -> Result<V::Vox, VolGrid2dError<V>> {
146 let ck = Self::chunk_key(pos);
147 self.chunks
148 .get_mut(&ck)
149 .ok_or(VolGrid2dError::NoSuchChunk)
150 .and_then(|chunk| {
151 let co = Self::chunk_offs(pos);
152 Arc::make_mut(chunk)
153 .set(co, vox)
154 .map_err(VolGrid2dError::ChunkError)
155 })
156 }
157}
158
159impl<V: RectRasterableVol> VolGrid2d<V> {
160 pub fn new(map_size_lg: MapSizeLg, default: Arc<V>) -> Result<Self, VolGrid2dError<V>> {
161 if Self::chunk_size()
162 .map(|e| e.is_power_of_two() && e > 0)
163 .reduce_and()
164 {
165 Ok(Self {
166 map_size_lg,
167 default,
168 chunks: HashMap::default(),
169 })
170 } else {
171 Err(VolGrid2dError::InvalidChunkSize)
172 }
173 }
174
175 #[inline(always)]
176 pub fn chunk_size() -> Vec2<u32> { V::RECT_SIZE }
177
178 pub fn insert(&mut self, key: Vec2<i32>, chunk: Arc<V>) -> Option<Arc<V>> {
179 self.chunks.insert(key, chunk)
180 }
181
182 #[inline(always)]
183 pub fn get_key(&self, key: Vec2<i32>) -> Option<&V> {
184 self.get_key_arc(key).map(|arc_chunk| arc_chunk.as_ref())
185 }
186
187 #[inline(always)]
188 pub fn get_key_real(&self, key: Vec2<i32>) -> Option<&V> {
189 self.get_key_arc_real(key)
190 .map(|arc_chunk| arc_chunk.as_ref())
191 }
192
193 #[inline(always)]
194 pub fn contains_key(&self, key: Vec2<i32>) -> bool {
195 self.contains_key_real(key) ||
196 !self.map_size_lg.contains_chunk(key)
199 }
200
201 #[inline(always)]
202 pub fn contains_key_real(&self, key: Vec2<i32>) -> bool { self.chunks.contains_key(&key) }
203
204 #[inline(always)]
205 pub fn get_key_arc(&self, key: Vec2<i32>) -> Option<&Arc<V>> {
206 self.get_key_arc_real(key).or_else(|| {
207 if !self.map_size_lg.contains_chunk(key) {
208 Some(&self.default)
209 } else {
210 None
211 }
212 })
213 }
214
215 #[inline(always)]
216 pub fn get_key_arc_real(&self, key: Vec2<i32>) -> Option<&Arc<V>> { self.chunks.get(&key) }
217
218 pub fn clear(&mut self) { self.chunks.clear(); }
219
220 pub fn drain(&mut self) -> hash_map::Drain<Vec2<i32>, Arc<V>> { self.chunks.drain() }
221
222 pub fn remove(&mut self, key: Vec2<i32>) -> Option<Arc<V>> { self.chunks.remove(&key) }
223
224 #[inline(always)]
229 pub fn key_pos(&self, key: Vec2<i32>) -> Vec2<i32> { Self::key_chunk(key) }
230
231 #[inline(always)]
234 pub fn pos_key(&self, pos: Vec3<i32>) -> Vec2<i32> { Self::chunk_key(pos) }
235
236 #[inline(always)]
238 pub fn pos_chunk(&self, pos: Vec3<i32>) -> Option<&V> { self.get_key(self.pos_key(pos)) }
239
240 pub fn iter(&self) -> ChunkIter<V> {
241 ChunkIter {
242 iter: self.chunks.iter(),
243 }
244 }
245
246 pub fn cached(&self) -> CachedVolGrid2d<V> { CachedVolGrid2d::new(self) }
247}
248
249pub struct CachedVolGrid2d<'a, V: RectRasterableVol> {
250 vol_grid_2d: &'a VolGrid2d<V>,
251 cache: Option<(Vec2<i32>, Arc<V>)>,
254}
255
256impl<'a, V: RectRasterableVol> CachedVolGrid2d<'a, V> {
257 fn new(vol_grid_2d: &'a VolGrid2d<V>) -> Self {
258 Self {
259 vol_grid_2d,
260 cache: None,
261 }
262 }
263}
264
265impl<V: RectRasterableVol + ReadVol> CachedVolGrid2d<'_, V> {
266 #[inline(always)]
267 pub fn get(&mut self, pos: Vec3<i32>) -> Result<&V::Vox, VolGrid2dError<V>> {
268 let ck = VolGrid2d::<V>::chunk_key(pos);
270 let chunk = if self
271 .cache
272 .as_ref()
273 .map(|(key, _)| *key == ck)
274 .unwrap_or(false)
275 {
276 &self.cache.as_ref().unwrap().1
278 } else {
279 let chunk = self
281 .vol_grid_2d
282 .get_key_arc(ck)
283 .ok_or(VolGrid2dError::NoSuchChunk)?;
284 self.cache = Some((ck, Arc::clone(chunk)));
286 chunk
287 };
288 let co = VolGrid2d::<V>::chunk_offs(pos);
289 Ok(chunk.get_unchecked(co))
290 }
291}
292
293impl<V: RectRasterableVol> Deref for CachedVolGrid2d<'_, V> {
294 type Target = VolGrid2d<V>;
295
296 fn deref(&self) -> &Self::Target { self.vol_grid_2d }
297}
298
299pub struct ChunkIter<'a, V: RectRasterableVol> {
300 iter: hash_map::Iter<'a, Vec2<i32>, Arc<V>>,
301}
302
303impl<'a, V: RectRasterableVol> Iterator for ChunkIter<'a, V> {
304 type Item = (Vec2<i32>, &'a Arc<V>);
305
306 fn next(&mut self) -> Option<Self::Item> { self.iter.next().map(|(k, c)| (*k, c)) }
307}