use crate::{Face, VoxelError};
use std::collections::HashMap;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct BlockId(u16);
impl BlockId {
pub const AIR: Self = Self(0);
pub const fn raw(self) -> u16 {
self.0
}
pub const fn from_raw(raw: u16) -> Self {
Self(raw)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct TileId(pub u16);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CollisionKind {
None,
Solid,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RenderKind {
Invisible,
Opaque,
Cutout,
Transparent,
}
#[derive(Clone, Debug, PartialEq)]
pub struct BlockDef {
pub name: String,
pub collision: CollisionKind,
pub render: RenderKind,
pub hardness: Option<f32>,
pub textures: [TileId; 6],
}
impl BlockDef {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
collision: CollisionKind::Solid,
render: RenderKind::Opaque,
hardness: Some(1.0),
textures: [TileId(0); 6],
}
}
pub fn texture(&self, face: Face) -> TileId {
self.textures[face.index()]
}
}
pub struct BlockRegistry {
definitions: Vec<BlockDef>,
names: HashMap<String, BlockId>,
}
impl Default for BlockRegistry {
fn default() -> Self {
Self::new()
}
}
impl BlockRegistry {
pub fn new() -> Self {
let air = BlockDef {
name: "air".into(),
collision: CollisionKind::None,
render: RenderKind::Invisible,
hardness: Some(0.0),
textures: [TileId(0); 6],
};
Self {
names: HashMap::from([(air.name.clone(), BlockId::AIR)]),
definitions: vec![air],
}
}
pub fn register(&mut self, definition: BlockDef) -> Result<BlockId, VoxelError> {
if definition.name.is_empty()
|| definition.name.len() > 128
|| !definition
.name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"_.:/-".contains(&c))
|| definition
.hardness
.is_some_and(|h| !h.is_finite() || h < 0.0)
{
return Err(VoxelError::InvalidDefinition);
}
if self.names.contains_key(&definition.name) {
return Err(VoxelError::DuplicateName);
}
let raw = u16::try_from(self.definitions.len()).map_err(|_| VoxelError::RegistryFull)?;
self.definitions
.try_reserve(1)
.map_err(|_| VoxelError::Allocation)?;
self.names
.try_reserve(1)
.map_err(|_| VoxelError::Allocation)?;
let mut key = String::new();
key.try_reserve_exact(definition.name.len())
.map_err(|_| VoxelError::Allocation)?;
key.push_str(&definition.name);
let id = BlockId(raw);
self.definitions.push(definition);
self.names.insert(key, id);
Ok(id)
}
pub fn get(&self, id: BlockId) -> Option<&BlockDef> {
self.definitions.get(usize::from(id.raw()))
}
pub fn id(&self, name: &str) -> Option<BlockId> {
self.names.get(name).copied()
}
pub fn len(&self) -> usize {
self.definitions.len()
}
pub fn is_empty(&self) -> bool {
self.definitions.is_empty()
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = (BlockId, &BlockDef)> {
self.definitions
.iter()
.enumerate()
.map(|(i, d)| (BlockId(i as u16), d))
}
}