use crate::{BlockId, BlockPos, BlockRegistry, CHUNK_VOLUME, ChunkPos, Face, LocalPos, VoxelError};
use std::{collections::HashMap, sync::Arc};
pub struct Chunk {
registry: Arc<BlockRegistry>,
blocks: Box<[BlockId]>,
revision: u64,
saved_revision: Option<u64>,
}
impl std::fmt::Debug for Chunk {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Chunk")
.field("revision", &self.revision)
.field("saved_revision", &self.saved_revision)
.field("cell_count", &self.blocks.len())
.finish_non_exhaustive()
}
}
#[derive(Debug)]
pub struct ChunkInsertError {
pub error: VoxelError,
pub chunk: Chunk,
}
impl std::fmt::Display for ChunkInsertError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.error.fmt(f)
}
}
impl std::error::Error for ChunkInsertError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.error)
}
}
impl Chunk {
pub fn filled(registry: Arc<BlockRegistry>, block: BlockId) -> Result<Self, VoxelError> {
if registry.get(block).is_none() {
return Err(VoxelError::UnknownBlock(block));
}
let mut blocks = Vec::new();
blocks
.try_reserve_exact(CHUNK_VOLUME)
.map_err(|_| VoxelError::Allocation)?;
blocks.resize(CHUNK_VOLUME, block);
Ok(Self {
registry,
blocks: blocks.into_boxed_slice(),
revision: 0,
saved_revision: None,
})
}
pub fn from_blocks(
registry: Arc<BlockRegistry>,
blocks: Vec<BlockId>,
) -> Result<Self, VoxelError> {
if blocks.len() != CHUNK_VOLUME {
return Err(VoxelError::InvalidChunkLength);
}
if let Some(&id) = blocks.iter().find(|&&id| registry.get(id).is_none()) {
return Err(VoxelError::UnknownBlock(id));
}
Ok(Self {
registry,
blocks: blocks.into_boxed_slice(),
revision: 0,
saved_revision: None,
})
}
pub fn registry(&self) -> &BlockRegistry {
&self.registry
}
pub fn get(&self, local: LocalPos) -> BlockId {
self.blocks[local.index()]
}
pub fn blocks(&self) -> &[BlockId] {
&self.blocks
}
pub fn revision(&self) -> u64 {
self.revision
}
pub fn is_dirty(&self) -> bool {
self.saved_revision != Some(self.revision)
}
pub fn mark_saved(&mut self, revision: u64) -> bool {
if revision != self.revision {
return false;
}
self.saved_revision = Some(revision);
true
}
pub fn set(&mut self, local: LocalPos, block: BlockId) -> Result<Option<BlockId>, VoxelError> {
if self.registry.get(block).is_none() {
return Err(VoxelError::UnknownBlock(block));
}
let old = self.get(local);
if old == block {
return Ok(None);
}
let next = self
.revision
.checked_add(1)
.ok_or(VoxelError::RevisionExhausted)?;
self.blocks[local.index()] = block;
self.revision = next;
Ok(Some(old))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ChunkStamp {
pub generation: u64,
pub revision: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DirtyChunks {
positions: [ChunkPos; 4],
len: u8,
}
impl DirtyChunks {
fn for_edit(pos: ChunkPos, local: LocalPos) -> Self {
let mut dirty = Self {
positions: [pos; 4],
len: 1,
};
let borders = [
local.x() == 0,
local.x() == 15,
local.y() == 0,
local.y() == 15,
local.z() == 0,
local.z() == 15,
];
for (face, touches) in Face::ALL.into_iter().zip(borders) {
if touches && let Some(neighbor) = pos.neighbor(face) {
dirty.positions[usize::from(dirty.len)] = neighbor;
dirty.len += 1;
}
}
dirty
}
pub fn as_slice(&self) -> &[ChunkPos] {
&self.positions[..usize::from(self.len)]
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockEdit {
pub position: BlockPos,
pub previous: BlockId,
pub current: BlockId,
pub stamp: ChunkStamp,
pub affected_chunks: DirtyChunks,
}
struct Resident {
chunk: Chunk,
generation: u64,
}
pub struct VoxelWorld {
pub(crate) identity: Arc<()>,
registry: Arc<BlockRegistry>,
chunks: HashMap<ChunkPos, Resident>,
max_chunks: usize,
generation: u64,
}
impl VoxelWorld {
pub fn new(registry: Arc<BlockRegistry>, max_chunks: usize) -> Self {
Self {
identity: Arc::new(()),
registry,
chunks: HashMap::new(),
max_chunks,
generation: 0,
}
}
pub fn registry(&self) -> &BlockRegistry {
&self.registry
}
pub fn shared_registry(&self) -> Arc<BlockRegistry> {
self.registry.clone()
}
pub fn len(&self) -> usize {
self.chunks.len()
}
pub fn is_empty(&self) -> bool {
self.chunks.is_empty()
}
pub fn capacity(&self) -> usize {
self.max_chunks
}
pub fn chunk(&self, pos: ChunkPos) -> Option<&Chunk> {
self.chunks.get(&pos).map(|c| &c.chunk)
}
pub fn chunk_with_stamp(&self, pos: ChunkPos) -> Option<(&Chunk, ChunkStamp)> {
self.chunks.get(&pos).map(|c| {
(
&c.chunk,
ChunkStamp {
generation: c.generation,
revision: c.chunk.revision(),
},
)
})
}
pub fn stamp(&self, pos: ChunkPos) -> Option<ChunkStamp> {
self.chunks.get(&pos).map(|c| ChunkStamp {
generation: c.generation,
revision: c.chunk.revision(),
})
}
pub fn chunks(&self) -> impl Iterator<Item = (ChunkPos, &Chunk)> {
self.chunks.iter().map(|(&pos, c)| (pos, &c.chunk))
}
pub fn insert_chunk(
&mut self,
pos: ChunkPos,
chunk: Chunk,
) -> Result<Option<Chunk>, ChunkInsertError> {
let admission = (|| {
pos.origin()?;
if !Arc::ptr_eq(&self.registry, &chunk.registry) {
return Err(VoxelError::RegistryMismatch);
}
let replacing = self.chunks.contains_key(&pos);
if !replacing && self.chunks.len() >= self.max_chunks {
return Err(VoxelError::WorldFull);
}
let generation = self
.generation
.checked_add(1)
.ok_or(VoxelError::RevisionExhausted)?;
if !replacing {
self.chunks
.try_reserve(1)
.map_err(|_| VoxelError::Allocation)?;
}
Ok(generation)
})();
let generation = match admission {
Ok(generation) => generation,
Err(error) => return Err(ChunkInsertError { error, chunk }),
};
let previous = self.chunks.insert(pos, Resident { chunk, generation });
self.generation = generation;
Ok(previous.map(|c| c.chunk))
}
pub fn remove_chunk(&mut self, pos: ChunkPos) -> Option<Chunk> {
self.chunks.remove(&pos).map(|c| c.chunk)
}
pub fn block(&self, pos: BlockPos) -> Option<BlockId> {
let (chunk, local) = pos.split();
self.chunk(chunk).map(|c| c.get(local))
}
pub fn set_block(
&mut self,
position: BlockPos,
block: BlockId,
) -> Result<Option<BlockEdit>, VoxelError> {
let (pos, local) = position.split();
let resident = self
.chunks
.get_mut(&pos)
.ok_or(VoxelError::MissingChunk(pos))?;
let Some(previous) = resident.chunk.set(local, block)? else {
return Ok(None);
};
Ok(Some(BlockEdit {
position,
previous,
current: block,
stamp: ChunkStamp {
generation: resident.generation,
revision: resident.chunk.revision(),
},
affected_chunks: DirtyChunks::for_edit(pos, local),
}))
}
pub fn mark_saved(&mut self, pos: ChunkPos, stamp: ChunkStamp) -> bool {
let Some(resident) = self.chunks.get_mut(&pos) else {
return false;
};
resident.generation == stamp.generation && resident.chunk.mark_saved(stamp.revision)
}
}
#[cfg(test)]
mod tests;