forked from feather-rs/feather
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworld_source.rs
More file actions
84 lines (75 loc) · 2.48 KB
/
world_source.rs
File metadata and controls
84 lines (75 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use base::{Chunk, ChunkPosition};
pub mod flat;
pub mod null;
pub mod region;
/// A chunk loaded from a [`WorldSource`].
pub struct LoadedChunk {
pub pos: ChunkPosition,
pub result: ChunkLoadResult,
}
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum ChunkLoadResult {
/// The chunk does not exist in this source.
Missing,
/// An error occurred while loading the chunk.
Error(anyhow::Error),
/// Successfully loaded the chunk.
Loaded { chunk: Chunk },
}
/// Provides methods to load chunks, entities, and global world data.
pub trait WorldSource: 'static {
/// Enqueues the chunk at `pos` to be loaded.
/// A future call to `poll_loaded_chunk` should
/// return this chunk.
fn queue_load(&mut self, pos: ChunkPosition);
/// Polls for the next loaded chunk. Should not block
///
/// The order in which chunks are loaded is not defined. In other
/// words, this method does not need to yield chunks in the
/// same order they were queued for loading.
fn poll_loaded_chunk(&mut self) -> Option<LoadedChunk>;
/// Creates a `WorldSource` that falls back to `fallback`
/// if chunks in `self` are missing or corrupt.
fn with_fallback(self, fallback: impl WorldSource) -> FallbackWorldSource
where
Self: Sized,
{
FallbackWorldSource {
first: Box::new(self),
fallback: Box::new(fallback),
}
}
}
/// `WorldSource` wrapping two world sources. Falls back
/// to the second source if the first one is missing a chunk.
pub struct FallbackWorldSource {
first: Box<dyn WorldSource>,
fallback: Box<dyn WorldSource>,
}
impl WorldSource for FallbackWorldSource {
fn queue_load(&mut self, pos: ChunkPosition) {
self.first.queue_load(pos);
}
fn poll_loaded_chunk(&mut self) -> Option<LoadedChunk> {
self.first
.poll_loaded_chunk()
.map(|chunk| {
if matches!(
&chunk.result,
ChunkLoadResult::Error(_) | ChunkLoadResult::Missing
) {
self.fallback.queue_load(chunk.pos);
log::trace!(
"Chunk load falling back (failure cause: {:?})",
chunk.result
);
None
} else {
Some(chunk)
}
})
.flatten()
.or_else(|| self.fallback.poll_loaded_chunk())
}
}